blob: 55136e3a3ce59e846ec31956639aab8b8a85e889 [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++]}}};
Victor Leschukdb689112017-08-30 11:31:56 +00002488 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002489
Richard Smith0f99d6a2015-08-09 08:48:41 +00002490 // If our client can't cope with us being out of date, we can't cope with
2491 // our dependency being missing.
2492 unsigned Capabilities = ClientLoadCapabilities;
2493 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2494 Capabilities &= ~ARR_Missing;
2495
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002497 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2498 Loaded, StoredSize, StoredModTime,
2499 StoredSignature, Capabilities);
2500
2501 // If we diagnosed a problem, produce a backtrace.
2502 if (isDiagnosedResult(Result, Capabilities))
2503 Diag(diag::note_module_file_imported_by)
2504 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2505
2506 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 case Failure: return Failure;
2508 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002509 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 case OutOfDate: return OutOfDate;
2511 case VersionMismatch: return VersionMismatch;
2512 case ConfigurationMismatch: return ConfigurationMismatch;
2513 case HadErrors: return HadErrors;
2514 case Success: break;
2515 }
2516 }
2517 break;
2518 }
2519
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 case ORIGINAL_FILE:
2521 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002522 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002524 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 break;
2526
2527 case ORIGINAL_FILE_ID:
2528 F.OriginalSourceFileID = FileID::get(Record[0]);
2529 break;
2530
2531 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002532 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 break;
2534
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002535 case MODULE_NAME:
2536 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002537 if (Listener)
2538 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002539
2540 // Validate the AST as soon as we have a name so we can exit early on
2541 // failure.
2542 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2543 return Result;
2544
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002545 break;
2546
Richard Smith223d3f22014-12-06 03:21:08 +00002547 case MODULE_DIRECTORY: {
2548 assert(!F.ModuleName.empty() &&
2549 "MODULE_DIRECTORY found before MODULE_NAME");
2550 // If we've already loaded a module map file covering this module, we may
2551 // have a better path for it (relative to the current build).
2552 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2553 if (M && M->Directory) {
2554 // If we're implicitly loading a module, the base directory can't
2555 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002556 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002557 const DirectoryEntry *BuildDir =
2558 PP.getFileManager().getDirectory(Blob);
2559 if (!BuildDir || BuildDir != M->Directory) {
2560 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2561 Diag(diag::err_imported_module_relocated)
2562 << F.ModuleName << Blob << M->Directory->getName();
2563 return OutOfDate;
2564 }
2565 }
2566 F.BaseDirectory = M->Directory->getName();
2567 } else {
2568 F.BaseDirectory = Blob;
2569 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002570 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002571 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002572
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002573 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002574 if (ASTReadResult Result =
2575 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2576 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002577 break;
2578
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002579 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002580 NumInputs = Record[0];
2581 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002582 F.InputFileOffsets =
2583 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002584 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002585 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 break;
2587 }
2588 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002589}
2590
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591ASTReader::ASTReadResult
2592ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002593 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002594
2595 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2596 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599
2600 // Read all of the records and blocks for the AST file.
2601 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002602 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002604
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 switch (Entry.Kind) {
2606 case llvm::BitstreamEntry::Error:
2607 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002609 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002610 // Outside of C++, we do not store a lookup map for the translation unit.
2611 // Instead, mark it as needing a lookup map to be built if this module
2612 // contains any declarations lexically within it (which it always does!).
2613 // This usually has no cost, since we very rarely need the lookup map for
2614 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002615 if (ASTContext *Ctx = ContextObj) {
2616 DeclContext *DC = Ctx->getTranslationUnitDecl();
2617 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2618 DC->setMustBuildLookupTable();
2619 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002620
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623 case llvm::BitstreamEntry::SubBlock:
2624 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 case DECLTYPES_BLOCK_ID:
2626 // We lazily load the decls block, but we want to set up the
2627 // DeclsCursor cursor to point into it. Clone our current bitcode
2628 // cursor to it, enter the block and read the abbrevs in that block.
2629 // With the main cursor, we just skip over it.
2630 F.DeclsCursor = Stream;
2631 if (Stream.SkipBlock() || // Skip with the main cursor.
2632 // Read the abbrevs.
2633 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2634 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002635 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 }
2637 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002638
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 case PREPROCESSOR_BLOCK_ID:
2640 F.MacroCursor = Stream;
2641 if (!PP.getExternalSource())
2642 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 if (Stream.SkipBlock() ||
2645 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2646 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002647 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 }
2649 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2650 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002651
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 case PREPROCESSOR_DETAIL_BLOCK_ID:
2653 F.PreprocessorDetailCursor = Stream;
2654 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002657 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002661 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002662
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 if (!PP.getPreprocessingRecord())
2664 PP.createPreprocessingRecord();
2665 if (!PP.getPreprocessingRecord()->getExternalSource())
2666 PP.getPreprocessingRecord()->SetExternalSource(*this);
2667 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 case SOURCE_MANAGER_BLOCK_ID:
2670 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002671 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002673
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002675 if (ASTReadResult Result =
2676 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002677 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002681 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 if (Stream.SkipBlock() ||
2683 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2684 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002685 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 }
2687 CommentsCursors.push_back(std::make_pair(C, &F));
2688 break;
2689 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002692 if (Stream.SkipBlock()) {
2693 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002694 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002695 }
2696 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 }
2698 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002699
Chris Lattnere7b154b2013-01-19 21:39:22 +00002700 case llvm::BitstreamEntry::Record:
2701 // The interesting case.
2702 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 }
2704
2705 // Read and process a record.
2706 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002707 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002708 auto RecordType =
2709 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2710
2711 // If we're not loading an AST context, we don't care about most records.
2712 if (!ContextObj) {
2713 switch (RecordType) {
2714 case IDENTIFIER_TABLE:
2715 case IDENTIFIER_OFFSET:
2716 case INTERESTING_IDENTIFIERS:
2717 case STATISTICS:
2718 case PP_CONDITIONAL_STACK:
2719 case PP_COUNTER_VALUE:
2720 case SOURCE_LOCATION_OFFSETS:
2721 case MODULE_OFFSET_MAP:
2722 case SOURCE_MANAGER_LINE_TABLE:
2723 case SOURCE_LOCATION_PRELOADS:
2724 case PPD_ENTITIES_OFFSETS:
2725 case HEADER_SEARCH_TABLE:
2726 case IMPORTED_MODULES:
2727 case MACRO_OFFSET:
2728 break;
2729 default:
2730 continue;
2731 }
2732 }
2733
2734 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 default: // Default behavior: ignore.
2736 break;
2737
2738 case TYPE_OFFSET: {
2739 if (F.LocalNumTypes != 0) {
2740 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002741 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002743 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 F.LocalNumTypes = Record[0];
2745 unsigned LocalBaseTypeIndex = Record[1];
2746 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002747
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 if (F.LocalNumTypes > 0) {
2749 // Introduce the global -> local mapping for types within this module.
2750 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 // Introduce the local -> global mapping for types within this module.
2753 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002754 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002756
2757 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 }
2759 break;
2760 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 case DECL_OFFSET: {
2763 if (F.LocalNumDecls != 0) {
2764 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002765 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002767 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 F.LocalNumDecls = Record[0];
2769 unsigned LocalBaseDeclID = Record[1];
2770 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002771
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002773 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 // module.
2775 GlobalDeclMap.insert(
2776 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002777
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 // Introduce the local -> global mapping for declarations within this
2779 // module.
2780 F.DeclRemap.insertOrReplace(
2781 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002782
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 // Introduce the global -> local mapping for declarations within this
2784 // module.
2785 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002786
Ben Langmuir52ca6782014-10-20 16:27:32 +00002787 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 break;
2790 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002791
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002793 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002794 LexicalContents Contents(
2795 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2796 Blob.data()),
2797 static_cast<unsigned int>(Blob.size() / 4));
2798 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 TU->setHasExternalLexicalStorage(true);
2800 break;
2801 }
2802
2803 case UPDATE_VISIBLE: {
2804 unsigned Idx = 0;
2805 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002806 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002807 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002808 // If we've already loaded the decl, perform the updates when we finish
2809 // loading this block.
2810 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002811 PendingUpdateRecords.push_back(
2812 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 break;
2814 }
2815
2816 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002817 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002819 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2820 (const unsigned char *)F.IdentifierTableData + Record[0],
2821 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2822 (const unsigned char *)F.IdentifierTableData,
2823 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002824
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2826 }
2827 break;
2828
2829 case IDENTIFIER_OFFSET: {
2830 if (F.LocalNumIdentifiers != 0) {
2831 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002832 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002834 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 F.LocalNumIdentifiers = Record[0];
2836 unsigned LocalBaseIdentifierID = Record[1];
2837 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002838
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 if (F.LocalNumIdentifiers > 0) {
2840 // Introduce the global -> local mapping for identifiers within this
2841 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002842 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002844
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 // Introduce the local -> global mapping for identifiers within this
2846 // module.
2847 F.IdentifierRemap.insertOrReplace(
2848 std::make_pair(LocalBaseIdentifierID,
2849 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002850
Ben Langmuir52ca6782014-10-20 16:27:32 +00002851 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2852 + F.LocalNumIdentifiers);
2853 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 break;
2855 }
2856
Richard Smith33e0f7e2015-07-22 02:08:40 +00002857 case INTERESTING_IDENTIFIERS:
2858 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2859 break;
2860
Ben Langmuir332aafe2014-01-31 01:06:56 +00002861 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002862 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2863 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002865 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 break;
2867
David Blaikie9ffe5a32017-01-30 05:00:26 +00002868 case MODULAR_CODEGEN_DECLS:
2869 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2870 // them (ie: if we're not codegenerating this module).
2871 if (F.Kind == MK_MainFile)
2872 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2873 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2874 break;
2875
Guy Benyei11169dd2012-12-18 14:30:41 +00002876 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002877 if (SpecialTypes.empty()) {
2878 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2879 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2880 break;
2881 }
2882
2883 if (SpecialTypes.size() != Record.size()) {
2884 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002885 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002886 }
2887
2888 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2889 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2890 if (!SpecialTypes[I])
2891 SpecialTypes[I] = ID;
2892 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2893 // merge step?
2894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 break;
2896
2897 case STATISTICS:
2898 TotalNumStatements += Record[0];
2899 TotalNumMacros += Record[1];
2900 TotalLexicalDeclContexts += Record[2];
2901 TotalVisibleDeclContexts += Record[3];
2902 break;
2903
2904 case UNUSED_FILESCOPED_DECLS:
2905 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2906 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2907 break;
2908
2909 case DELEGATING_CTORS:
2910 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2911 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2912 break;
2913
2914 case WEAK_UNDECLARED_IDENTIFIERS:
2915 if (Record.size() % 4 != 0) {
2916 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002919
2920 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 // files. This isn't the way to do it :)
2922 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002923
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 // Translate the weak, undeclared identifiers into global IDs.
2925 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2926 WeakUndeclaredIdentifiers.push_back(
2927 getGlobalIdentifierID(F, Record[I++]));
2928 WeakUndeclaredIdentifiers.push_back(
2929 getGlobalIdentifierID(F, Record[I++]));
2930 WeakUndeclaredIdentifiers.push_back(
2931 ReadSourceLocation(F, Record, I).getRawEncoding());
2932 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2933 }
2934 break;
2935
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002937 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 F.LocalNumSelectors = Record[0];
2939 unsigned LocalBaseSelectorID = Record[1];
2940 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002943 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 // module.
2945 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002946
2947 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 // module.
2949 F.SelectorRemap.insertOrReplace(
2950 std::make_pair(LocalBaseSelectorID,
2951 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002952
2953 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 }
2955 break;
2956 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002957
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002959 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 if (Record[0])
2961 F.SelectorLookupTable
2962 = ASTSelectorLookupTable::Create(
2963 F.SelectorLookupTableData + Record[0],
2964 F.SelectorLookupTableData,
2965 ASTSelectorLookupTrait(*this, F));
2966 TotalNumMethodPoolEntries += Record[1];
2967 break;
2968
2969 case REFERENCED_SELECTOR_POOL:
2970 if (!Record.empty()) {
2971 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002972 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 Record[Idx++]));
2974 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2975 getRawEncoding());
2976 }
2977 }
2978 break;
2979
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002980 case PP_CONDITIONAL_STACK:
2981 if (!Record.empty()) {
2982 SmallVector<PPConditionalInfo, 4> ConditionalStack;
2983 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2984 auto Loc = ReadSourceLocation(F, Record, Idx);
2985 bool WasSkipping = Record[Idx++];
2986 bool FoundNonSkip = Record[Idx++];
2987 bool FoundElse = Record[Idx++];
2988 ConditionalStack.push_back(
2989 {Loc, WasSkipping, FoundNonSkip, FoundElse});
2990 }
2991 PP.setReplayablePreambleConditionalStack(ConditionalStack);
2992 }
2993 break;
2994
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 case PP_COUNTER_VALUE:
2996 if (!Record.empty() && Listener)
2997 Listener->ReadCounter(F, Record[0]);
2998 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002999
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003001 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 F.NumFileSortedDecls = Record[0];
3003 break;
3004
3005 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003006 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 F.LocalNumSLocEntries = Record[0];
3008 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003009 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003010 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003012 if (!F.SLocEntryBaseID) {
3013 Error("ran out of source locations");
3014 break;
3015 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 // Make our entry in the range map. BaseID is negative and growing, so
3017 // we invert it. Because we invert it, though, we need the other end of
3018 // the range.
3019 unsigned RangeStart =
3020 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3021 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3022 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3023
3024 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3025 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3026 GlobalSLocOffsetMap.insert(
3027 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3028 - SLocSpaceSize,&F));
3029
3030 // Initialize the remapping table.
3031 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003032 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003034 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 TotalNumSLocEntries += F.LocalNumSLocEntries;
3038 break;
3039 }
3040
Richard Smith37a93df2017-02-18 00:32:02 +00003041 case MODULE_OFFSET_MAP:
3042 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003044
3045 case SOURCE_MANAGER_LINE_TABLE:
3046 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003047 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 break;
3049
3050 case SOURCE_LOCATION_PRELOADS: {
3051 // Need to transform from the local view (1-based IDs) to the global view,
3052 // which is based off F.SLocEntryBaseID.
3053 if (!F.PreloadSLocEntries.empty()) {
3054 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003055 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003057
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 F.PreloadSLocEntries.swap(Record);
3059 break;
3060 }
3061
3062 case EXT_VECTOR_DECLS:
3063 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3064 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3065 break;
3066
3067 case VTABLE_USES:
3068 if (Record.size() % 3 != 0) {
3069 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003072
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 // Later tables overwrite earlier ones.
3074 // FIXME: Modules will have some trouble with this. This is clearly not
3075 // the right way to do this.
3076 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003077
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3079 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3080 VTableUses.push_back(
3081 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3082 VTableUses.push_back(Record[Idx++]);
3083 }
3084 break;
3085
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 case PENDING_IMPLICIT_INSTANTIATIONS:
3087 if (PendingInstantiations.size() % 2 != 0) {
3088 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003089 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 }
3091
3092 if (Record.size() % 2 != 0) {
3093 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003094 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 }
3096
3097 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3098 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3099 PendingInstantiations.push_back(
3100 ReadSourceLocation(F, Record, I).getRawEncoding());
3101 }
3102 break;
3103
3104 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003105 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003106 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003107 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3110 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3111 break;
3112
3113 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003114 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3115 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3116 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003117
3118 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 unsigned StartingID;
3121 if (!PP.getPreprocessingRecord())
3122 PP.createPreprocessingRecord();
3123 if (!PP.getPreprocessingRecord()->getExternalSource())
3124 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003125 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003127 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 F.BasePreprocessedEntityID = StartingID;
3129
3130 if (F.NumPreprocessedEntities > 0) {
3131 // Introduce the global -> local mapping for preprocessed entities in
3132 // this module.
3133 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003134
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 // Introduce the local -> global mapping for preprocessed entities in
3136 // this module.
3137 F.PreprocessedEntityRemap.insertOrReplace(
3138 std::make_pair(LocalBasePreprocessedEntityID,
3139 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3140 }
3141
3142 break;
3143 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 case DECL_UPDATE_OFFSETS: {
3146 if (Record.size() % 2 != 0) {
3147 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003148 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003150 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3151 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3152 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3153
3154 // If we've already loaded the decl, perform the updates when we finish
3155 // loading this block.
3156 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003157 PendingUpdateRecords.push_back(
3158 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 break;
3161 }
3162
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 case OBJC_CATEGORIES_MAP: {
3164 if (F.LocalNumObjCCategoriesInMap != 0) {
3165 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003166 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003168
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003170 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 break;
3172 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003173
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 case OBJC_CATEGORIES:
3175 F.ObjCCategories.swap(Record);
3176 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003177
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 case CUDA_SPECIAL_DECL_REFS:
3179 // Later tables overwrite earlier ones.
3180 // FIXME: Modules will have trouble with this.
3181 CUDASpecialDeclRefs.clear();
3182 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3183 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3184 break;
3185
3186 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003187 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 if (Record[0]) {
3190 F.HeaderFileInfoTable
3191 = HeaderFileInfoLookupTable::Create(
3192 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3193 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003194 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003196 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 PP.getHeaderSearchInfo().SetExternalSource(this);
3199 if (!PP.getHeaderSearchInfo().getExternalLookup())
3200 PP.getHeaderSearchInfo().SetExternalLookup(this);
3201 }
3202 break;
3203 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003204
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 case FP_PRAGMA_OPTIONS:
3206 // Later tables overwrite earlier ones.
3207 FPPragmaOptions.swap(Record);
3208 break;
3209
3210 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003211 for (unsigned I = 0, E = Record.size(); I != E; ) {
3212 auto Name = ReadString(Record, I);
3213 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003214 Opt.Supported = Record[I++] != 0;
3215 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003216 Opt.Avail = Record[I++];
3217 Opt.Core = Record[I++];
3218 }
3219 break;
3220
3221 case OPENCL_EXTENSION_TYPES:
3222 for (unsigned I = 0, E = Record.size(); I != E;) {
3223 auto TypeID = static_cast<::TypeID>(Record[I++]);
3224 auto *Type = GetType(TypeID).getTypePtr();
3225 auto NumExt = static_cast<unsigned>(Record[I++]);
3226 for (unsigned II = 0; II != NumExt; ++II) {
3227 auto Ext = ReadString(Record, I);
3228 OpenCLTypeExtMap[Type].insert(Ext);
3229 }
3230 }
3231 break;
3232
3233 case OPENCL_EXTENSION_DECLS:
3234 for (unsigned I = 0, E = Record.size(); I != E;) {
3235 auto DeclID = static_cast<::DeclID>(Record[I++]);
3236 auto *Decl = GetDecl(DeclID);
3237 auto NumExt = static_cast<unsigned>(Record[I++]);
3238 for (unsigned II = 0; II != NumExt; ++II) {
3239 auto Ext = ReadString(Record, I);
3240 OpenCLDeclExtMap[Decl].insert(Ext);
3241 }
3242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003243 break;
3244
3245 case TENTATIVE_DEFINITIONS:
3246 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3247 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3248 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 case KNOWN_NAMESPACES:
3251 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3252 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3253 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003254
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003255 case UNDEFINED_BUT_USED:
3256 if (UndefinedButUsed.size() % 2 != 0) {
3257 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003258 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003259 }
3260
3261 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003262 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003263 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003264 }
3265 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003266 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3267 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003268 ReadSourceLocation(F, Record, I).getRawEncoding());
3269 }
3270 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003271 case DELETE_EXPRS_TO_ANALYZE:
3272 for (unsigned I = 0, N = Record.size(); I != N;) {
3273 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3274 const uint64_t Count = Record[I++];
3275 DelayedDeleteExprs.push_back(Count);
3276 for (uint64_t C = 0; C < Count; ++C) {
3277 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3278 bool IsArrayForm = Record[I++] == 1;
3279 DelayedDeleteExprs.push_back(IsArrayForm);
3280 }
3281 }
3282 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003283
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003285 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 // If we aren't loading a module (which has its own exports), make
3287 // all of the imported modules visible.
3288 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003289 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3290 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3291 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003292 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003293 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003294 if (DeserializationListener)
3295 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3296 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 }
3298 }
3299 break;
3300 }
3301
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 case MACRO_OFFSET: {
3303 if (F.LocalNumMacros != 0) {
3304 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003305 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003307 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003308 F.LocalNumMacros = Record[0];
3309 unsigned LocalBaseMacroID = Record[1];
3310 F.BaseMacroID = getTotalNumMacros();
3311
3312 if (F.LocalNumMacros > 0) {
3313 // Introduce the global -> local mapping for macros within this module.
3314 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3315
3316 // Introduce the local -> global mapping for macros within this module.
3317 F.MacroRemap.insertOrReplace(
3318 std::make_pair(LocalBaseMacroID,
3319 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003320
3321 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003322 }
3323 break;
3324 }
3325
Richard Smithe40f2ba2013-08-07 21:41:30 +00003326 case LATE_PARSED_TEMPLATE: {
3327 LateParsedTemplates.append(Record.begin(), Record.end());
3328 break;
3329 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003330
3331 case OPTIMIZE_PRAGMA_OPTIONS:
3332 if (Record.size() != 1) {
3333 Error("invalid pragma optimize record");
3334 return Failure;
3335 }
3336 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3337 break;
Nico Weber72889432014-09-06 01:25:55 +00003338
Nico Weber779355f2016-03-02 23:22:00 +00003339 case MSSTRUCT_PRAGMA_OPTIONS:
3340 if (Record.size() != 1) {
3341 Error("invalid pragma ms_struct record");
3342 return Failure;
3343 }
3344 PragmaMSStructState = Record[0];
3345 break;
3346
Nico Weber42932312016-03-03 00:17:35 +00003347 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3348 if (Record.size() != 2) {
3349 Error("invalid pragma ms_struct record");
3350 return Failure;
3351 }
3352 PragmaMSPointersToMembersState = Record[0];
3353 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3354 break;
3355
Nico Weber72889432014-09-06 01:25:55 +00003356 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3357 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3358 UnusedLocalTypedefNameCandidates.push_back(
3359 getGlobalDeclID(F, Record[I]));
3360 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003361
3362 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3363 if (Record.size() != 1) {
3364 Error("invalid cuda pragma options record");
3365 return Failure;
3366 }
3367 ForceCUDAHostDeviceDepth = Record[0];
3368 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003369
3370 case PACK_PRAGMA_OPTIONS: {
3371 if (Record.size() < 3) {
3372 Error("invalid pragma pack record");
3373 return Failure;
3374 }
3375 PragmaPackCurrentValue = Record[0];
3376 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3377 unsigned NumStackEntries = Record[2];
3378 unsigned Idx = 3;
3379 // Reset the stack when importing a new module.
3380 PragmaPackStack.clear();
3381 for (unsigned I = 0; I < NumStackEntries; ++I) {
3382 PragmaPackStackEntry Entry;
3383 Entry.Value = Record[Idx++];
3384 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003385 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003386 PragmaPackStrings.push_back(ReadString(Record, Idx));
3387 Entry.SlotLabel = PragmaPackStrings.back();
3388 PragmaPackStack.push_back(Entry);
3389 }
3390 break;
3391 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 }
3393 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003394}
3395
Richard Smith37a93df2017-02-18 00:32:02 +00003396void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3397 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3398
3399 // Additional remapping information.
3400 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3401 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3402 F.ModuleOffsetMap = StringRef();
3403
3404 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3405 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3406 F.SLocRemap.insert(std::make_pair(0U, 0));
3407 F.SLocRemap.insert(std::make_pair(2U, 1));
3408 }
3409
3410 // Continuous range maps we may be updating in our module.
3411 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3412 RemapBuilder;
3413 RemapBuilder SLocRemap(F.SLocRemap);
3414 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3415 RemapBuilder MacroRemap(F.MacroRemap);
3416 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3417 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3418 RemapBuilder SelectorRemap(F.SelectorRemap);
3419 RemapBuilder DeclRemap(F.DeclRemap);
3420 RemapBuilder TypeRemap(F.TypeRemap);
3421
3422 while (Data < DataEnd) {
Victor Leschukdb689112017-08-30 11:31:56 +00003423 // FIXME: Looking up dependency modules by filename is horrible.
Richard Smith37a93df2017-02-18 00:32:02 +00003424 using namespace llvm::support;
3425 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3426 StringRef Name = StringRef((const char*)Data, Len);
3427 Data += Len;
Victor Leschukdb689112017-08-30 11:31:56 +00003428 ModuleFile *OM = ModuleMgr.lookup(Name);
Richard Smith37a93df2017-02-18 00:32:02 +00003429 if (!OM) {
3430 std::string Msg =
3431 "SourceLocation remap refers to unknown module, cannot find ";
3432 Msg.append(Name);
3433 Error(Msg);
3434 return;
3435 }
3436
3437 uint32_t SLocOffset =
3438 endian::readNext<uint32_t, little, unaligned>(Data);
3439 uint32_t IdentifierIDOffset =
3440 endian::readNext<uint32_t, little, unaligned>(Data);
3441 uint32_t MacroIDOffset =
3442 endian::readNext<uint32_t, little, unaligned>(Data);
3443 uint32_t PreprocessedEntityIDOffset =
3444 endian::readNext<uint32_t, little, unaligned>(Data);
3445 uint32_t SubmoduleIDOffset =
3446 endian::readNext<uint32_t, little, unaligned>(Data);
3447 uint32_t SelectorIDOffset =
3448 endian::readNext<uint32_t, little, unaligned>(Data);
3449 uint32_t DeclIDOffset =
3450 endian::readNext<uint32_t, little, unaligned>(Data);
3451 uint32_t TypeIndexOffset =
3452 endian::readNext<uint32_t, little, unaligned>(Data);
3453
3454 uint32_t None = std::numeric_limits<uint32_t>::max();
3455
3456 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3457 RemapBuilder &Remap) {
3458 if (Offset != None)
3459 Remap.insert(std::make_pair(Offset,
3460 static_cast<int>(BaseOffset - Offset)));
3461 };
3462 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3463 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3464 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3465 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3466 PreprocessedEntityRemap);
3467 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3468 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3469 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3470 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3471
3472 // Global -> local mappings.
3473 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3474 }
3475}
3476
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003477ASTReader::ASTReadResult
3478ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3479 const ModuleFile *ImportedBy,
3480 unsigned ClientLoadCapabilities) {
3481 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003482 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003483
3484 // Try to resolve ModuleName in the current header search context and
3485 // verify that it is found in the same module map file as we saved. If the
3486 // top-level AST file is a main file, skip this check because there is no
3487 // usable header search context.
3488 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003489 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003490 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003491 // An implicitly-loaded module file should have its module listed in some
3492 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003493 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003494 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3495 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3496 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003497 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003498 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3499 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3500 // This module was defined by an imported (explicit) module.
3501 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3502 << ASTFE->getName();
3503 else
3504 // This module was built with a different module map.
3505 Diag(diag::err_imported_module_not_found)
3506 << F.ModuleName << F.FileName << ImportedBy->FileName
3507 << F.ModuleMapPath;
3508 }
3509 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003510 }
3511
Richard Smithe842a472014-10-22 02:05:46 +00003512 assert(M->Name == F.ModuleName && "found module with different name");
3513
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003514 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003515 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003516 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3517 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003518 assert(ImportedBy && "top-level import should be verified");
3519 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3520 Diag(diag::err_imported_module_modmap_changed)
3521 << F.ModuleName << ImportedBy->FileName
3522 << ModMap->getName() << F.ModuleMapPath;
3523 return OutOfDate;
3524 }
3525
3526 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3527 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3528 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003529 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003530 const FileEntry *F =
3531 FileMgr.getFile(Filename, false, false);
3532 if (F == nullptr) {
3533 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3534 Error("could not find file '" + Filename +"' referenced by AST file");
3535 return OutOfDate;
3536 }
3537 AdditionalStoredMaps.insert(F);
3538 }
3539
3540 // Check any additional module map files (e.g. module.private.modulemap)
3541 // that are not in the pcm.
3542 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3543 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3544 // Remove files that match
3545 // Note: SmallPtrSet::erase is really remove
3546 if (!AdditionalStoredMaps.erase(ModMap)) {
3547 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3548 Diag(diag::err_module_different_modmap)
3549 << F.ModuleName << /*new*/0 << ModMap->getName();
3550 return OutOfDate;
3551 }
3552 }
3553 }
3554
3555 // Check any additional module map files that are in the pcm, but not
3556 // found in header search. Cases that match are already removed.
3557 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3558 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3559 Diag(diag::err_module_different_modmap)
3560 << F.ModuleName << /*not new*/1 << ModMap->getName();
3561 return OutOfDate;
3562 }
3563 }
3564
3565 if (Listener)
3566 Listener->ReadModuleMapFile(F.ModuleMapPath);
3567 return Success;
3568}
3569
3570
Douglas Gregorc1489562013-02-12 23:36:21 +00003571/// \brief Move the given method to the back of the global list of methods.
3572static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3573 // Find the entry for this selector in the method pool.
3574 Sema::GlobalMethodPool::iterator Known
3575 = S.MethodPool.find(Method->getSelector());
3576 if (Known == S.MethodPool.end())
3577 return;
3578
3579 // Retrieve the appropriate method list.
3580 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3581 : Known->second.second;
3582 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003583 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003584 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003585 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003586 Found = true;
3587 } else {
3588 // Keep searching.
3589 continue;
3590 }
3591 }
3592
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003593 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003594 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003595 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003596 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003597 }
3598}
3599
Richard Smithde711422015-04-23 21:20:19 +00003600void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003601 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003602 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003603 bool wasHidden = D->isHidden();
3604 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003605
Richard Smith49f906a2014-03-01 00:08:04 +00003606 if (wasHidden && SemaObj) {
3607 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3608 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003609 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 }
3611 }
3612}
3613
Richard Smith49f906a2014-03-01 00:08:04 +00003614void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003615 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003616 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003618 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003619 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003621 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003622
3623 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003624 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 // there is nothing more to do.
3626 continue;
3627 }
Richard Smith49f906a2014-03-01 00:08:04 +00003628
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 if (!Mod->isAvailable()) {
3630 // Modules that aren't available cannot be made visible.
3631 continue;
3632 }
3633
3634 // Update the module's name visibility.
3635 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003636
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 // If we've already deserialized any names from this module,
3638 // mark them as visible.
3639 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3640 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003641 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003643 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003644 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3645 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003647
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003649 SmallVector<Module *, 16> Exports;
3650 Mod->getExportedModules(Exports);
3651 for (SmallVectorImpl<Module *>::iterator
3652 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3653 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003654 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003655 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003656 }
3657 }
3658}
3659
Richard Smith6561f922016-09-12 21:06:40 +00003660/// We've merged the definition \p MergedDef into the existing definition
3661/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3662/// visible.
3663void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3664 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003665 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3666 // in modules other than its owning module. We should instead give the
3667 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003668 if (Def->isHidden()) {
3669 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003670 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003671 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003672 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3673 getContext().mergeDefinitionIntoModule(
3674 Def, MergedDef->getImportedOwningModule(),
3675 /*NotifyListeners*/ false);
3676 PendingMergedDefinitionsToDeduplicate.insert(Def);
3677 } else {
3678 auto SubmoduleID = MergedDef->getOwningModuleID();
3679 assert(SubmoduleID && "hidden definition in no module");
3680 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3681 }
Richard Smith6561f922016-09-12 21:06:40 +00003682 }
3683}
3684
Douglas Gregore060e572013-01-25 01:03:03 +00003685bool ASTReader::loadGlobalIndex() {
3686 if (GlobalIndex)
3687 return false;
3688
3689 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003690 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003691 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003692
Douglas Gregore060e572013-01-25 01:03:03 +00003693 // Try to load the global index.
3694 TriedLoadingGlobalIndex = true;
3695 StringRef ModuleCachePath
3696 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3697 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003698 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003699 if (!Result.first)
3700 return true;
3701
3702 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003703 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003704 return false;
3705}
3706
3707bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003708 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003709 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3710}
3711
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003712static void updateModuleTimestamp(ModuleFile &MF) {
3713 // Overwrite the timestamp file contents so that file's mtime changes.
3714 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003715 std::error_code EC;
3716 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3717 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003718 return;
3719 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003720 OS.close();
3721 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003722}
3723
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003724/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3725/// cursor into the start of the given block ID, returning false on success and
3726/// true on failure.
3727static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003728 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003729 llvm::BitstreamEntry Entry = Cursor.advance();
3730 switch (Entry.Kind) {
3731 case llvm::BitstreamEntry::Error:
3732 case llvm::BitstreamEntry::EndBlock:
3733 return true;
3734
3735 case llvm::BitstreamEntry::Record:
3736 // Ignore top-level records.
3737 Cursor.skipRecord(Entry.ID);
3738 break;
3739
3740 case llvm::BitstreamEntry::SubBlock:
3741 if (Entry.ID == BlockID) {
3742 if (Cursor.EnterSubBlock(BlockID))
3743 return true;
3744 // Found it!
3745 return false;
3746 }
3747
3748 if (Cursor.SkipBlock())
3749 return true;
3750 }
3751 }
3752}
3753
Benjamin Kramer0772c422016-02-13 13:42:54 +00003754ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 ModuleKind Type,
3756 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003757 unsigned ClientLoadCapabilities,
3758 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003759 llvm::SaveAndRestore<SourceLocation>
3760 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3761
Richard Smithd1c46742014-04-30 02:24:17 +00003762 // Defer any pending actions until we get to the end of reading the AST file.
3763 Deserializing AnASTFile(this);
3764
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003766 unsigned PreviousGeneration = 0;
3767 if (ContextObj)
3768 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003769
3770 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003771 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003772 switch (ASTReadResult ReadResult =
3773 ReadASTCore(FileName, Type, ImportLoc,
3774 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3775 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003777 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003778 case OutOfDate:
3779 case VersionMismatch:
3780 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003781 case HadErrors: {
3782 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3783 for (const ImportedModule &IM : Loaded)
3784 LoadedSet.insert(IM.Mod);
3785
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003786 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003787 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003788 ? &PP.getHeaderSearchInfo().getModuleMap()
3789 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003790
3791 // If we find that any modules are unusable, the global index is going
3792 // to be out-of-date. Just remove it.
3793 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003794 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003796 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 case Success:
3798 break;
3799 }
3800
3801 // Here comes stuff that we only do once the entire chain is loaded.
3802
3803 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003804 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3805 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 M != MEnd; ++M) {
3807 ModuleFile &F = *M->Mod;
3808
3809 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003810 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3811 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003812
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003813 // Read the extension blocks.
3814 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3815 if (ASTReadResult Result = ReadExtensionBlock(F))
3816 return Result;
3817 }
3818
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003819 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003820 // bits of all files we've seen.
3821 F.GlobalBitOffset = TotalModulesSizeInBits;
3822 TotalModulesSizeInBits += F.SizeInBits;
3823 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003824
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 // Preload SLocEntries.
3826 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3827 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3828 // Load it through the SourceManager and don't call ReadSLocEntry()
3829 // directly because the entry may have already been loaded in which case
3830 // calling ReadSLocEntry() directly would trigger an assertion in
3831 // SourceManager.
3832 SourceMgr.getLoadedSLocEntryByID(Index);
3833 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003834
Richard Smithea741482017-05-01 22:10:47 +00003835 // Map the original source file ID into the ID space of the current
3836 // compilation.
3837 if (F.OriginalSourceFileID.isValid()) {
3838 F.OriginalSourceFileID = FileID::get(
3839 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3840 }
3841
Richard Smith33e0f7e2015-07-22 02:08:40 +00003842 // Preload all the pending interesting identifiers by marking them out of
3843 // date.
3844 for (auto Offset : F.PreloadIdentifierOffsets) {
3845 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3846 F.IdentifierTableData + Offset);
3847
3848 ASTIdentifierLookupTrait Trait(*this, F);
3849 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3850 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003851 auto &II = PP.getIdentifierTable().getOwn(Key);
3852 II.setOutOfDate(true);
3853
3854 // Mark this identifier as being from an AST file so that we can track
3855 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003856 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003857
3858 // Associate the ID with the identifier so that the writer can reuse it.
3859 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3860 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003861 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003862 }
3863
Douglas Gregor603cd862013-03-22 18:50:14 +00003864 // Setup the import locations and notify the module manager that we've
3865 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003866 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3867 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 M != MEnd; ++M) {
3869 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003870
3871 ModuleMgr.moduleFileAccepted(&F);
3872
3873 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003874 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003875 // FIXME: We assume that locations from PCH / preamble do not need
3876 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 if (!M->ImportedBy)
3878 F.ImportLoc = M->ImportLoc;
3879 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003880 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 }
3882
Richard Smithdbafb6c2017-06-29 23:23:46 +00003883 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003884 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3885 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003886 // Mark all of the identifiers in the identifier table as being out of date,
3887 // so that various accessors know to check the loaded modules when the
3888 // identifier is used.
3889 //
3890 // For C++ modules, we don't need information on many identifiers (just
3891 // those that provide macros or are poisoned), so we mark all of
3892 // the interesting ones via PreloadIdentifierOffsets.
3893 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3894 IdEnd = PP.getIdentifierTable().end();
3895 Id != IdEnd; ++Id)
3896 Id->second->setOutOfDate(true);
3897 }
Manman Rena0f31a02016-04-29 19:04:05 +00003898 // Mark selectors as out of date.
3899 for (auto Sel : SelectorGeneration)
3900 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003901
Guy Benyei11169dd2012-12-18 14:30:41 +00003902 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003903 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3904 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3906 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003907
3908 switch (Unresolved.Kind) {
3909 case UnresolvedModuleRef::Conflict:
3910 if (ResolvedMod) {
3911 Module::Conflict Conflict;
3912 Conflict.Other = ResolvedMod;
3913 Conflict.Message = Unresolved.String.str();
3914 Unresolved.Mod->Conflicts.push_back(Conflict);
3915 }
3916 continue;
3917
3918 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003920 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Douglas Gregorfb912652013-03-20 21:10:35 +00003923 case UnresolvedModuleRef::Export:
3924 if (ResolvedMod || Unresolved.IsWildcard)
3925 Unresolved.Mod->Exports.push_back(
3926 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3927 continue;
3928 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003930 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003931
Graydon Hoaree7196af2016-12-09 21:45:49 +00003932 if (Imported)
3933 Imported->append(ImportedModules.begin(),
3934 ImportedModules.end());
3935
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003936 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3937 // Might be unnecessary as use declarations are only used to build the
3938 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003939
Richard Smithdbafb6c2017-06-29 23:23:46 +00003940 if (ContextObj)
3941 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00003942
Richard Smith3d8e97e2013-10-18 06:54:39 +00003943 if (SemaObj)
3944 UpdateSema();
3945
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 if (DeserializationListener)
3947 DeserializationListener->ReaderInitialized(this);
3948
3949 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003950 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 // If this AST file is a precompiled preamble, then set the
3952 // preamble file ID of the source manager to the file source file
3953 // from which the preamble was built.
3954 if (Type == MK_Preamble) {
3955 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3956 } else if (Type == MK_MainFile) {
3957 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3958 }
3959 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003960
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // For any Objective-C class definitions we have already loaded, make sure
3962 // that we load any additional categories.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003963 if (ContextObj) {
3964 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3965 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3966 ObjCClassesLoaded[I],
3967 PreviousGeneration);
3968 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 }
Douglas Gregore060e572013-01-25 01:03:03 +00003970
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003971 if (PP.getHeaderSearchInfo()
3972 .getHeaderSearchOpts()
3973 .ModulesValidateOncePerBuildSession) {
3974 // Now we are certain that the module and all modules it depends on are
3975 // up to date. Create or update timestamp files for modules that are
3976 // located in the module cache (not for PCH files that could be anywhere
3977 // in the filesystem).
3978 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3979 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003980 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003981 updateModuleTimestamp(*M.Mod);
3982 }
3983 }
3984 }
3985
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 return Success;
3987}
3988
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003989static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003990
Ben Langmuir70a1b812015-03-24 04:43:52 +00003991/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3992static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003993 return Stream.canSkipToPos(4) &&
3994 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003995 Stream.Read(8) == 'P' &&
3996 Stream.Read(8) == 'C' &&
3997 Stream.Read(8) == 'H';
3998}
3999
Richard Smith0f99d6a2015-08-09 08:48:41 +00004000static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4001 switch (Kind) {
4002 case MK_PCH:
4003 return 0; // PCH
4004 case MK_ImplicitModule:
4005 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004006 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004007 return 1; // module
4008 case MK_MainFile:
4009 case MK_Preamble:
4010 return 2; // main source file
4011 }
4012 llvm_unreachable("unknown module kind");
4013}
4014
Guy Benyei11169dd2012-12-18 14:30:41 +00004015ASTReader::ASTReadResult
4016ASTReader::ReadASTCore(StringRef FileName,
4017 ModuleKind Type,
4018 SourceLocation ImportLoc,
4019 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004020 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004021 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004022 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 unsigned ClientLoadCapabilities) {
4024 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004026 ModuleManager::AddModuleResult AddResult
4027 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004028 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004029 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004030 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004031
Douglas Gregor7029ce12013-03-19 00:28:20 +00004032 switch (AddResult) {
4033 case ModuleManager::AlreadyLoaded:
4034 return Success;
4035
4036 case ModuleManager::NewlyLoaded:
4037 // Load module file below.
4038 break;
4039
4040 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004041 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004042 // it.
4043 if (ClientLoadCapabilities & ARR_Missing)
4044 return Missing;
4045
4046 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004047 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004048 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004049 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004050 return Failure;
4051
4052 case ModuleManager::OutOfDate:
4053 // We couldn't load the module file because it is out-of-date. If the
4054 // client can handle out-of-date, return it.
4055 if (ClientLoadCapabilities & ARR_OutOfDate)
4056 return OutOfDate;
4057
4058 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004059 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004060 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004061 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 return Failure;
4063 }
4064
Douglas Gregor7029ce12013-03-19 00:28:20 +00004065 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004068 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004069 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004070 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004071
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004073 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004074 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4075 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 return Failure;
4077 }
4078
4079 // This is used for compatibility with older PCH formats.
4080 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004081 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004082 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004083
Chris Lattnerefa77172013-01-20 00:00:22 +00004084 switch (Entry.Kind) {
4085 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004086 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004087 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 Error("invalid record at top-level of AST file");
4089 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004090
Chris Lattnerefa77172013-01-20 00:00:22 +00004091 case llvm::BitstreamEntry::SubBlock:
4092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 }
4094
Chris Lattnerefa77172013-01-20 00:00:22 +00004095 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 case CONTROL_BLOCK_ID:
4097 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004098 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004100 // Check that we didn't try to load a non-module AST file as a module.
4101 //
4102 // FIXME: Should we also perform the converse check? Loading a module as
4103 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004104 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4105 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004106 F.ModuleName.empty()) {
4107 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4108 if (Result != OutOfDate ||
4109 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4110 Diag(diag::err_module_file_not_module) << FileName;
4111 return Result;
4112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 break;
4114
4115 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004116 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 case OutOfDate: return OutOfDate;
4118 case VersionMismatch: return VersionMismatch;
4119 case ConfigurationMismatch: return ConfigurationMismatch;
4120 case HadErrors: return HadErrors;
4121 }
4122 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004123
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 case AST_BLOCK_ID:
4125 if (!HaveReadControlBlock) {
4126 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004127 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 return VersionMismatch;
4129 }
4130
4131 // Record that we've loaded this module.
4132 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4133 return Success;
4134
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004135 case UNHASHED_CONTROL_BLOCK_ID:
4136 // This block is handled using look-ahead during ReadControlBlock. We
4137 // shouldn't get here!
4138 Error("malformed block record in AST file");
4139 return Failure;
4140
Guy Benyei11169dd2012-12-18 14:30:41 +00004141 default:
4142 if (Stream.SkipBlock()) {
4143 Error("malformed block record in AST file");
4144 return Failure;
4145 }
4146 break;
4147 }
4148 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004149
4150 return Success;
4151}
4152
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004153ASTReader::ASTReadResult
4154ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4155 unsigned ClientLoadCapabilities) {
4156 const HeaderSearchOptions &HSOpts =
4157 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4158 bool AllowCompatibleConfigurationMismatch =
4159 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4160
4161 ASTReadResult Result = readUnhashedControlBlockImpl(
4162 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4163 Listener.get(),
4164 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4165
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004166 // If F was directly imported by another module, it's implicitly validated by
4167 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004168 if (DisableValidation || WasImportedBy ||
4169 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4170 return Success;
4171
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004172 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004173 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004174 return Failure;
4175 }
4176
4177 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4178 // If this module has already been finalized in the PCMCache, we're stuck
4179 // with it; we can only load a single version of each module.
4180 //
4181 // This can happen when a module is imported in two contexts: in one, as a
4182 // user module; in another, as a system module (due to an import from
4183 // another module marked with the [system] flag). It usually indicates a
4184 // bug in the module map: this module should also be marked with [system].
4185 //
4186 // If -Wno-system-headers (the default), and the first import is as a
4187 // system module, then validation will fail during the as-user import,
4188 // since -Werror flags won't have been validated. However, it's reasonable
4189 // to treat this consistently as a system module.
4190 //
4191 // If -Wsystem-headers, the PCM on disk was built with
4192 // -Wno-system-headers, and the first import is as a user module, then
4193 // validation will fail during the as-system import since the PCM on disk
4194 // doesn't guarantee that -Werror was respected. However, the -Werror
4195 // flags were checked during the initial as-user import.
4196 if (PCMCache.isBufferFinal(F.FileName)) {
4197 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4198 return Success;
4199 }
4200 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004201
4202 return Result;
4203}
4204
4205ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4206 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4207 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4208 bool ValidateDiagnosticOptions) {
4209 // Initialize a stream.
4210 BitstreamCursor Stream(StreamData);
4211
4212 // Sniff for the signature.
4213 if (!startsWithASTFileMagic(Stream))
4214 return Failure;
4215
4216 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4217 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4218 return Failure;
4219
4220 // Read all of the records in the options block.
4221 RecordData Record;
4222 ASTReadResult Result = Success;
4223 while (1) {
4224 llvm::BitstreamEntry Entry = Stream.advance();
4225
4226 switch (Entry.Kind) {
4227 case llvm::BitstreamEntry::Error:
4228 case llvm::BitstreamEntry::SubBlock:
4229 return Failure;
4230
4231 case llvm::BitstreamEntry::EndBlock:
4232 return Result;
4233
4234 case llvm::BitstreamEntry::Record:
4235 // The interesting case.
4236 break;
4237 }
4238
4239 // Read and process a record.
4240 Record.clear();
4241 switch (
4242 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4243 case SIGNATURE: {
4244 if (F)
4245 std::copy(Record.begin(), Record.end(), F->Signature.data());
4246 break;
4247 }
4248 case DIAGNOSTIC_OPTIONS: {
4249 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4250 if (Listener && ValidateDiagnosticOptions &&
4251 !AllowCompatibleConfigurationMismatch &&
4252 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004253 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004254 break;
4255 }
4256 case DIAG_PRAGMA_MAPPINGS:
4257 if (!F)
4258 break;
4259 if (F->PragmaDiagMappings.empty())
4260 F->PragmaDiagMappings.swap(Record);
4261 else
4262 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4263 Record.begin(), Record.end());
4264 break;
4265 }
4266 }
4267}
4268
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004269/// Parse a record and blob containing module file extension metadata.
4270static bool parseModuleFileExtensionMetadata(
4271 const SmallVectorImpl<uint64_t> &Record,
4272 StringRef Blob,
4273 ModuleFileExtensionMetadata &Metadata) {
4274 if (Record.size() < 4) return true;
4275
4276 Metadata.MajorVersion = Record[0];
4277 Metadata.MinorVersion = Record[1];
4278
4279 unsigned BlockNameLen = Record[2];
4280 unsigned UserInfoLen = Record[3];
4281
4282 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4283
4284 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4285 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4286 Blob.data() + BlockNameLen + UserInfoLen);
4287 return false;
4288}
4289
4290ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4291 BitstreamCursor &Stream = F.Stream;
4292
4293 RecordData Record;
4294 while (true) {
4295 llvm::BitstreamEntry Entry = Stream.advance();
4296 switch (Entry.Kind) {
4297 case llvm::BitstreamEntry::SubBlock:
4298 if (Stream.SkipBlock())
4299 return Failure;
4300
4301 continue;
4302
4303 case llvm::BitstreamEntry::EndBlock:
4304 return Success;
4305
4306 case llvm::BitstreamEntry::Error:
4307 return HadErrors;
4308
4309 case llvm::BitstreamEntry::Record:
4310 break;
4311 }
4312
4313 Record.clear();
4314 StringRef Blob;
4315 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4316 switch (RecCode) {
4317 case EXTENSION_METADATA: {
4318 ModuleFileExtensionMetadata Metadata;
4319 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4320 return Failure;
4321
4322 // Find a module file extension with this block name.
4323 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4324 if (Known == ModuleFileExtensions.end()) break;
4325
4326 // Form a reader.
4327 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4328 F, Stream)) {
4329 F.ExtensionReaders.push_back(std::move(Reader));
4330 }
4331
4332 break;
4333 }
4334 }
4335 }
4336
4337 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004338}
4339
Richard Smitha7e2cc62015-05-01 01:53:09 +00004340void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004341 assert(ContextObj && "no context to initialize");
4342 ASTContext &Context = *ContextObj;
4343
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 // If there's a listener, notify them that we "read" the translation unit.
4345 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004346 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 Context.getTranslationUnitDecl());
4348
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 // FIXME: Find a better way to deal with collisions between these
4350 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004351
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 // Load the special types.
4353 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4354 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4355 if (!Context.CFConstantStringTypeDecl)
4356 Context.setCFConstantStringType(GetType(String));
4357 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004358
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4360 QualType FileType = GetType(File);
4361 if (FileType.isNull()) {
4362 Error("FILE type is NULL");
4363 return;
4364 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 if (!Context.FILEDecl) {
4367 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4368 Context.setFILEDecl(Typedef->getDecl());
4369 else {
4370 const TagType *Tag = FileType->getAs<TagType>();
4371 if (!Tag) {
4372 Error("Invalid FILE type in AST file");
4373 return;
4374 }
4375 Context.setFILEDecl(Tag->getDecl());
4376 }
4377 }
4378 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004379
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4381 QualType Jmp_bufType = GetType(Jmp_buf);
4382 if (Jmp_bufType.isNull()) {
4383 Error("jmp_buf type is NULL");
4384 return;
4385 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004386
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (!Context.jmp_bufDecl) {
4388 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4389 Context.setjmp_bufDecl(Typedef->getDecl());
4390 else {
4391 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4392 if (!Tag) {
4393 Error("Invalid jmp_buf type in AST file");
4394 return;
4395 }
4396 Context.setjmp_bufDecl(Tag->getDecl());
4397 }
4398 }
4399 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004400
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4402 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4403 if (Sigjmp_bufType.isNull()) {
4404 Error("sigjmp_buf type is NULL");
4405 return;
4406 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004407
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 if (!Context.sigjmp_bufDecl) {
4409 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4410 Context.setsigjmp_bufDecl(Typedef->getDecl());
4411 else {
4412 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4413 assert(Tag && "Invalid sigjmp_buf type in AST file");
4414 Context.setsigjmp_bufDecl(Tag->getDecl());
4415 }
4416 }
4417 }
4418
4419 if (unsigned ObjCIdRedef
4420 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4421 if (Context.ObjCIdRedefinitionType.isNull())
4422 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4423 }
4424
4425 if (unsigned ObjCClassRedef
4426 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4427 if (Context.ObjCClassRedefinitionType.isNull())
4428 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4429 }
4430
4431 if (unsigned ObjCSelRedef
4432 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4433 if (Context.ObjCSelRedefinitionType.isNull())
4434 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4435 }
4436
4437 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4438 QualType Ucontext_tType = GetType(Ucontext_t);
4439 if (Ucontext_tType.isNull()) {
4440 Error("ucontext_t type is NULL");
4441 return;
4442 }
4443
4444 if (!Context.ucontext_tDecl) {
4445 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4446 Context.setucontext_tDecl(Typedef->getDecl());
4447 else {
4448 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4449 assert(Tag && "Invalid ucontext_t type in AST file");
4450 Context.setucontext_tDecl(Tag->getDecl());
4451 }
4452 }
4453 }
4454 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004455
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4457
4458 // If there were any CUDA special declarations, deserialize them.
4459 if (!CUDASpecialDeclRefs.empty()) {
4460 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4461 Context.setcudaConfigureCallDecl(
4462 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4463 }
Richard Smith56be7542014-03-21 00:33:59 +00004464
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004466 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004467 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004468 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004469 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004470 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004471 if (Import.ImportLoc.isValid())
4472 PP.makeModuleVisible(Imported, Import.ImportLoc);
4473 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004474 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 }
4476 ImportedModules.clear();
4477}
4478
4479void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004480 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004481}
4482
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004483/// \brief Reads and return the signature record from \p PCH's control block, or
4484/// else returns 0.
4485static ASTFileSignature readASTFileSignature(StringRef PCH) {
4486 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004487 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004488 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004489
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004490 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4491 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4492 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004493
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004494 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004495 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004496 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004497 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004498 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004499 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004500
4501 Record.clear();
4502 StringRef Blob;
4503 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004504 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4505 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004506 }
4507}
4508
Guy Benyei11169dd2012-12-18 14:30:41 +00004509/// \brief Retrieve the name of the original source file name
4510/// directly from the AST file, without actually loading the AST
4511/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004512std::string ASTReader::getOriginalSourceFile(
4513 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004514 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004516 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004518 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4519 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 return std::string();
4521 }
4522
4523 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004524 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004525
4526 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004527 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4529 return std::string();
4530 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004531
Chris Lattnere7b154b2013-01-19 21:39:22 +00004532 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004533 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004534 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4535 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004536 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004537
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004538 // Scan for ORIGINAL_FILE inside the control block.
4539 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004540 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004541 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004542 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4543 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004544
Chris Lattnere7b154b2013-01-19 21:39:22 +00004545 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4546 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4547 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004549
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004551 StringRef Blob;
4552 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4553 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004555}
4556
4557namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004558
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 class SimplePCHValidator : public ASTReaderListener {
4560 const LangOptions &ExistingLangOpts;
4561 const TargetOptions &ExistingTargetOpts;
4562 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004563 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004565
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 public:
4567 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4568 const TargetOptions &ExistingTargetOpts,
4569 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004570 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 FileManager &FileMgr)
4572 : ExistingLangOpts(ExistingLangOpts),
4573 ExistingTargetOpts(ExistingTargetOpts),
4574 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004575 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 FileMgr(FileMgr)
4577 {
4578 }
4579
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004580 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4581 bool AllowCompatibleDifferences) override {
4582 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4583 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004585
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004586 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4587 bool AllowCompatibleDifferences) override {
4588 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4589 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004591
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004592 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4593 StringRef SpecificModuleCachePath,
4594 bool Complain) override {
4595 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4596 ExistingModuleCachePath,
4597 nullptr, ExistingLangOpts);
4598 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004599
Craig Topper3e89dfe2014-03-13 02:13:41 +00004600 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4601 bool Complain,
4602 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004603 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004604 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 }
4606 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004607
4608} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004609
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004610bool ASTReader::readASTFileControlBlock(
4611 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004612 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004613 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004614 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004616 // FIXME: This allows use of the VFS; we do not allow use of the
4617 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004618 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 if (!Buffer) {
4620 return true;
4621 }
4622
4623 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004624 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4625 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626
4627 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004628 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004630
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004631 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004632 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004633 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004634
4635 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004636 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004637 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004638 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004639
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004641 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004642 bool DoneWithControlBlock = false;
4643 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004644 llvm::BitstreamEntry Entry = Stream.advance();
4645
4646 switch (Entry.Kind) {
4647 case llvm::BitstreamEntry::SubBlock: {
4648 switch (Entry.ID) {
4649 case OPTIONS_BLOCK_ID: {
4650 std::string IgnoredSuggestedPredefines;
4651 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4652 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004653 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004654 return true;
4655 break;
4656 }
4657
4658 case INPUT_FILES_BLOCK_ID:
4659 InputFilesCursor = Stream;
4660 if (Stream.SkipBlock() ||
4661 (NeedsInputFiles &&
4662 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4663 return true;
4664 break;
4665
4666 default:
4667 if (Stream.SkipBlock())
4668 return true;
4669 break;
4670 }
4671
4672 continue;
4673 }
4674
4675 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004676 DoneWithControlBlock = true;
4677 break;
Richard Smith0516b182015-09-08 19:40:14 +00004678
4679 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004680 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004681
4682 case llvm::BitstreamEntry::Record:
4683 break;
4684 }
4685
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004686 if (DoneWithControlBlock) break;
4687
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004689 StringRef Blob;
4690 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004691 switch ((ControlRecordTypes)RecCode) {
4692 case METADATA: {
4693 if (Record[0] != VERSION_MAJOR)
4694 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004695
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004696 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004697 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004698
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004699 break;
4700 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004701 case MODULE_NAME:
4702 Listener.ReadModuleName(Blob);
4703 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004704 case MODULE_DIRECTORY:
4705 ModuleDir = Blob;
4706 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004707 case MODULE_MAP_FILE: {
4708 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004709 auto Path = ReadString(Record, Idx);
4710 ResolveImportedPath(Path, ModuleDir);
4711 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004712 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004713 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004714 case INPUT_FILE_OFFSETS: {
4715 if (!NeedsInputFiles)
4716 break;
4717
4718 unsigned NumInputFiles = Record[0];
4719 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004720 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004721 for (unsigned I = 0; I != NumInputFiles; ++I) {
4722 // Go find this input file.
4723 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004724
4725 if (isSystemFile && !NeedsSystemInputFiles)
4726 break; // the rest are system input files
4727
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004728 BitstreamCursor &Cursor = InputFilesCursor;
4729 SavedStreamPosition SavedPosition(Cursor);
4730 Cursor.JumpToBit(InputFileOffs[I]);
4731
4732 unsigned Code = Cursor.ReadCode();
4733 RecordData Record;
4734 StringRef Blob;
4735 bool shouldContinue = false;
4736 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4737 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004738 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004739 std::string Filename = Blob;
4740 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004741 shouldContinue = Listener.visitInputFile(
4742 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004743 break;
4744 }
4745 if (!shouldContinue)
4746 break;
4747 }
4748 break;
4749 }
4750
Richard Smithd4b230b2014-10-27 23:01:16 +00004751 case IMPORTS: {
4752 if (!NeedsImports)
4753 break;
4754
4755 unsigned Idx = 0, N = Record.size();
4756 while (Idx < N) {
4757 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004758 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004759 std::string Filename = ReadString(Record, Idx);
4760 ResolveImportedPath(Filename, ModuleDir);
4761 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004762 }
4763 break;
4764 }
4765
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004766 default:
4767 // No other validation to perform.
4768 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 }
4770 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004771
4772 // Look for module file extension blocks, if requested.
4773 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004774 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004775 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4776 bool DoneWithExtensionBlock = false;
4777 while (!DoneWithExtensionBlock) {
4778 llvm::BitstreamEntry Entry = Stream.advance();
4779
4780 switch (Entry.Kind) {
4781 case llvm::BitstreamEntry::SubBlock:
4782 if (Stream.SkipBlock())
4783 return true;
4784
4785 continue;
4786
4787 case llvm::BitstreamEntry::EndBlock:
4788 DoneWithExtensionBlock = true;
4789 continue;
4790
4791 case llvm::BitstreamEntry::Error:
4792 return true;
4793
4794 case llvm::BitstreamEntry::Record:
4795 break;
4796 }
4797
4798 Record.clear();
4799 StringRef Blob;
4800 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4801 switch (RecCode) {
4802 case EXTENSION_METADATA: {
4803 ModuleFileExtensionMetadata Metadata;
4804 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4805 return true;
4806
4807 Listener.readModuleFileExtension(Metadata);
4808 break;
4809 }
4810 }
4811 }
4812 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004813 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004814 }
4815
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004816 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4817 if (readUnhashedControlBlockImpl(
4818 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4819 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4820 ValidateDiagnosticOptions) != Success)
4821 return true;
4822
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004823 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004824}
4825
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004826bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4827 const PCHContainerReader &PCHContainerRdr,
4828 const LangOptions &LangOpts,
4829 const TargetOptions &TargetOpts,
4830 const PreprocessorOptions &PPOpts,
4831 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004832 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4833 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004834 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004835 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004836 validator,
4837 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004838}
4839
Ben Langmuir2c9af442014-04-10 17:57:43 +00004840ASTReader::ASTReadResult
4841ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 // Enter the submodule block.
4843 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4844 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 }
4847
4848 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4849 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004850 Module *CurrentModule = nullptr;
Richard Smith145e15a2017-04-24 23:12:30 +00004851 Module::ModuleKind ModuleKind = Module::ModuleMapModule;
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 RecordData Record;
4853 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004854 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004855
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004856 switch (Entry.Kind) {
4857 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4858 case llvm::BitstreamEntry::Error:
4859 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004860 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004861 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004862 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004863 case llvm::BitstreamEntry::Record:
4864 // The interesting case.
4865 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004867
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004869 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004871 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4872
4873 if ((Kind == SUBMODULE_METADATA) != First) {
4874 Error("submodule metadata record should be at beginning of block");
4875 return Failure;
4876 }
4877 First = false;
4878
4879 // Submodule information is only valid if we have a current module.
4880 // FIXME: Should we error on these cases?
4881 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4882 Kind != SUBMODULE_DEFINITION)
4883 continue;
4884
4885 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 default: // Default behavior: ignore.
4887 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004888
Richard Smith03478d92014-10-23 22:12:14 +00004889 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004890 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004892 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 }
Richard Smith03478d92014-10-23 22:12:14 +00004894
Chris Lattner0e6c9402013-01-20 02:38:54 +00004895 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004896 unsigned Idx = 0;
4897 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4898 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4899 bool IsFramework = Record[Idx++];
4900 bool IsExplicit = Record[Idx++];
4901 bool IsSystem = Record[Idx++];
4902 bool IsExternC = Record[Idx++];
4903 bool InferSubmodules = Record[Idx++];
4904 bool InferExplicitSubmodules = Record[Idx++];
4905 bool InferExportWildcard = Record[Idx++];
4906 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004907
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004908 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004909 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004911
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 // Retrieve this (sub)module from the module map, creating it if
4913 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004914 CurrentModule =
4915 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4916 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004917
4918 // FIXME: set the definition loc for CurrentModule, or call
4919 // ModMap.setInferredModuleAllowedBy()
4920
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4922 if (GlobalIndex >= SubmodulesLoaded.size() ||
4923 SubmodulesLoaded[GlobalIndex]) {
4924 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004925 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004927
Douglas Gregor7029ce12013-03-19 00:28:20 +00004928 if (!ParentModule) {
4929 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4930 if (CurFile != F.File) {
4931 if (!Diags.isDiagnosticInFlight()) {
4932 Diag(diag::err_module_file_conflict)
4933 << CurrentModule->getTopLevelModuleName()
4934 << CurFile->getName()
4935 << F.File->getName();
4936 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004937 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004938 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004939 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004940
4941 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00004942 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004943 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004944
Richard Smith145e15a2017-04-24 23:12:30 +00004945 CurrentModule->Kind = ModuleKind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00004946 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 CurrentModule->IsFromModuleFile = true;
4948 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004949 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 CurrentModule->InferSubmodules = InferSubmodules;
4951 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4952 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004953 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 if (DeserializationListener)
4955 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004956
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004958
Richard Smith8a3e39a2016-03-28 21:31:09 +00004959 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004960 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004961 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004962 CurrentModule->UnresolvedConflicts.clear();
4963 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004964
4965 // The module is available unless it's missing a requirement; relevant
4966 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4967 // Missing headers that were present when the module was built do not
4968 // make it unavailable -- if we got this far, this must be an explicitly
4969 // imported module file.
4970 CurrentModule->Requirements.clear();
4971 CurrentModule->MissingHeaders.clear();
4972 CurrentModule->IsMissingRequirement =
4973 ParentModule && ParentModule->IsMissingRequirement;
4974 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 break;
4976 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004977
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004979 std::string Filename = Blob;
4980 ResolveImportedPath(F, Filename);
4981 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004983 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4984 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00004985 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4986 Error("mismatched umbrella headers in submodule");
4987 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 }
4989 }
4990 break;
4991 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004992
Richard Smith202210b2014-10-24 20:23:01 +00004993 case SUBMODULE_HEADER:
4994 case SUBMODULE_EXCLUDED_HEADER:
4995 case SUBMODULE_PRIVATE_HEADER:
4996 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004997 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4998 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004999 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005000
Richard Smith202210b2014-10-24 20:23:01 +00005001 case SUBMODULE_TEXTUAL_HEADER:
5002 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5003 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5004 // them here.
5005 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005006
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005008 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 break;
5010 }
5011
5012 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005013 std::string Dirname = Blob;
5014 ResolveImportedPath(F, Dirname);
5015 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005017 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5018 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005019 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5020 Error("mismatched umbrella directories in submodule");
5021 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 }
5023 }
5024 break;
5025 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005026
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 F.BaseSubmoduleID = getTotalNumSubmodules();
5029 F.LocalNumSubmodules = Record[0];
5030 unsigned LocalBaseSubmoduleID = Record[1];
5031 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005032 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005033 // module.
5034 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005035
5036 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 // module.
5038 F.SubmoduleRemap.insertOrReplace(
5039 std::make_pair(LocalBaseSubmoduleID,
5040 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005041
Ben Langmuir52ca6782014-10-20 16:27:32 +00005042 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5043 }
Richard Smith145e15a2017-04-24 23:12:30 +00005044 ModuleKind = (Module::ModuleKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 break;
5046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005047
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005050 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 Unresolved.File = &F;
5052 Unresolved.Mod = CurrentModule;
5053 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005054 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005056 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 }
5058 break;
5059 }
5060
5061 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005063 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 Unresolved.File = &F;
5065 Unresolved.Mod = CurrentModule;
5066 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005067 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005069 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005071
5072 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 // the parsed, unresolved exports around.
5074 CurrentModule->UnresolvedExports.clear();
5075 break;
5076 }
5077 case SUBMODULE_REQUIRES: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005078 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5079 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 break;
5081 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005082
5083 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005084 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005085 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005086 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005087
5088 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005089 CurrentModule->ConfigMacros.push_back(Blob.str());
5090 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005091
5092 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005093 UnresolvedModuleRef Unresolved;
5094 Unresolved.File = &F;
5095 Unresolved.Mod = CurrentModule;
5096 Unresolved.ID = Record[0];
5097 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5098 Unresolved.IsWildcard = false;
5099 Unresolved.String = Blob;
5100 UnresolvedModuleRefs.push_back(Unresolved);
5101 break;
5102 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005103
5104 case SUBMODULE_INITIALIZERS:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005105 if (!ContextObj)
5106 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005107 SmallVector<uint32_t, 16> Inits;
5108 for (auto &ID : Record)
5109 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005110 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005111 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 }
5113 }
5114}
5115
5116/// \brief Parse the record that corresponds to a LangOptions data
5117/// structure.
5118///
5119/// This routine parses the language options from the AST file and then gives
5120/// them to the AST listener if one is set.
5121///
5122/// \returns true if the listener deems the file unacceptable, false otherwise.
5123bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5124 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005125 ASTReaderListener &Listener,
5126 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 LangOptions LangOpts;
5128 unsigned Idx = 0;
5129#define LANGOPT(Name, Bits, Default, Description) \
5130 LangOpts.Name = Record[Idx++];
5131#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5132 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5133#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005134#define SANITIZER(NAME, ID) \
5135 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005136#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005137
Ben Langmuircd98cb72015-06-23 18:20:18 +00005138 for (unsigned N = Record[Idx++]; N; --N)
5139 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5140
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5142 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5143 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005144
Ben Langmuird4a667a2015-06-23 18:20:23 +00005145 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005146
5147 // Comment options.
5148 for (unsigned N = Record[Idx++]; N; --N) {
5149 LangOpts.CommentOpts.BlockCommandNames.push_back(
5150 ReadString(Record, Idx));
5151 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005152 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005153
Samuel Antaoee8fb302016-01-06 13:42:12 +00005154 // OpenMP offloading options.
5155 for (unsigned N = Record[Idx++]; N; --N) {
5156 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5157 }
5158
5159 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5160
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005161 return Listener.ReadLanguageOptions(LangOpts, Complain,
5162 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005163}
5164
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005165bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5166 ASTReaderListener &Listener,
5167 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 unsigned Idx = 0;
5169 TargetOptions TargetOpts;
5170 TargetOpts.Triple = ReadString(Record, Idx);
5171 TargetOpts.CPU = ReadString(Record, Idx);
5172 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 for (unsigned N = Record[Idx++]; N; --N) {
5174 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5175 }
5176 for (unsigned N = Record[Idx++]; N; --N) {
5177 TargetOpts.Features.push_back(ReadString(Record, Idx));
5178 }
5179
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005180 return Listener.ReadTargetOptions(TargetOpts, Complain,
5181 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005182}
5183
5184bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5185 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005186 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005188#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005189#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005190 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005191#include "clang/Basic/DiagnosticOptions.def"
5192
Richard Smith3be1cb22014-08-07 00:24:21 +00005193 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005194 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005195 for (unsigned N = Record[Idx++]; N; --N)
5196 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005197
5198 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5199}
5200
5201bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5202 ASTReaderListener &Listener) {
5203 FileSystemOptions FSOpts;
5204 unsigned Idx = 0;
5205 FSOpts.WorkingDir = ReadString(Record, Idx);
5206 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5207}
5208
5209bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5210 bool Complain,
5211 ASTReaderListener &Listener) {
5212 HeaderSearchOptions HSOpts;
5213 unsigned Idx = 0;
5214 HSOpts.Sysroot = ReadString(Record, Idx);
5215
5216 // Include entries.
5217 for (unsigned N = Record[Idx++]; N; --N) {
5218 std::string Path = ReadString(Record, Idx);
5219 frontend::IncludeDirGroup Group
5220 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 bool IsFramework = Record[Idx++];
5222 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005223 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5224 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 }
5226
5227 // System header prefixes.
5228 for (unsigned N = Record[Idx++]; N; --N) {
5229 std::string Prefix = ReadString(Record, Idx);
5230 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005231 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 }
5233
5234 HSOpts.ResourceDir = ReadString(Record, Idx);
5235 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005236 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005238 HSOpts.ImplicitModuleMaps = Record[Idx++];
5239 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 HSOpts.UseBuiltinIncludes = Record[Idx++];
5241 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5242 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5243 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005244 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005245
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005246 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5247 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005248}
5249
5250bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5251 bool Complain,
5252 ASTReaderListener &Listener,
5253 std::string &SuggestedPredefines) {
5254 PreprocessorOptions PPOpts;
5255 unsigned Idx = 0;
5256
5257 // Macro definitions/undefs
5258 for (unsigned N = Record[Idx++]; N; --N) {
5259 std::string Macro = ReadString(Record, Idx);
5260 bool IsUndef = Record[Idx++];
5261 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5262 }
5263
5264 // Includes
5265 for (unsigned N = Record[Idx++]; N; --N) {
5266 PPOpts.Includes.push_back(ReadString(Record, Idx));
5267 }
5268
5269 // Macro Includes
5270 for (unsigned N = Record[Idx++]; N; --N) {
5271 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5272 }
5273
5274 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005275 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5277 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5278 PPOpts.ObjCXXARCStandardLibrary =
5279 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5280 SuggestedPredefines.clear();
5281 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5282 SuggestedPredefines);
5283}
5284
5285std::pair<ModuleFile *, unsigned>
5286ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5287 GlobalPreprocessedEntityMapType::iterator
5288 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005289 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 "Corrupted global preprocessed entity map");
5291 ModuleFile *M = I->second;
5292 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5293 return std::make_pair(M, LocalIndex);
5294}
5295
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005296llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005297ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5298 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5299 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5300 Mod.NumPreprocessedEntities);
5301
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005302 return llvm::make_range(PreprocessingRecord::iterator(),
5303 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005304}
5305
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005306llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005307ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005308 return llvm::make_range(
5309 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5310 ModuleDeclIterator(this, &Mod,
5311 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005312}
5313
5314PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5315 PreprocessedEntityID PPID = Index+1;
5316 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5317 ModuleFile &M = *PPInfo.first;
5318 unsigned LocalIndex = PPInfo.second;
5319 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5320
Guy Benyei11169dd2012-12-18 14:30:41 +00005321 if (!PP.getPreprocessingRecord()) {
5322 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005323 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005324 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005325
5326 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005327 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5328
5329 llvm::BitstreamEntry Entry =
5330 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5331 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005332 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005333
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005335 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5336 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005338 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 RecordData Record;
5340 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005341 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5342 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 switch (RecType) {
5344 case PPD_MACRO_EXPANSION: {
5345 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005346 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005347 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 if (isBuiltin)
5349 Name = getLocalIdentifier(M, Record[1]);
5350 else {
Richard Smith66a81862015-05-04 02:25:31 +00005351 PreprocessedEntityID GlobalID =
5352 getGlobalPreprocessedEntityID(M, Record[1]);
5353 Def = cast<MacroDefinitionRecord>(
5354 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005355 }
5356
5357 MacroExpansion *ME;
5358 if (isBuiltin)
5359 ME = new (PPRec) MacroExpansion(Name, Range);
5360 else
5361 ME = new (PPRec) MacroExpansion(Def, Range);
5362
5363 return ME;
5364 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005365
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 case PPD_MACRO_DEFINITION: {
5367 // Decode the identifier info and then check again; if the macro is
5368 // still defined and associated with the identifier,
5369 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005370 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005371
5372 if (DeserializationListener)
5373 DeserializationListener->MacroDefinitionRead(PPID, MD);
5374
5375 return MD;
5376 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005377
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005379 const char *FullFileNameStart = Blob.data() + Record[0];
5380 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005381 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 if (!FullFileName.empty())
5383 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005384
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 // FIXME: Stable encoding
5386 InclusionDirective::InclusionKind Kind
5387 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5388 InclusionDirective *ID
5389 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005390 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 Record[1], Record[3],
5392 File,
5393 Range);
5394 return ID;
5395 }
5396 }
5397
5398 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5399}
5400
5401/// \brief \arg SLocMapI points at a chunk of a module that contains no
5402/// preprocessed entities or the entities it contains are not the ones we are
5403/// looking for. Find the next module that contains entities and return the ID
5404/// of the first entry.
5405PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5406 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5407 ++SLocMapI;
5408 for (GlobalSLocOffsetMapType::const_iterator
5409 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5410 ModuleFile &M = *SLocMapI->second;
5411 if (M.NumPreprocessedEntities)
5412 return M.BasePreprocessedEntityID;
5413 }
5414
5415 return getTotalNumPreprocessedEntities();
5416}
5417
5418namespace {
5419
Guy Benyei11169dd2012-12-18 14:30:41 +00005420struct PPEntityComp {
5421 const ASTReader &Reader;
5422 ModuleFile &M;
5423
5424 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5425
5426 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5427 SourceLocation LHS = getLoc(L);
5428 SourceLocation RHS = getLoc(R);
5429 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5430 }
5431
5432 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5433 SourceLocation LHS = getLoc(L);
5434 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5435 }
5436
5437 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5438 SourceLocation RHS = getLoc(R);
5439 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5440 }
5441
5442 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005443 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 }
5445};
5446
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005447} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005448
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005449PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5450 bool EndsAfter) const {
5451 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 return getTotalNumPreprocessedEntities();
5453
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005454 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5455 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5457 "Corrupted global sloc offset map");
5458
5459 if (SLocMapI->second->NumPreprocessedEntities == 0)
5460 return findNextPreprocessedEntity(SLocMapI);
5461
5462 ModuleFile &M = *SLocMapI->second;
5463 typedef const PPEntityOffset *pp_iterator;
5464 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5465 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5466
5467 size_t Count = M.NumPreprocessedEntities;
5468 size_t Half;
5469 pp_iterator First = pp_begin;
5470 pp_iterator PPI;
5471
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005472 if (EndsAfter) {
5473 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005474 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005475 } else {
5476 // Do a binary search manually instead of using std::lower_bound because
5477 // The end locations of entities may be unordered (when a macro expansion
5478 // is inside another macro argument), but for this case it is not important
5479 // whether we get the first macro expansion or its containing macro.
5480 while (Count > 0) {
5481 Half = Count / 2;
5482 PPI = First;
5483 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005484 if (SourceMgr.isBeforeInTranslationUnit(
5485 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005486 First = PPI;
5487 ++First;
5488 Count = Count - Half - 1;
5489 } else
5490 Count = Half;
5491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 }
5493
5494 if (PPI == pp_end)
5495 return findNextPreprocessedEntity(SLocMapI);
5496
5497 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5498}
5499
Guy Benyei11169dd2012-12-18 14:30:41 +00005500/// \brief Returns a pair of [Begin, End) indices of preallocated
5501/// preprocessed entities that \arg Range encompasses.
5502std::pair<unsigned, unsigned>
5503 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5504 if (Range.isInvalid())
5505 return std::make_pair(0,0);
5506 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5507
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005508 PreprocessedEntityID BeginID =
5509 findPreprocessedEntity(Range.getBegin(), false);
5510 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 return std::make_pair(BeginID, EndID);
5512}
5513
5514/// \brief Optionally returns true or false if the preallocated preprocessed
5515/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005516Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005517 FileID FID) {
5518 if (FID.isInvalid())
5519 return false;
5520
5521 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5522 ModuleFile &M = *PPInfo.first;
5523 unsigned LocalIndex = PPInfo.second;
5524 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005525
Richard Smithcb34bd32016-03-27 07:28:06 +00005526 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005527 if (Loc.isInvalid())
5528 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005529
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5531 return true;
5532 else
5533 return false;
5534}
5535
5536namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005537
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 /// \brief Visitor used to search for information about a header file.
5539 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005540 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005541
David Blaikie05785d12013-02-20 22:23:23 +00005542 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005543
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005545 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5546 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005547
5548 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 HeaderFileInfoLookupTable *Table
5550 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5551 if (!Table)
5552 return false;
5553
5554 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005555 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005556 if (Pos == Table->end())
5557 return false;
5558
Richard Smithbdf2d932015-07-30 03:37:16 +00005559 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005560 return true;
5561 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005562
David Blaikie05785d12013-02-20 22:23:23 +00005563 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005565
5566} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005567
5568HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005569 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005570 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005571 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005572 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005573
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 return HeaderFileInfo();
5575}
5576
5577void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005578 using DiagState = DiagnosticsEngine::DiagState;
5579 SmallVector<DiagState *, 32> DiagStates;
5580
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005581 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005583 auto &Record = F.PragmaDiagMappings;
5584 if (Record.empty())
5585 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005586
Richard Smithd230de22017-01-26 01:01:01 +00005587 DiagStates.clear();
5588
5589 auto ReadDiagState =
5590 [&](const DiagState &BasedOn, SourceLocation Loc,
5591 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5592 unsigned BackrefID = Record[Idx++];
5593 if (BackrefID != 0)
5594 return DiagStates[BackrefID - 1];
5595
Guy Benyei11169dd2012-12-18 14:30:41 +00005596 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005597 Diag.DiagStates.push_back(BasedOn);
5598 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005600 unsigned Size = Record[Idx++];
5601 assert(Idx + Size * 2 <= Record.size() &&
5602 "Invalid data, not enough diag/map pairs");
5603 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005604 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005605 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005606 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005607 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5608 continue;
5609
5610 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5611
5612 // If this mapping was specified as a warning but the severity was
5613 // upgraded due to diagnostic settings, simulate the current diagnostic
5614 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005615 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5616 NewMapping.setSeverity(diag::Severity::Warning);
5617 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005618 }
5619
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005620 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005621 }
Richard Smithd230de22017-01-26 01:01:01 +00005622 return NewState;
5623 };
5624
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005625 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005626 DiagState *FirstState;
5627 if (F.Kind == MK_ImplicitModule) {
5628 // Implicitly-built modules are reused with different diagnostic
5629 // settings. Use the initial diagnostic state from Diag to simulate this
5630 // compilation's diagnostic settings.
5631 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5632 DiagStates.push_back(FirstState);
5633
5634 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005635 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005636 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005637 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005638 assert(Idx < Record.size() &&
5639 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005640 } else if (F.isModule()) {
5641 // For an explicit module, preserve the flags from the module build
5642 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5643 // -Wblah flags.
5644 unsigned Flags = Record[Idx++];
5645 DiagState Initial;
5646 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5647 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5648 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5649 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5650 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5651 Initial.ExtBehavior = (diag::Severity)Flags;
5652 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005653
Richard Smithe37391c2017-05-03 00:28:49 +00005654 // Set up the root buffer of the module to start with the initial
5655 // diagnostic state of the module itself, to cover files that contain no
5656 // explicit transitions (for which we did not serialize anything).
5657 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5658 .StateTransitions.push_back({FirstState, 0});
5659 } else {
5660 // For prefix ASTs, start with whatever the user configured on the
5661 // command line.
5662 Idx++; // Skip flags.
5663 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5664 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005665 }
Richard Smithd230de22017-01-26 01:01:01 +00005666
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005667 // Read the state transitions.
5668 unsigned NumLocations = Record[Idx++];
5669 while (NumLocations--) {
5670 assert(Idx < Record.size() &&
5671 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005672 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5673 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5674 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5675 unsigned Transitions = Record[Idx++];
5676
5677 // Note that we don't need to set up Parent/ParentOffset here, because
5678 // we won't be changing the diagnostic state within imported FileIDs
5679 // (other than perhaps appending to the main source file, which has no
5680 // parent).
5681 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5682 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5683 for (unsigned I = 0; I != Transitions; ++I) {
5684 unsigned Offset = Record[Idx++];
5685 auto *State =
5686 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5687 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005688 }
5689 }
Richard Smithd230de22017-01-26 01:01:01 +00005690
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005691 // Read the final state.
5692 assert(Idx < Record.size() &&
5693 "Invalid data, missing final pragma diagnostic state");
5694 SourceLocation CurStateLoc =
5695 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5696 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5697
5698 if (!F.isModule()) {
5699 Diag.DiagStatesByLoc.CurDiagState = CurState;
5700 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5701
5702 // Preserve the property that the imaginary root file describes the
5703 // current state.
5704 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5705 if (T.empty())
5706 T.push_back({CurState, 0});
5707 else
5708 T[0].State = CurState;
5709 }
5710
Richard Smithd230de22017-01-26 01:01:01 +00005711 // Don't try to read these mappings again.
5712 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005713 }
5714}
5715
5716/// \brief Get the correct cursor and offset for loading a type.
5717ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5718 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5719 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5720 ModuleFile *M = I->second;
5721 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5722}
5723
5724/// \brief Read and return the type with the given index..
5725///
5726/// The index is the type ID, shifted and minus the number of predefs. This
5727/// routine actually reads the record corresponding to the type at the given
5728/// location. It is a helper routine for GetType, which deals with reading type
5729/// IDs.
5730QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005731 assert(ContextObj && "reading type with no AST context");
5732 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005733 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005734 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005735
5736 // Keep track of where we are in the stream, then jump back there
5737 // after reading this type.
5738 SavedStreamPosition SavedPosition(DeclsCursor);
5739
5740 ReadingKindTracker ReadingKind(Read_Type, *this);
5741
5742 // Note that we are loading a type record.
5743 Deserializing AType(this);
5744
5745 unsigned Idx = 0;
5746 DeclsCursor.JumpToBit(Loc.Offset);
5747 RecordData Record;
5748 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005749 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005750 case TYPE_EXT_QUAL: {
5751 if (Record.size() != 2) {
5752 Error("Incorrect encoding of extended qualifier type");
5753 return QualType();
5754 }
5755 QualType Base = readType(*Loc.F, Record, Idx);
5756 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5757 return Context.getQualifiedType(Base, Quals);
5758 }
5759
5760 case TYPE_COMPLEX: {
5761 if (Record.size() != 1) {
5762 Error("Incorrect encoding of complex type");
5763 return QualType();
5764 }
5765 QualType ElemType = readType(*Loc.F, Record, Idx);
5766 return Context.getComplexType(ElemType);
5767 }
5768
5769 case TYPE_POINTER: {
5770 if (Record.size() != 1) {
5771 Error("Incorrect encoding of pointer type");
5772 return QualType();
5773 }
5774 QualType PointeeType = readType(*Loc.F, Record, Idx);
5775 return Context.getPointerType(PointeeType);
5776 }
5777
Reid Kleckner8a365022013-06-24 17:51:48 +00005778 case TYPE_DECAYED: {
5779 if (Record.size() != 1) {
5780 Error("Incorrect encoding of decayed type");
5781 return QualType();
5782 }
5783 QualType OriginalType = readType(*Loc.F, Record, Idx);
5784 QualType DT = Context.getAdjustedParameterType(OriginalType);
5785 if (!isa<DecayedType>(DT))
5786 Error("Decayed type does not decay");
5787 return DT;
5788 }
5789
Reid Kleckner0503a872013-12-05 01:23:43 +00005790 case TYPE_ADJUSTED: {
5791 if (Record.size() != 2) {
5792 Error("Incorrect encoding of adjusted type");
5793 return QualType();
5794 }
5795 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5796 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5797 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5798 }
5799
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 case TYPE_BLOCK_POINTER: {
5801 if (Record.size() != 1) {
5802 Error("Incorrect encoding of block pointer type");
5803 return QualType();
5804 }
5805 QualType PointeeType = readType(*Loc.F, Record, Idx);
5806 return Context.getBlockPointerType(PointeeType);
5807 }
5808
5809 case TYPE_LVALUE_REFERENCE: {
5810 if (Record.size() != 2) {
5811 Error("Incorrect encoding of lvalue reference type");
5812 return QualType();
5813 }
5814 QualType PointeeType = readType(*Loc.F, Record, Idx);
5815 return Context.getLValueReferenceType(PointeeType, Record[1]);
5816 }
5817
5818 case TYPE_RVALUE_REFERENCE: {
5819 if (Record.size() != 1) {
5820 Error("Incorrect encoding of rvalue reference type");
5821 return QualType();
5822 }
5823 QualType PointeeType = readType(*Loc.F, Record, Idx);
5824 return Context.getRValueReferenceType(PointeeType);
5825 }
5826
5827 case TYPE_MEMBER_POINTER: {
5828 if (Record.size() != 2) {
5829 Error("Incorrect encoding of member pointer type");
5830 return QualType();
5831 }
5832 QualType PointeeType = readType(*Loc.F, Record, Idx);
5833 QualType ClassType = readType(*Loc.F, Record, Idx);
5834 if (PointeeType.isNull() || ClassType.isNull())
5835 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005836
Guy Benyei11169dd2012-12-18 14:30:41 +00005837 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5838 }
5839
5840 case TYPE_CONSTANT_ARRAY: {
5841 QualType ElementType = readType(*Loc.F, Record, Idx);
5842 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5843 unsigned IndexTypeQuals = Record[2];
5844 unsigned Idx = 3;
5845 llvm::APInt Size = ReadAPInt(Record, Idx);
5846 return Context.getConstantArrayType(ElementType, Size,
5847 ASM, IndexTypeQuals);
5848 }
5849
5850 case TYPE_INCOMPLETE_ARRAY: {
5851 QualType ElementType = readType(*Loc.F, Record, Idx);
5852 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5853 unsigned IndexTypeQuals = Record[2];
5854 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5855 }
5856
5857 case TYPE_VARIABLE_ARRAY: {
5858 QualType ElementType = readType(*Loc.F, Record, Idx);
5859 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5860 unsigned IndexTypeQuals = Record[2];
5861 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5862 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5863 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5864 ASM, IndexTypeQuals,
5865 SourceRange(LBLoc, RBLoc));
5866 }
5867
5868 case TYPE_VECTOR: {
5869 if (Record.size() != 3) {
5870 Error("incorrect encoding of vector type in AST file");
5871 return QualType();
5872 }
5873
5874 QualType ElementType = readType(*Loc.F, Record, Idx);
5875 unsigned NumElements = Record[1];
5876 unsigned VecKind = Record[2];
5877 return Context.getVectorType(ElementType, NumElements,
5878 (VectorType::VectorKind)VecKind);
5879 }
5880
5881 case TYPE_EXT_VECTOR: {
5882 if (Record.size() != 3) {
5883 Error("incorrect encoding of extended vector type in AST file");
5884 return QualType();
5885 }
5886
5887 QualType ElementType = readType(*Loc.F, Record, Idx);
5888 unsigned NumElements = Record[1];
5889 return Context.getExtVectorType(ElementType, NumElements);
5890 }
5891
5892 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005893 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005894 Error("incorrect encoding of no-proto function type");
5895 return QualType();
5896 }
5897 QualType ResultType = readType(*Loc.F, Record, Idx);
5898 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005899 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005900 return Context.getFunctionNoProtoType(ResultType, Info);
5901 }
5902
5903 case TYPE_FUNCTION_PROTO: {
5904 QualType ResultType = readType(*Loc.F, Record, Idx);
5905
5906 FunctionProtoType::ExtProtoInfo EPI;
5907 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5908 /*hasregparm*/ Record[2],
5909 /*regparm*/ Record[3],
5910 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005911 /*produces*/ Record[5],
5912 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005913
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005914 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00005915
5916 EPI.Variadic = Record[Idx++];
5917 EPI.HasTrailingReturn = Record[Idx++];
5918 EPI.TypeQuals = Record[Idx++];
5919 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005920 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005921 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005922
5923 unsigned NumParams = Record[Idx++];
5924 SmallVector<QualType, 16> ParamTypes;
5925 for (unsigned I = 0; I != NumParams; ++I)
5926 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5927
John McCall18afab72016-03-01 00:49:02 +00005928 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5929 if (Idx != Record.size()) {
5930 for (unsigned I = 0; I != NumParams; ++I)
5931 ExtParameterInfos.push_back(
5932 FunctionProtoType::ExtParameterInfo
5933 ::getFromOpaqueValue(Record[Idx++]));
5934 EPI.ExtParameterInfos = ExtParameterInfos.data();
5935 }
5936
5937 assert(Idx == Record.size());
5938
Jordan Rose5c382722013-03-08 21:51:21 +00005939 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005940 }
5941
5942 case TYPE_UNRESOLVED_USING: {
5943 unsigned Idx = 0;
5944 return Context.getTypeDeclType(
5945 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5946 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005947
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 case TYPE_TYPEDEF: {
5949 if (Record.size() != 2) {
5950 Error("incorrect encoding of typedef type");
5951 return QualType();
5952 }
5953 unsigned Idx = 0;
5954 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5955 QualType Canonical = readType(*Loc.F, Record, Idx);
5956 if (!Canonical.isNull())
5957 Canonical = Context.getCanonicalType(Canonical);
5958 return Context.getTypedefType(Decl, Canonical);
5959 }
5960
5961 case TYPE_TYPEOF_EXPR:
5962 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5963
5964 case TYPE_TYPEOF: {
5965 if (Record.size() != 1) {
5966 Error("incorrect encoding of typeof(type) in AST file");
5967 return QualType();
5968 }
5969 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5970 return Context.getTypeOfType(UnderlyingType);
5971 }
5972
5973 case TYPE_DECLTYPE: {
5974 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5975 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5976 }
5977
5978 case TYPE_UNARY_TRANSFORM: {
5979 QualType BaseType = readType(*Loc.F, Record, Idx);
5980 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5981 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5982 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5983 }
5984
Richard Smith74aeef52013-04-26 16:15:35 +00005985 case TYPE_AUTO: {
5986 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005987 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005988 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005989 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005991
Richard Smith600b5262017-01-26 20:40:47 +00005992 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5993 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5994 QualType Deduced = readType(*Loc.F, Record, Idx);
5995 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5996 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5997 IsDependent);
5998 }
5999
Guy Benyei11169dd2012-12-18 14:30:41 +00006000 case TYPE_RECORD: {
6001 if (Record.size() != 2) {
6002 Error("incorrect encoding of record type");
6003 return QualType();
6004 }
6005 unsigned Idx = 0;
6006 bool IsDependent = Record[Idx++];
6007 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
6008 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6009 QualType T = Context.getRecordType(RD);
6010 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6011 return T;
6012 }
6013
6014 case TYPE_ENUM: {
6015 if (Record.size() != 2) {
6016 Error("incorrect encoding of enum type");
6017 return QualType();
6018 }
6019 unsigned Idx = 0;
6020 bool IsDependent = Record[Idx++];
6021 QualType T
6022 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6023 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6024 return T;
6025 }
6026
6027 case TYPE_ATTRIBUTED: {
6028 if (Record.size() != 3) {
6029 Error("incorrect encoding of attributed type");
6030 return QualType();
6031 }
6032 QualType modifiedType = readType(*Loc.F, Record, Idx);
6033 QualType equivalentType = readType(*Loc.F, Record, Idx);
6034 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6035 return Context.getAttributedType(kind, modifiedType, equivalentType);
6036 }
6037
6038 case TYPE_PAREN: {
6039 if (Record.size() != 1) {
6040 Error("incorrect encoding of paren type");
6041 return QualType();
6042 }
6043 QualType InnerType = readType(*Loc.F, Record, Idx);
6044 return Context.getParenType(InnerType);
6045 }
6046
6047 case TYPE_PACK_EXPANSION: {
6048 if (Record.size() != 2) {
6049 Error("incorrect encoding of pack expansion type");
6050 return QualType();
6051 }
6052 QualType Pattern = readType(*Loc.F, Record, Idx);
6053 if (Pattern.isNull())
6054 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006055 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 if (Record[1])
6057 NumExpansions = Record[1] - 1;
6058 return Context.getPackExpansionType(Pattern, NumExpansions);
6059 }
6060
6061 case TYPE_ELABORATED: {
6062 unsigned Idx = 0;
6063 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6064 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6065 QualType NamedType = readType(*Loc.F, Record, Idx);
6066 return Context.getElaboratedType(Keyword, NNS, NamedType);
6067 }
6068
6069 case TYPE_OBJC_INTERFACE: {
6070 unsigned Idx = 0;
6071 ObjCInterfaceDecl *ItfD
6072 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6073 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6074 }
6075
Manman Rene6be26c2016-09-13 17:25:08 +00006076 case TYPE_OBJC_TYPE_PARAM: {
6077 unsigned Idx = 0;
6078 ObjCTypeParamDecl *Decl
6079 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6080 unsigned NumProtos = Record[Idx++];
6081 SmallVector<ObjCProtocolDecl*, 4> Protos;
6082 for (unsigned I = 0; I != NumProtos; ++I)
6083 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6084 return Context.getObjCTypeParamType(Decl, Protos);
6085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006086 case TYPE_OBJC_OBJECT: {
6087 unsigned Idx = 0;
6088 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006089 unsigned NumTypeArgs = Record[Idx++];
6090 SmallVector<QualType, 4> TypeArgs;
6091 for (unsigned I = 0; I != NumTypeArgs; ++I)
6092 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 unsigned NumProtos = Record[Idx++];
6094 SmallVector<ObjCProtocolDecl*, 4> Protos;
6095 for (unsigned I = 0; I != NumProtos; ++I)
6096 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006097 bool IsKindOf = Record[Idx++];
6098 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 }
6100
6101 case TYPE_OBJC_OBJECT_POINTER: {
6102 unsigned Idx = 0;
6103 QualType Pointee = readType(*Loc.F, Record, Idx);
6104 return Context.getObjCObjectPointerType(Pointee);
6105 }
6106
6107 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6108 unsigned Idx = 0;
6109 QualType Parm = readType(*Loc.F, Record, Idx);
6110 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006111 return Context.getSubstTemplateTypeParmType(
6112 cast<TemplateTypeParmType>(Parm),
6113 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 }
6115
6116 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6117 unsigned Idx = 0;
6118 QualType Parm = readType(*Loc.F, Record, Idx);
6119 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6120 return Context.getSubstTemplateTypeParmPackType(
6121 cast<TemplateTypeParmType>(Parm),
6122 ArgPack);
6123 }
6124
6125 case TYPE_INJECTED_CLASS_NAME: {
6126 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6127 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6128 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6129 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006130 const Type *T = nullptr;
6131 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6132 if (const Type *Existing = DI->getTypeForDecl()) {
6133 T = Existing;
6134 break;
6135 }
6136 }
6137 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006138 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006139 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6140 DI->setTypeForDecl(T);
6141 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006142 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 }
6144
6145 case TYPE_TEMPLATE_TYPE_PARM: {
6146 unsigned Idx = 0;
6147 unsigned Depth = Record[Idx++];
6148 unsigned Index = Record[Idx++];
6149 bool Pack = Record[Idx++];
6150 TemplateTypeParmDecl *D
6151 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6152 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6153 }
6154
6155 case TYPE_DEPENDENT_NAME: {
6156 unsigned Idx = 0;
6157 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6158 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006159 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 QualType Canon = readType(*Loc.F, Record, Idx);
6161 if (!Canon.isNull())
6162 Canon = Context.getCanonicalType(Canon);
6163 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6164 }
6165
6166 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6167 unsigned Idx = 0;
6168 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6169 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006170 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 unsigned NumArgs = Record[Idx++];
6172 SmallVector<TemplateArgument, 8> Args;
6173 Args.reserve(NumArgs);
6174 while (NumArgs--)
6175 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6176 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006177 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 }
6179
6180 case TYPE_DEPENDENT_SIZED_ARRAY: {
6181 unsigned Idx = 0;
6182
6183 // ArrayType
6184 QualType ElementType = readType(*Loc.F, Record, Idx);
6185 ArrayType::ArraySizeModifier ASM
6186 = (ArrayType::ArraySizeModifier)Record[Idx++];
6187 unsigned IndexTypeQuals = Record[Idx++];
6188
6189 // DependentSizedArrayType
6190 Expr *NumElts = ReadExpr(*Loc.F);
6191 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6192
6193 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6194 IndexTypeQuals, Brackets);
6195 }
6196
6197 case TYPE_TEMPLATE_SPECIALIZATION: {
6198 unsigned Idx = 0;
6199 bool IsDependent = Record[Idx++];
6200 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6201 SmallVector<TemplateArgument, 8> Args;
6202 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6203 QualType Underlying = readType(*Loc.F, Record, Idx);
6204 QualType T;
6205 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006206 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006207 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006208 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6210 return T;
6211 }
6212
6213 case TYPE_ATOMIC: {
6214 if (Record.size() != 1) {
6215 Error("Incorrect encoding of atomic type");
6216 return QualType();
6217 }
6218 QualType ValueType = readType(*Loc.F, Record, Idx);
6219 return Context.getAtomicType(ValueType);
6220 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006221
Joey Goulye3c85de2016-12-01 11:30:49 +00006222 case TYPE_PIPE: {
6223 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006224 Error("Incorrect encoding of pipe type");
6225 return QualType();
6226 }
6227
6228 // Reading the pipe element type.
6229 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006230 unsigned ReadOnly = Record[1];
6231 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006232 }
6233
Alex Lorenz00aee432017-03-22 10:04:48 +00006234 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6235 unsigned Idx = 0;
6236
6237 // DependentSizedExtVectorType
6238 QualType ElementType = readType(*Loc.F, Record, Idx);
6239 Expr *SizeExpr = ReadExpr(*Loc.F);
6240 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6241
6242 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6243 AttrLoc);
6244 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 }
6246 llvm_unreachable("Invalid TypeCode!");
6247}
6248
Richard Smith564417a2014-03-20 21:47:22 +00006249void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6250 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006251 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006252 const RecordData &Record, unsigned &Idx) {
6253 ExceptionSpecificationType EST =
6254 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006255 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006256 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006257 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006258 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006259 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006260 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006261 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006262 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006263 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6264 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006265 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006266 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006267 }
6268}
6269
Guy Benyei11169dd2012-12-18 14:30:41 +00006270class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006271 ModuleFile *F;
6272 ASTReader *Reader;
6273 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006274 unsigned &Idx;
6275
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006276 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006277 return Reader->ReadSourceLocation(*F, Record, Idx);
6278 }
6279
6280 TypeSourceInfo *GetTypeSourceInfo() {
6281 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6282 }
6283
6284 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6285 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006286 }
6287
Guy Benyei11169dd2012-12-18 14:30:41 +00006288public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006289 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006291 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006292
6293 // We want compile-time assurance that we've enumerated all of
6294 // these, so unfortunately we have to declare them first, then
6295 // define them out-of-line.
6296#define ABSTRACT_TYPELOC(CLASS, PARENT)
6297#define TYPELOC(CLASS, PARENT) \
6298 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6299#include "clang/AST/TypeLocNodes.def"
6300
6301 void VisitFunctionTypeLoc(FunctionTypeLoc);
6302 void VisitArrayTypeLoc(ArrayTypeLoc);
6303};
6304
6305void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6306 // nothing to do
6307}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006308
Guy Benyei11169dd2012-12-18 14:30:41 +00006309void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006310 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006311 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006312 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6313 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6314 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6315 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 }
6317}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006318
Guy Benyei11169dd2012-12-18 14:30:41 +00006319void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006320 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006321}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006322
Guy Benyei11169dd2012-12-18 14:30:41 +00006323void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006324 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006325}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006326
Reid Kleckner8a365022013-06-24 17:51:48 +00006327void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6328 // nothing to do
6329}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006330
Reid Kleckner0503a872013-12-05 01:23:43 +00006331void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6332 // nothing to do
6333}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006334
Guy Benyei11169dd2012-12-18 14:30:41 +00006335void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006336 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006337}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006338
Guy Benyei11169dd2012-12-18 14:30:41 +00006339void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006340 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006341}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006342
Guy Benyei11169dd2012-12-18 14:30:41 +00006343void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006344 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006345}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006346
Guy Benyei11169dd2012-12-18 14:30:41 +00006347void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006348 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006349 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006350}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006351
Guy Benyei11169dd2012-12-18 14:30:41 +00006352void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006353 TL.setLBracketLoc(ReadSourceLocation());
6354 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006355 if (Record[Idx++])
6356 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 else
Craig Toppera13603a2014-05-22 05:54:18 +00006358 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006359}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006360
Guy Benyei11169dd2012-12-18 14:30:41 +00006361void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6362 VisitArrayTypeLoc(TL);
6363}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006364
Guy Benyei11169dd2012-12-18 14:30:41 +00006365void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6366 VisitArrayTypeLoc(TL);
6367}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006368
Guy Benyei11169dd2012-12-18 14:30:41 +00006369void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6370 VisitArrayTypeLoc(TL);
6371}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006372
Guy Benyei11169dd2012-12-18 14:30:41 +00006373void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6374 DependentSizedArrayTypeLoc TL) {
6375 VisitArrayTypeLoc(TL);
6376}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006377
Guy Benyei11169dd2012-12-18 14:30:41 +00006378void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6379 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006380 TL.setNameLoc(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::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006384 TL.setNameLoc(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::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006388 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006389}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006390
Guy Benyei11169dd2012-12-18 14:30:41 +00006391void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006392 TL.setLocalRangeBegin(ReadSourceLocation());
6393 TL.setLParenLoc(ReadSourceLocation());
6394 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006395 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6396 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006397 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006398 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006399 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 }
6401}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006402
Guy Benyei11169dd2012-12-18 14:30:41 +00006403void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6404 VisitFunctionTypeLoc(TL);
6405}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006406
Guy Benyei11169dd2012-12-18 14:30:41 +00006407void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6408 VisitFunctionTypeLoc(TL);
6409}
6410void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006411 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006412}
6413void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006414 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006415}
6416void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006417 TL.setTypeofLoc(ReadSourceLocation());
6418 TL.setLParenLoc(ReadSourceLocation());
6419 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006420}
6421void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006422 TL.setTypeofLoc(ReadSourceLocation());
6423 TL.setLParenLoc(ReadSourceLocation());
6424 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006425 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006426}
6427void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006428 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006429}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006430
Guy Benyei11169dd2012-12-18 14:30:41 +00006431void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006432 TL.setKWLoc(ReadSourceLocation());
6433 TL.setLParenLoc(ReadSourceLocation());
6434 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006435 TL.setUnderlyingTInfo(GetTypeSourceInfo());
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::VisitAutoTypeLoc(AutoTypeLoc 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
Richard Smith600b5262017-01-26 20:40:47 +00006442void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6443 DeducedTemplateSpecializationTypeLoc TL) {
6444 TL.setTemplateNameLoc(ReadSourceLocation());
6445}
6446
Guy Benyei11169dd2012-12-18 14:30:41 +00006447void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006448 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006449}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006450
Guy Benyei11169dd2012-12-18 14:30:41 +00006451void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006452 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006453}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006456 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 if (TL.hasAttrOperand()) {
6458 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006459 range.setBegin(ReadSourceLocation());
6460 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006461 TL.setAttrOperandParensRange(range);
6462 }
6463 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006464 if (Record[Idx++])
6465 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 else
Craig Toppera13603a2014-05-22 05:54:18 +00006467 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006469 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006470}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006471
Guy Benyei11169dd2012-12-18 14:30:41 +00006472void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006473 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006474}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006475
Guy Benyei11169dd2012-12-18 14:30:41 +00006476void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6477 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006478 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006479}
6480void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6481 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006482 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006483}
6484void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6485 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006486 TL.setTemplateKeywordLoc(ReadSourceLocation());
6487 TL.setTemplateNameLoc(ReadSourceLocation());
6488 TL.setLAngleLoc(ReadSourceLocation());
6489 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006491 TL.setArgLocInfo(
6492 i,
6493 Reader->GetTemplateArgumentLocInfo(
6494 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006495}
6496void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006497 TL.setLParenLoc(ReadSourceLocation());
6498 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006499}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006500
Guy Benyei11169dd2012-12-18 14:30:41 +00006501void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006502 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006503 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
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::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006507 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006508}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006509
Guy Benyei11169dd2012-12-18 14:30:41 +00006510void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006511 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006512 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006513 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006514}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006515
Guy Benyei11169dd2012-12-18 14:30:41 +00006516void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6517 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006518 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006519 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006520 TL.setTemplateKeywordLoc(ReadSourceLocation());
6521 TL.setTemplateNameLoc(ReadSourceLocation());
6522 TL.setLAngleLoc(ReadSourceLocation());
6523 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006525 TL.setArgLocInfo(
6526 I,
6527 Reader->GetTemplateArgumentLocInfo(
6528 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006529}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006530
Guy Benyei11169dd2012-12-18 14:30:41 +00006531void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006532 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006536 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006537}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006538
Manman Rene6be26c2016-09-13 17:25:08 +00006539void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6540 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006541 TL.setProtocolLAngleLoc(ReadSourceLocation());
6542 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006543 }
6544 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006545 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006546}
6547
Guy Benyei11169dd2012-12-18 14:30:41 +00006548void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006549 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006550 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6551 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006552 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006553 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006554 TL.setProtocolLAngleLoc(ReadSourceLocation());
6555 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006557 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006558}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006559
Guy Benyei11169dd2012-12-18 14:30:41 +00006560void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006561 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006562}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006563
Guy Benyei11169dd2012-12-18 14:30:41 +00006564void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006565 TL.setKWLoc(ReadSourceLocation());
6566 TL.setLParenLoc(ReadSourceLocation());
6567 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006568}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006569
Xiuli Pan9c14e282016-01-09 12:53:17 +00006570void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006571 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006572}
Guy Benyei11169dd2012-12-18 14:30:41 +00006573
David L. Jonesbe1557a2016-12-21 00:17:49 +00006574TypeSourceInfo *
6575ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6576 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 QualType InfoTy = readType(F, Record, Idx);
6578 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006579 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006580
6581 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006582 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6584 TLR.Visit(TL);
6585 return TInfo;
6586}
6587
6588QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006589 assert(ContextObj && "reading type with no AST context");
6590 ASTContext &Context = *ContextObj;
6591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 unsigned FastQuals = ID & Qualifiers::FastMask;
6593 unsigned Index = ID >> Qualifiers::FastWidth;
6594
6595 if (Index < NUM_PREDEF_TYPE_IDS) {
6596 QualType T;
6597 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006598 case PREDEF_TYPE_NULL_ID:
6599 return QualType();
6600 case PREDEF_TYPE_VOID_ID:
6601 T = Context.VoidTy;
6602 break;
6603 case PREDEF_TYPE_BOOL_ID:
6604 T = Context.BoolTy;
6605 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006606
6607 case PREDEF_TYPE_CHAR_U_ID:
6608 case PREDEF_TYPE_CHAR_S_ID:
6609 // FIXME: Check that the signedness of CharTy is correct!
6610 T = Context.CharTy;
6611 break;
6612
Alexey Baderbdf7c842015-09-15 12:18:29 +00006613 case PREDEF_TYPE_UCHAR_ID:
6614 T = Context.UnsignedCharTy;
6615 break;
6616 case PREDEF_TYPE_USHORT_ID:
6617 T = Context.UnsignedShortTy;
6618 break;
6619 case PREDEF_TYPE_UINT_ID:
6620 T = Context.UnsignedIntTy;
6621 break;
6622 case PREDEF_TYPE_ULONG_ID:
6623 T = Context.UnsignedLongTy;
6624 break;
6625 case PREDEF_TYPE_ULONGLONG_ID:
6626 T = Context.UnsignedLongLongTy;
6627 break;
6628 case PREDEF_TYPE_UINT128_ID:
6629 T = Context.UnsignedInt128Ty;
6630 break;
6631 case PREDEF_TYPE_SCHAR_ID:
6632 T = Context.SignedCharTy;
6633 break;
6634 case PREDEF_TYPE_WCHAR_ID:
6635 T = Context.WCharTy;
6636 break;
6637 case PREDEF_TYPE_SHORT_ID:
6638 T = Context.ShortTy;
6639 break;
6640 case PREDEF_TYPE_INT_ID:
6641 T = Context.IntTy;
6642 break;
6643 case PREDEF_TYPE_LONG_ID:
6644 T = Context.LongTy;
6645 break;
6646 case PREDEF_TYPE_LONGLONG_ID:
6647 T = Context.LongLongTy;
6648 break;
6649 case PREDEF_TYPE_INT128_ID:
6650 T = Context.Int128Ty;
6651 break;
6652 case PREDEF_TYPE_HALF_ID:
6653 T = Context.HalfTy;
6654 break;
6655 case PREDEF_TYPE_FLOAT_ID:
6656 T = Context.FloatTy;
6657 break;
6658 case PREDEF_TYPE_DOUBLE_ID:
6659 T = Context.DoubleTy;
6660 break;
6661 case PREDEF_TYPE_LONGDOUBLE_ID:
6662 T = Context.LongDoubleTy;
6663 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006664 case PREDEF_TYPE_FLOAT128_ID:
6665 T = Context.Float128Ty;
6666 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006667 case PREDEF_TYPE_OVERLOAD_ID:
6668 T = Context.OverloadTy;
6669 break;
6670 case PREDEF_TYPE_BOUND_MEMBER:
6671 T = Context.BoundMemberTy;
6672 break;
6673 case PREDEF_TYPE_PSEUDO_OBJECT:
6674 T = Context.PseudoObjectTy;
6675 break;
6676 case PREDEF_TYPE_DEPENDENT_ID:
6677 T = Context.DependentTy;
6678 break;
6679 case PREDEF_TYPE_UNKNOWN_ANY:
6680 T = Context.UnknownAnyTy;
6681 break;
6682 case PREDEF_TYPE_NULLPTR_ID:
6683 T = Context.NullPtrTy;
6684 break;
6685 case PREDEF_TYPE_CHAR16_ID:
6686 T = Context.Char16Ty;
6687 break;
6688 case PREDEF_TYPE_CHAR32_ID:
6689 T = Context.Char32Ty;
6690 break;
6691 case PREDEF_TYPE_OBJC_ID:
6692 T = Context.ObjCBuiltinIdTy;
6693 break;
6694 case PREDEF_TYPE_OBJC_CLASS:
6695 T = Context.ObjCBuiltinClassTy;
6696 break;
6697 case PREDEF_TYPE_OBJC_SEL:
6698 T = Context.ObjCBuiltinSelTy;
6699 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006700#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6701 case PREDEF_TYPE_##Id##_ID: \
6702 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006703 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006704#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006705 case PREDEF_TYPE_SAMPLER_ID:
6706 T = Context.OCLSamplerTy;
6707 break;
6708 case PREDEF_TYPE_EVENT_ID:
6709 T = Context.OCLEventTy;
6710 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006711 case PREDEF_TYPE_CLK_EVENT_ID:
6712 T = Context.OCLClkEventTy;
6713 break;
6714 case PREDEF_TYPE_QUEUE_ID:
6715 T = Context.OCLQueueTy;
6716 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006717 case PREDEF_TYPE_RESERVE_ID_ID:
6718 T = Context.OCLReserveIDTy;
6719 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006720 case PREDEF_TYPE_AUTO_DEDUCT:
6721 T = Context.getAutoDeductType();
6722 break;
6723
6724 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6725 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 break;
6727
6728 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6729 T = Context.ARCUnbridgedCastTy;
6730 break;
6731
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 case PREDEF_TYPE_BUILTIN_FN:
6733 T = Context.BuiltinFnTy;
6734 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006735
6736 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6737 T = Context.OMPArraySectionTy;
6738 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006739 }
6740
6741 assert(!T.isNull() && "Unknown predefined type");
6742 return T.withFastQualifiers(FastQuals);
6743 }
6744
6745 Index -= NUM_PREDEF_TYPE_IDS;
6746 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6747 if (TypesLoaded[Index].isNull()) {
6748 TypesLoaded[Index] = readTypeRecord(Index);
6749 if (TypesLoaded[Index].isNull())
6750 return QualType();
6751
6752 TypesLoaded[Index]->setFromAST();
6753 if (DeserializationListener)
6754 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6755 TypesLoaded[Index]);
6756 }
6757
6758 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6759}
6760
6761QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6762 return GetType(getGlobalTypeID(F, LocalID));
6763}
6764
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006765serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006766ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6767 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6768 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006769
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6771 return LocalID;
6772
Richard Smith37a93df2017-02-18 00:32:02 +00006773 if (!F.ModuleOffsetMap.empty())
6774 ReadModuleOffsetMap(F);
6775
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6777 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6778 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006779
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 unsigned GlobalIndex = LocalIndex + I->second;
6781 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6782}
6783
6784TemplateArgumentLocInfo
6785ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6786 TemplateArgument::ArgKind Kind,
6787 const RecordData &Record,
6788 unsigned &Index) {
6789 switch (Kind) {
6790 case TemplateArgument::Expression:
6791 return ReadExpr(F);
6792 case TemplateArgument::Type:
6793 return GetTypeSourceInfo(F, Record, Index);
6794 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006795 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006796 Index);
6797 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6798 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6799 SourceLocation());
6800 }
6801 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006802 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006803 Index);
6804 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6805 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006806 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006807 EllipsisLoc);
6808 }
6809 case TemplateArgument::Null:
6810 case TemplateArgument::Integral:
6811 case TemplateArgument::Declaration:
6812 case TemplateArgument::NullPtr:
6813 case TemplateArgument::Pack:
6814 // FIXME: Is this right?
6815 return TemplateArgumentLocInfo();
6816 }
6817 llvm_unreachable("unexpected template argument loc");
6818}
6819
6820TemplateArgumentLoc
6821ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6822 const RecordData &Record, unsigned &Index) {
6823 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6824
6825 if (Arg.getKind() == TemplateArgument::Expression) {
6826 if (Record[Index++]) // bool InfoHasSameExpr.
6827 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6828 }
6829 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6830 Record, Index));
6831}
6832
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006833const ASTTemplateArgumentListInfo*
6834ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6835 const RecordData &Record,
6836 unsigned &Index) {
6837 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6838 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6839 unsigned NumArgsAsWritten = Record[Index++];
6840 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6841 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6842 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6843 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6844}
6845
Guy Benyei11169dd2012-12-18 14:30:41 +00006846Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6847 return GetDecl(ID);
6848}
6849
Richard Smith053f6c62014-05-16 23:01:30 +00006850void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006851 if (NumCurrentElementsDeserializing) {
6852 // We arrange to not care about the complete redeclaration chain while we're
6853 // deserializing. Just remember that the AST has marked this one as complete
6854 // but that it's not actually complete yet, so we know we still need to
6855 // complete it later.
6856 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6857 return;
6858 }
6859
Richard Smith053f6c62014-05-16 23:01:30 +00006860 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6861
Richard Smith053f6c62014-05-16 23:01:30 +00006862 // If this is a named declaration, complete it by looking it up
6863 // within its context.
6864 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006865 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006866 // all mergeable entities within it.
6867 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6868 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6869 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006870 if (!getContext().getLangOpts().CPlusPlus &&
6871 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006872 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006873 // the identifier instead. (For C++ modules, we don't store decls
6874 // in the serialized identifier table, so we do the lookup in the TU.)
6875 auto *II = Name.getAsIdentifierInfo();
6876 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006877 if (II->isOutOfDate())
6878 updateOutOfDateIdentifier(*II);
6879 } else
6880 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006881 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006882 // Find all declarations of this kind from the relevant context.
6883 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6884 auto *DC = cast<DeclContext>(DCDecl);
6885 SmallVector<Decl*, 8> Decls;
6886 FindExternalLexicalDecls(
6887 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6888 }
Richard Smith053f6c62014-05-16 23:01:30 +00006889 }
6890 }
Richard Smith50895422015-01-31 03:04:55 +00006891
6892 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6893 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6894 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6895 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6896 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6897 if (auto *Template = FD->getPrimaryTemplate())
6898 Template->LoadLazySpecializations();
6899 }
Richard Smith053f6c62014-05-16 23:01:30 +00006900}
6901
Richard Smithc2bb8182015-03-24 06:36:48 +00006902CXXCtorInitializer **
6903ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6904 RecordLocation Loc = getLocalBitOffset(Offset);
6905 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6906 SavedStreamPosition SavedPosition(Cursor);
6907 Cursor.JumpToBit(Loc.Offset);
6908 ReadingKindTracker ReadingKind(Read_Decl, *this);
6909
6910 RecordData Record;
6911 unsigned Code = Cursor.ReadCode();
6912 unsigned RecCode = Cursor.readRecord(Code, Record);
6913 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6914 Error("malformed AST file: missing C++ ctor initializers");
6915 return nullptr;
6916 }
6917
6918 unsigned Idx = 0;
6919 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6920}
6921
Guy Benyei11169dd2012-12-18 14:30:41 +00006922CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006923 assert(ContextObj && "reading base specifiers with no AST context");
6924 ASTContext &Context = *ContextObj;
6925
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006927 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 SavedStreamPosition SavedPosition(Cursor);
6929 Cursor.JumpToBit(Loc.Offset);
6930 ReadingKindTracker ReadingKind(Read_Decl, *this);
6931 RecordData Record;
6932 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006933 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006935 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006936 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 }
6938
6939 unsigned Idx = 0;
6940 unsigned NumBases = Record[Idx++];
6941 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6942 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6943 for (unsigned I = 0; I != NumBases; ++I)
6944 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6945 return Bases;
6946}
6947
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006948serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006949ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6950 if (LocalID < NUM_PREDEF_DECL_IDS)
6951 return LocalID;
6952
Richard Smith37a93df2017-02-18 00:32:02 +00006953 if (!F.ModuleOffsetMap.empty())
6954 ReadModuleOffsetMap(F);
6955
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6957 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6958 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006959
Guy Benyei11169dd2012-12-18 14:30:41 +00006960 return LocalID + I->second;
6961}
6962
6963bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6964 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006965 // Predefined decls aren't from any module.
6966 if (ID < NUM_PREDEF_DECL_IDS)
6967 return false;
6968
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006969 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006970 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006971}
6972
Douglas Gregor9f782892013-01-21 15:25:38 +00006973ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006975 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6977 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6978 return I->second;
6979}
6980
6981SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6982 if (ID < NUM_PREDEF_DECL_IDS)
6983 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006984
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6986
6987 if (Index > DeclsLoaded.size()) {
6988 Error("declaration ID out-of-range for AST file");
6989 return SourceLocation();
6990 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006991
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 if (Decl *D = DeclsLoaded[Index])
6993 return D->getLocation();
6994
Richard Smithcb34bd32016-03-27 07:28:06 +00006995 SourceLocation Loc;
6996 DeclCursorForID(ID, Loc);
6997 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006998}
6999
Richard Smithfe620d22015-03-05 23:24:12 +00007000static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7001 switch (ID) {
7002 case PREDEF_DECL_NULL_ID:
7003 return nullptr;
7004
7005 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7006 return Context.getTranslationUnitDecl();
7007
7008 case PREDEF_DECL_OBJC_ID_ID:
7009 return Context.getObjCIdDecl();
7010
7011 case PREDEF_DECL_OBJC_SEL_ID:
7012 return Context.getObjCSelDecl();
7013
7014 case PREDEF_DECL_OBJC_CLASS_ID:
7015 return Context.getObjCClassDecl();
7016
7017 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7018 return Context.getObjCProtocolDecl();
7019
7020 case PREDEF_DECL_INT_128_ID:
7021 return Context.getInt128Decl();
7022
7023 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7024 return Context.getUInt128Decl();
7025
7026 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7027 return Context.getObjCInstanceTypeDecl();
7028
7029 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7030 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007031
Richard Smith9b88a4c2015-07-27 05:40:23 +00007032 case PREDEF_DECL_VA_LIST_TAG:
7033 return Context.getVaListTagDecl();
7034
Charles Davisc7d5c942015-09-17 20:55:33 +00007035 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7036 return Context.getBuiltinMSVaListDecl();
7037
Richard Smithf19e1272015-03-07 00:04:49 +00007038 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7039 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007040
7041 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7042 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007043
7044 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7045 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007046
7047 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7048 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007049
7050 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7051 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007052 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007053 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007054}
7055
Richard Smithcd45dbc2014-04-19 03:48:30 +00007056Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007057 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007058 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007059 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007060 if (D) {
7061 // Track that we have merged the declaration with ID \p ID into the
7062 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007063 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007064 if (Merged.empty())
7065 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 }
Richard Smithfe620d22015-03-05 23:24:12 +00007067 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007068 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007069
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7071
7072 if (Index >= DeclsLoaded.size()) {
7073 assert(0 && "declaration ID out-of-range for AST file");
7074 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007075 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007077
7078 return DeclsLoaded[Index];
7079}
7080
7081Decl *ASTReader::GetDecl(DeclID ID) {
7082 if (ID < NUM_PREDEF_DECL_IDS)
7083 return GetExistingDecl(ID);
7084
7085 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7086
7087 if (Index >= DeclsLoaded.size()) {
7088 assert(0 && "declaration ID out-of-range for AST file");
7089 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007090 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007091 }
7092
Guy Benyei11169dd2012-12-18 14:30:41 +00007093 if (!DeclsLoaded[Index]) {
7094 ReadDeclRecord(ID);
7095 if (DeserializationListener)
7096 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7097 }
7098
7099 return DeclsLoaded[Index];
7100}
7101
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007102DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 DeclID GlobalID) {
7104 if (GlobalID < NUM_PREDEF_DECL_IDS)
7105 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007106
Guy Benyei11169dd2012-12-18 14:30:41 +00007107 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7108 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7109 ModuleFile *Owner = I->second;
7110
7111 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7112 = M.GlobalToLocalDeclIDs.find(Owner);
7113 if (Pos == M.GlobalToLocalDeclIDs.end())
7114 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007115
Guy Benyei11169dd2012-12-18 14:30:41 +00007116 return GlobalID - Owner->BaseDeclID + Pos->second;
7117}
7118
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007119serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 const RecordData &Record,
7121 unsigned &Idx) {
7122 if (Idx >= Record.size()) {
7123 Error("Corrupted AST file");
7124 return 0;
7125 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 return getGlobalDeclID(F, Record[Idx++]);
7128}
7129
7130/// \brief Resolve the offset of a statement into a statement.
7131///
7132/// This operation will read a new statement from the external
7133/// source each time it is called, and is meant to be used via a
7134/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7135Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7136 // Switch case IDs are per Decl.
7137 ClearSwitchCaseIDs();
7138
7139 // Offset here is a global offset across the entire chain.
7140 RecordLocation Loc = getLocalBitOffset(Offset);
7141 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007142 assert(NumCurrentElementsDeserializing == 0 &&
7143 "should not be called while already deserializing");
7144 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007145 return ReadStmtFromStream(*Loc.F);
7146}
7147
Richard Smith3cb15722015-08-05 22:41:45 +00007148void ASTReader::FindExternalLexicalDecls(
7149 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7150 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007151 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7152
Richard Smith9ccdd932015-08-06 22:14:12 +00007153 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007154 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7155 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7156 auto K = (Decl::Kind)+LexicalDecls[I];
7157 if (!IsKindWeWant(K))
7158 continue;
7159
7160 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7161
7162 // Don't add predefined declarations to the lexical context more
7163 // than once.
7164 if (ID < NUM_PREDEF_DECL_IDS) {
7165 if (PredefsVisited[ID])
7166 continue;
7167
7168 PredefsVisited[ID] = true;
7169 }
7170
7171 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007172 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007173 if (!DC->isDeclInLexicalTraversal(D))
7174 Decls.push_back(D);
7175 }
7176 }
7177 };
7178
7179 if (isa<TranslationUnitDecl>(DC)) {
7180 for (auto Lexical : TULexicalDecls)
7181 Visit(Lexical.first, Lexical.second);
7182 } else {
7183 auto I = LexicalDecls.find(DC);
7184 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007185 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007186 }
7187
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007189}
7190
7191namespace {
7192
7193class DeclIDComp {
7194 ASTReader &Reader;
7195 ModuleFile &Mod;
7196
7197public:
7198 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7199
7200 bool operator()(LocalDeclID L, LocalDeclID R) const {
7201 SourceLocation LHS = getLocation(L);
7202 SourceLocation RHS = getLocation(R);
7203 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7204 }
7205
7206 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7207 SourceLocation RHS = getLocation(R);
7208 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7209 }
7210
7211 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7212 SourceLocation LHS = getLocation(L);
7213 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7214 }
7215
7216 SourceLocation getLocation(LocalDeclID ID) const {
7217 return Reader.getSourceManager().getFileLoc(
7218 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7219 }
7220};
7221
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007222} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007223
7224void ASTReader::FindFileRegionDecls(FileID File,
7225 unsigned Offset, unsigned Length,
7226 SmallVectorImpl<Decl *> &Decls) {
7227 SourceManager &SM = getSourceManager();
7228
7229 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7230 if (I == FileDeclIDs.end())
7231 return;
7232
7233 FileDeclsInfo &DInfo = I->second;
7234 if (DInfo.Decls.empty())
7235 return;
7236
7237 SourceLocation
7238 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7239 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7240
7241 DeclIDComp DIDComp(*this, *DInfo.Mod);
7242 ArrayRef<serialization::LocalDeclID>::iterator
7243 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7244 BeginLoc, DIDComp);
7245 if (BeginIt != DInfo.Decls.begin())
7246 --BeginIt;
7247
7248 // If we are pointing at a top-level decl inside an objc container, we need
7249 // to backtrack until we find it otherwise we will fail to report that the
7250 // region overlaps with an objc container.
7251 while (BeginIt != DInfo.Decls.begin() &&
7252 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7253 ->isTopLevelDeclInObjCContainer())
7254 --BeginIt;
7255
7256 ArrayRef<serialization::LocalDeclID>::iterator
7257 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7258 EndLoc, DIDComp);
7259 if (EndIt != DInfo.Decls.end())
7260 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007261
Guy Benyei11169dd2012-12-18 14:30:41 +00007262 for (ArrayRef<serialization::LocalDeclID>::iterator
7263 DIt = BeginIt; DIt != EndIt; ++DIt)
7264 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7265}
7266
Richard Smith9ce12e32013-02-07 03:30:24 +00007267bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007268ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7269 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007270 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 "DeclContext has no visible decls in storage");
7272 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007273 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007274
Richard Smithd88a7f12015-09-01 20:35:42 +00007275 auto It = Lookups.find(DC);
7276 if (It == Lookups.end())
7277 return false;
7278
Richard Smith8c913ec2014-08-14 02:21:01 +00007279 Deserializing LookupResults(this);
7280
Richard Smithd88a7f12015-09-01 20:35:42 +00007281 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007283 for (DeclID ID : It->second.Table.find(Name)) {
7284 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7285 if (ND->getDeclName() == Name)
7286 Decls.push_back(ND);
7287 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007288
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 ++NumVisibleDeclContextsRead;
7290 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007291 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007292}
7293
Guy Benyei11169dd2012-12-18 14:30:41 +00007294void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7295 if (!DC->hasExternalVisibleStorage())
7296 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007297
7298 auto It = Lookups.find(DC);
7299 assert(It != Lookups.end() &&
7300 "have external visible storage but no lookup tables");
7301
Craig Topper79be4cd2013-07-05 04:33:53 +00007302 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007303
Richard Smithd88a7f12015-09-01 20:35:42 +00007304 for (DeclID ID : It->second.Table.findAll()) {
7305 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7306 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007307 }
7308
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 ++NumVisibleDeclContextsRead;
7310
Craig Topper79be4cd2013-07-05 04:33:53 +00007311 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007312 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7313 }
7314 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7315}
7316
Richard Smithd88a7f12015-09-01 20:35:42 +00007317const serialization::reader::DeclContextLookupTable *
7318ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7319 auto I = Lookups.find(Primary);
7320 return I == Lookups.end() ? nullptr : &I->second;
7321}
7322
Guy Benyei11169dd2012-12-18 14:30:41 +00007323/// \brief Under non-PCH compilation the consumer receives the objc methods
7324/// before receiving the implementation, and codegen depends on this.
7325/// We simulate this by deserializing and passing to consumer the methods of the
7326/// implementation before passing the deserialized implementation decl.
7327static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7328 ASTConsumer *Consumer) {
7329 assert(ImplD && Consumer);
7330
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007331 for (auto *I : ImplD->methods())
7332 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007333
7334 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7335}
7336
Guy Benyei11169dd2012-12-18 14:30:41 +00007337void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7338 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7339 PassObjCImplDeclToConsumer(ImplD, Consumer);
7340 else
7341 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7342}
7343
7344void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7345 this->Consumer = Consumer;
7346
Richard Smith9e2341d2015-03-23 03:25:59 +00007347 if (Consumer)
7348 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007349
7350 if (DeserializationListener)
7351 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007352}
7353
7354void ASTReader::PrintStats() {
7355 std::fprintf(stderr, "*** AST File Statistics:\n");
7356
7357 unsigned NumTypesLoaded
7358 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7359 QualType());
7360 unsigned NumDeclsLoaded
7361 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007362 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007363 unsigned NumIdentifiersLoaded
7364 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7365 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007366 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 unsigned NumMacrosLoaded
7368 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7369 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007370 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007371 unsigned NumSelectorsLoaded
7372 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7373 SelectorsLoaded.end(),
7374 Selector());
7375
7376 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7377 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7378 NumSLocEntriesRead, TotalNumSLocEntries,
7379 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7380 if (!TypesLoaded.empty())
7381 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7382 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7383 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7384 if (!DeclsLoaded.empty())
7385 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7386 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7387 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7388 if (!IdentifiersLoaded.empty())
7389 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7390 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7391 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7392 if (!MacrosLoaded.empty())
7393 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7394 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7395 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7396 if (!SelectorsLoaded.empty())
7397 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7398 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7399 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7400 if (TotalNumStatements)
7401 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7402 NumStatementsRead, TotalNumStatements,
7403 ((float)NumStatementsRead/TotalNumStatements * 100));
7404 if (TotalNumMacros)
7405 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7406 NumMacrosRead, TotalNumMacros,
7407 ((float)NumMacrosRead/TotalNumMacros * 100));
7408 if (TotalLexicalDeclContexts)
7409 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7410 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7411 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7412 * 100));
7413 if (TotalVisibleDeclContexts)
7414 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7415 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7416 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7417 * 100));
7418 if (TotalNumMethodPoolEntries) {
7419 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7420 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7421 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7422 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007424 if (NumMethodPoolLookups) {
7425 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7426 NumMethodPoolHits, NumMethodPoolLookups,
7427 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7428 }
7429 if (NumMethodPoolTableLookups) {
7430 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7431 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7432 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7433 * 100.0));
7434 }
7435
Douglas Gregor00a50f72013-01-25 00:38:33 +00007436 if (NumIdentifierLookupHits) {
7437 std::fprintf(stderr,
7438 " %u / %u identifier table lookups succeeded (%f%%)\n",
7439 NumIdentifierLookupHits, NumIdentifierLookups,
7440 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7441 }
7442
Douglas Gregore060e572013-01-25 01:03:03 +00007443 if (GlobalIndex) {
7444 std::fprintf(stderr, "\n");
7445 GlobalIndex->printStats();
7446 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007447
Guy Benyei11169dd2012-12-18 14:30:41 +00007448 std::fprintf(stderr, "\n");
7449 dump();
7450 std::fprintf(stderr, "\n");
7451}
7452
7453template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007454LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007455dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007456 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 InitialCapacity> &Map) {
7458 if (Map.begin() == Map.end())
7459 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007460
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7462 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007463 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 I != IEnd; ++I) {
7465 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7466 << "\n";
7467 }
7468}
7469
Yaron Kerencdae9412016-01-29 19:38:18 +00007470LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7472 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7473 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7474 dumpModuleIDMap("Global type map", GlobalTypeMap);
7475 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7476 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7477 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7478 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7479 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007480 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007482
Guy Benyei11169dd2012-12-18 14:30:41 +00007483 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007484 for (ModuleFile &M : ModuleMgr)
7485 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007486}
7487
7488/// Return the amount of memory used by memory buffers, breaking down
7489/// by heap-backed versus mmap'ed memory.
7490void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007491 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007492 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007493 size_t bytes = buf->getBufferSize();
7494 switch (buf->getBufferKind()) {
7495 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7496 sizes.malloc_bytes += bytes;
7497 break;
7498 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7499 sizes.mmap_bytes += bytes;
7500 break;
7501 }
7502 }
7503 }
7504}
7505
7506void ASTReader::InitializeSema(Sema &S) {
7507 SemaObj = &S;
7508 S.addExternalSource(this);
7509
7510 // Makes sure any declarations that were deserialized "too early"
7511 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007512 for (uint64_t ID : PreloadedDeclIDs) {
7513 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7514 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007516 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007517
Richard Smith3d8e97e2013-10-18 06:54:39 +00007518 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 if (!FPPragmaOptions.empty()) {
7520 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007521 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007522 }
7523
Yaxun Liu5b746652016-12-18 05:18:55 +00007524 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7525 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7526 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007527
7528 UpdateSema();
7529}
7530
7531void ASTReader::UpdateSema() {
7532 assert(SemaObj && "no Sema to update");
7533
7534 // Load the offsets of the declarations that Sema references.
7535 // They will be lazily deserialized when needed.
7536 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007537 assert(SemaDeclRefs.size() % 3 == 0);
7538 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007539 if (!SemaObj->StdNamespace)
7540 SemaObj->StdNamespace = SemaDeclRefs[I];
7541 if (!SemaObj->StdBadAlloc)
7542 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007543 if (!SemaObj->StdAlignValT)
7544 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007545 }
7546 SemaDeclRefs.clear();
7547 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007548
Nico Weber779355f2016-03-02 23:22:00 +00007549 // Update the state of pragmas. Use the same API as if we had encountered the
7550 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007551 if(OptimizeOffPragmaLocation.isValid())
7552 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007553 if (PragmaMSStructState != -1)
7554 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007555 if (PointersToMembersPragmaLocation.isValid()) {
7556 SemaObj->ActOnPragmaMSPointersToMembers(
7557 (LangOptions::PragmaMSPointersToMembersKind)
7558 PragmaMSPointersToMembersState,
7559 PointersToMembersPragmaLocation);
7560 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007561 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007562
7563 if (PragmaPackCurrentValue) {
7564 // The bottom of the stack might have a default value. It must be adjusted
7565 // to the current value to ensure that the packing state is preserved after
7566 // popping entries that were included/imported from a PCH/module.
7567 bool DropFirst = false;
7568 if (!PragmaPackStack.empty() &&
7569 PragmaPackStack.front().Location.isInvalid()) {
7570 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7571 "Expected a default alignment value");
7572 SemaObj->PackStack.Stack.emplace_back(
7573 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007574 SemaObj->PackStack.CurrentPragmaLocation,
7575 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007576 DropFirst = true;
7577 }
7578 for (const auto &Entry :
7579 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7580 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007581 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007582 if (PragmaPackCurrentLocation.isInvalid()) {
7583 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7584 "Expected a default alignment value");
7585 // Keep the current values.
7586 } else {
7587 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7588 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7589 }
7590 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007591}
7592
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007593IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007594 // Note that we are loading an identifier.
7595 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007596
Douglas Gregor7211ac12013-01-25 23:32:03 +00007597 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007598 NumIdentifierLookups,
7599 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007600
7601 // We don't need to do identifier table lookups in C++ modules (we preload
7602 // all interesting declarations, and don't need to use the scope for name
7603 // lookups). Perform the lookup in PCH files, though, since we don't build
7604 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007605 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007606 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007607 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007608 break;
7609 } else {
7610 // If there is a global index, look there first to determine which modules
7611 // provably do not have any results for this identifier.
7612 GlobalModuleIndex::HitSet Hits;
7613 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7614 if (!loadGlobalIndex()) {
7615 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7616 HitsPtr = &Hits;
7617 }
7618 }
7619
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007620 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007621 }
7622
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 IdentifierInfo *II = Visitor.getIdentifierInfo();
7624 markIdentifierUpToDate(II);
7625 return II;
7626}
7627
7628namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007629
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 /// \brief An identifier-lookup iterator that enumerates all of the
7631 /// identifiers stored within a set of AST files.
7632 class ASTIdentifierIterator : public IdentifierIterator {
7633 /// \brief The AST reader whose identifiers are being enumerated.
7634 const ASTReader &Reader;
7635
7636 /// \brief The current index into the chain of AST files stored in
7637 /// the AST reader.
7638 unsigned Index;
7639
7640 /// \brief The current position within the identifier lookup table
7641 /// of the current AST file.
7642 ASTIdentifierLookupTable::key_iterator Current;
7643
7644 /// \brief The end position within the identifier lookup table of
7645 /// the current AST file.
7646 ASTIdentifierLookupTable::key_iterator End;
7647
Ben Langmuir537c5b52016-05-04 00:53:13 +00007648 /// \brief Whether to skip any modules in the ASTReader.
7649 bool SkipModules;
7650
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007652 explicit ASTIdentifierIterator(const ASTReader &Reader,
7653 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007654
Craig Topper3e89dfe2014-03-13 02:13:41 +00007655 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007657
7658} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007659
Ben Langmuir537c5b52016-05-04 00:53:13 +00007660ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7661 bool SkipModules)
7662 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007663}
7664
7665StringRef ASTIdentifierIterator::Next() {
7666 while (Current == End) {
7667 // If we have exhausted all of our AST files, we're done.
7668 if (Index == 0)
7669 return StringRef();
7670
7671 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007672 ModuleFile &F = Reader.ModuleMgr[Index];
7673 if (SkipModules && F.isModule())
7674 continue;
7675
7676 ASTIdentifierLookupTable *IdTable =
7677 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 Current = IdTable->key_begin();
7679 End = IdTable->key_end();
7680 }
7681
7682 // We have any identifiers remaining in the current AST file; return
7683 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007684 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007686 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007687}
7688
Ben Langmuir537c5b52016-05-04 00:53:13 +00007689namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007690
Ben Langmuir537c5b52016-05-04 00:53:13 +00007691/// A utility for appending two IdentifierIterators.
7692class ChainedIdentifierIterator : public IdentifierIterator {
7693 std::unique_ptr<IdentifierIterator> Current;
7694 std::unique_ptr<IdentifierIterator> Queued;
7695
7696public:
7697 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7698 std::unique_ptr<IdentifierIterator> Second)
7699 : Current(std::move(First)), Queued(std::move(Second)) {}
7700
7701 StringRef Next() override {
7702 if (!Current)
7703 return StringRef();
7704
7705 StringRef result = Current->Next();
7706 if (!result.empty())
7707 return result;
7708
7709 // Try the queued iterator, which may itself be empty.
7710 Current.reset();
7711 std::swap(Current, Queued);
7712 return Next();
7713 }
7714};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007715
Ben Langmuir537c5b52016-05-04 00:53:13 +00007716} // end anonymous namespace.
7717
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007718IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007719 if (!loadGlobalIndex()) {
7720 std::unique_ptr<IdentifierIterator> ReaderIter(
7721 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7722 std::unique_ptr<IdentifierIterator> ModulesIter(
7723 GlobalIndex->createIdentifierIterator());
7724 return new ChainedIdentifierIterator(std::move(ReaderIter),
7725 std::move(ModulesIter));
7726 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007727
Guy Benyei11169dd2012-12-18 14:30:41 +00007728 return new ASTIdentifierIterator(*this);
7729}
7730
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007731namespace clang {
7732namespace serialization {
7733
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 class ReadMethodPoolVisitor {
7735 ASTReader &Reader;
7736 Selector Sel;
7737 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007738 unsigned InstanceBits;
7739 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007740 bool InstanceHasMoreThanOneDecl;
7741 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007742 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7743 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007744
7745 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007746 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007748 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007749 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7750 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007751
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007752 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 if (!M.SelectorLookupTable)
7754 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007755
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007757 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007758 return true;
7759
Richard Smithbdf2d932015-07-30 03:37:16 +00007760 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007761 ASTSelectorLookupTable *PoolTable
7762 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007763 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 if (Pos == PoolTable->end())
7765 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007766
Richard Smithbdf2d932015-07-30 03:37:16 +00007767 ++Reader.NumMethodPoolTableHits;
7768 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007769 // FIXME: Not quite happy with the statistics here. We probably should
7770 // disable this tracking when called via LoadSelector.
7771 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007772 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007774 if (Reader.DeserializationListener)
7775 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007776
Richard Smithbdf2d932015-07-30 03:37:16 +00007777 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7778 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7779 InstanceBits = Data.InstanceBits;
7780 FactoryBits = Data.FactoryBits;
7781 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7782 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007783 return true;
7784 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007785
Guy Benyei11169dd2012-12-18 14:30:41 +00007786 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007787 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7788 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 }
7790
7791 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007792 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 return FactoryMethods;
7794 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007795
7796 unsigned getInstanceBits() const { return InstanceBits; }
7797 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007798 bool instanceHasMoreThanOneDecl() const {
7799 return InstanceHasMoreThanOneDecl;
7800 }
7801 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007802 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007803
7804} // end namespace serialization
7805} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007806
7807/// \brief Add the given set of methods to the method list.
7808static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7809 ObjCMethodList &List) {
7810 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7811 S.addMethodToGlobalList(&List, Methods[I]);
7812 }
7813}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007814
Guy Benyei11169dd2012-12-18 14:30:41 +00007815void ASTReader::ReadMethodPool(Selector Sel) {
7816 // Get the selector generation and update it to the current generation.
7817 unsigned &Generation = SelectorGeneration[Sel];
7818 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007819 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007820 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007821
Guy Benyei11169dd2012-12-18 14:30:41 +00007822 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007823 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007824 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007825 ModuleMgr.visit(Visitor);
7826
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007828 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007829 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007830
7831 ++NumMethodPoolHits;
7832
Guy Benyei11169dd2012-12-18 14:30:41 +00007833 if (!getSema())
7834 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007835
Guy Benyei11169dd2012-12-18 14:30:41 +00007836 Sema &S = *getSema();
7837 Sema::GlobalMethodPool::iterator Pos
7838 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007839
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007840 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007841 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007842 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007843 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007844
7845 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7846 // when building a module we keep every method individually and may need to
7847 // update hasMoreThanOneDecl as we add the methods.
7848 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7849 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007850}
7851
Manman Rena0f31a02016-04-29 19:04:05 +00007852void ASTReader::updateOutOfDateSelector(Selector Sel) {
7853 if (SelectorOutOfDate[Sel])
7854 ReadMethodPool(Sel);
7855}
7856
Guy Benyei11169dd2012-12-18 14:30:41 +00007857void ASTReader::ReadKnownNamespaces(
7858 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7859 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007860
Guy Benyei11169dd2012-12-18 14:30:41 +00007861 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007862 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007863 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7864 Namespaces.push_back(Namespace);
7865 }
7866}
7867
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007868void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007869 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007870 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7871 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007872 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007873 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007874 Undefined.insert(std::make_pair(D, Loc));
7875 }
7876}
Nick Lewycky8334af82013-01-26 00:35:08 +00007877
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007878void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7879 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7880 Exprs) {
7881 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7882 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7883 uint64_t Count = DelayedDeleteExprs[Idx++];
7884 for (uint64_t C = 0; C < Count; ++C) {
7885 SourceLocation DeleteLoc =
7886 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7887 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7888 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7889 }
7890 }
7891}
7892
Guy Benyei11169dd2012-12-18 14:30:41 +00007893void ASTReader::ReadTentativeDefinitions(
7894 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7895 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7896 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7897 if (Var)
7898 TentativeDefs.push_back(Var);
7899 }
7900 TentativeDefinitions.clear();
7901}
7902
7903void ASTReader::ReadUnusedFileScopedDecls(
7904 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7905 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7906 DeclaratorDecl *D
7907 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7908 if (D)
7909 Decls.push_back(D);
7910 }
7911 UnusedFileScopedDecls.clear();
7912}
7913
7914void ASTReader::ReadDelegatingConstructors(
7915 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7916 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7917 CXXConstructorDecl *D
7918 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7919 if (D)
7920 Decls.push_back(D);
7921 }
7922 DelegatingCtorDecls.clear();
7923}
7924
7925void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7926 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7927 TypedefNameDecl *D
7928 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7929 if (D)
7930 Decls.push_back(D);
7931 }
7932 ExtVectorDecls.clear();
7933}
7934
Nico Weber72889432014-09-06 01:25:55 +00007935void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7936 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7937 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7938 ++I) {
7939 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7940 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7941 if (D)
7942 Decls.insert(D);
7943 }
7944 UnusedLocalTypedefNameCandidates.clear();
7945}
7946
Guy Benyei11169dd2012-12-18 14:30:41 +00007947void ASTReader::ReadReferencedSelectors(
7948 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7949 if (ReferencedSelectorsData.empty())
7950 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007951
Guy Benyei11169dd2012-12-18 14:30:41 +00007952 // If there are @selector references added them to its pool. This is for
7953 // implementation of -Wselector.
7954 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7955 unsigned I = 0;
7956 while (I < DataSize) {
7957 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7958 SourceLocation SelLoc
7959 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7960 Sels.push_back(std::make_pair(Sel, SelLoc));
7961 }
7962 ReferencedSelectorsData.clear();
7963}
7964
7965void ASTReader::ReadWeakUndeclaredIdentifiers(
7966 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7967 if (WeakUndeclaredIdentifiers.empty())
7968 return;
7969
7970 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007971 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007973 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7975 SourceLocation Loc
7976 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7977 bool Used = WeakUndeclaredIdentifiers[I++];
7978 WeakInfo WI(AliasId, Loc);
7979 WI.setUsed(Used);
7980 WeakIDs.push_back(std::make_pair(WeakId, WI));
7981 }
7982 WeakUndeclaredIdentifiers.clear();
7983}
7984
7985void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7986 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7987 ExternalVTableUse VT;
7988 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7989 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7990 VT.DefinitionRequired = VTableUses[Idx++];
7991 VTables.push_back(VT);
7992 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007993
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 VTableUses.clear();
7995}
7996
7997void ASTReader::ReadPendingInstantiations(
7998 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7999 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8000 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8001 SourceLocation Loc
8002 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8003
8004 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 PendingInstantiations.clear();
8007}
8008
Richard Smithe40f2ba2013-08-07 21:41:30 +00008009void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008010 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8011 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008012 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8013 /* In loop */) {
8014 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8015
Justin Lebar28f09c52016-10-10 16:26:08 +00008016 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008017 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8018
8019 ModuleFile *F = getOwningModuleFile(LT->D);
8020 assert(F && "No module");
8021
8022 unsigned TokN = LateParsedTemplates[Idx++];
8023 LT->Toks.reserve(TokN);
8024 for (unsigned T = 0; T < TokN; ++T)
8025 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8026
Justin Lebar28f09c52016-10-10 16:26:08 +00008027 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008028 }
8029
8030 LateParsedTemplates.clear();
8031}
8032
Guy Benyei11169dd2012-12-18 14:30:41 +00008033void ASTReader::LoadSelector(Selector Sel) {
8034 // It would be complicated to avoid reading the methods anyway. So don't.
8035 ReadMethodPool(Sel);
8036}
8037
8038void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8039 assert(ID && "Non-zero identifier ID required");
8040 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8041 IdentifiersLoaded[ID - 1] = II;
8042 if (DeserializationListener)
8043 DeserializationListener->IdentifierRead(ID, II);
8044}
8045
8046/// \brief Set the globally-visible declarations associated with the given
8047/// identifier.
8048///
8049/// If the AST reader is currently in a state where the given declaration IDs
8050/// cannot safely be resolved, they are queued until it is safe to resolve
8051/// them.
8052///
8053/// \param II an IdentifierInfo that refers to one or more globally-visible
8054/// declarations.
8055///
8056/// \param DeclIDs the set of declaration IDs with the name @p II that are
8057/// visible at global scope.
8058///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008059/// \param Decls if non-null, this vector will be populated with the set of
8060/// deserialized declarations. These declarations will not be pushed into
8061/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008062void
8063ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8064 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008065 SmallVectorImpl<Decl *> *Decls) {
8066 if (NumCurrentElementsDeserializing && !Decls) {
8067 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 return;
8069 }
8070
8071 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008072 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 // Queue this declaration so that it will be added to the
8074 // translation unit scope and identifier's declaration chain
8075 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00008076 PreloadedDeclIDs.push_back(DeclIDs[I]);
8077 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008079
8080 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8081
8082 // If we're simply supposed to record the declarations, do so now.
8083 if (Decls) {
8084 Decls->push_back(D);
8085 continue;
8086 }
8087
8088 // Introduce this declaration into the translation-unit scope
8089 // and add it to the declaration chain for this identifier, so
8090 // that (unqualified) name lookup will find it.
8091 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008092 }
8093}
8094
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008095IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008096 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008097 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008098
8099 if (IdentifiersLoaded.empty()) {
8100 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008102 }
8103
8104 ID -= 1;
8105 if (!IdentifiersLoaded[ID]) {
8106 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8107 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8108 ModuleFile *M = I->second;
8109 unsigned Index = ID - M->BaseIdentifierID;
8110 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8111
8112 // All of the strings in the AST file are preceded by a 16-bit length.
8113 // Extract that 16-bit length to avoid having to execute strlen().
8114 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8115 // unsigned integers. This is important to avoid integer overflow when
8116 // we cast them to 'unsigned'.
8117 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8118 unsigned StrLen = (((unsigned) StrLenPtr[0])
8119 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008120 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8121 IdentifiersLoaded[ID] = &II;
8122 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008124 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 }
8126
8127 return IdentifiersLoaded[ID];
8128}
8129
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008130IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8131 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008132}
8133
8134IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8135 if (LocalID < NUM_PREDEF_IDENT_IDS)
8136 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008137
Richard Smith37a93df2017-02-18 00:32:02 +00008138 if (!M.ModuleOffsetMap.empty())
8139 ReadModuleOffsetMap(M);
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8142 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008143 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008145
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 return LocalID + I->second;
8147}
8148
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008149MacroInfo *ASTReader::getMacro(MacroID 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 (MacrosLoaded.empty()) {
8154 Error("no macro 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 -= NUM_PREDEF_MACRO_IDS;
8159 if (!MacrosLoaded[ID]) {
8160 GlobalMacroMapType::iterator I
8161 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8162 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8163 ModuleFile *M = I->second;
8164 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008165 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008166
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008167 if (DeserializationListener)
8168 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8169 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 }
8171
8172 return MacrosLoaded[ID];
8173}
8174
8175MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8176 if (LocalID < NUM_PREDEF_MACRO_IDS)
8177 return LocalID;
8178
Richard Smith37a93df2017-02-18 00:32:02 +00008179 if (!M.ModuleOffsetMap.empty())
8180 ReadModuleOffsetMap(M);
8181
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8183 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8184 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8185
8186 return LocalID + I->second;
8187}
8188
8189serialization::SubmoduleID
8190ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8191 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8192 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008193
Richard Smith37a93df2017-02-18 00:32:02 +00008194 if (!M.ModuleOffsetMap.empty())
8195 ReadModuleOffsetMap(M);
8196
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8198 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008199 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008201
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 return LocalID + I->second;
8203}
8204
8205Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8206 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8207 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008208 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008210
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 if (GlobalID > SubmodulesLoaded.size()) {
8212 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008213 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008215
Guy Benyei11169dd2012-12-18 14:30:41 +00008216 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8217}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008218
8219Module *ASTReader::getModule(unsigned ID) {
8220 return getSubmodule(ID);
8221}
8222
Richard Smithd88a7f12015-09-01 20:35:42 +00008223ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8224 if (ID & 1) {
8225 // It's a module, look it up by submodule ID.
8226 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8227 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8228 } else {
8229 // It's a prefix (preamble, PCH, ...). Look it up by index.
8230 unsigned IndexFromEnd = ID >> 1;
8231 assert(IndexFromEnd && "got reference to unknown module file");
8232 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8233 }
8234}
8235
8236unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8237 if (!F)
8238 return 1;
8239
8240 // For a file representing a module, use the submodule ID of the top-level
8241 // module as the file ID. For any other kind of file, the number of such
8242 // files loaded beforehand will be the same on reload.
8243 // FIXME: Is this true even if we have an explicit module file and a PCH?
8244 if (F->isModule())
8245 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8246
8247 auto PCHModules = getModuleManager().pch_modules();
8248 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8249 assert(I != PCHModules.end() && "emitting reference to unknown file");
8250 return (I - PCHModules.end()) << 1;
8251}
8252
Adrian Prantl15bcf702015-06-30 17:39:43 +00008253llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8254ASTReader::getSourceDescriptor(unsigned ID) {
8255 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008256 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008257
8258 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008259 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008260 const auto &PCHChain = ModuleMgr.pch_modules();
8261 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008262 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008263 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008264 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8265 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8266 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008267 }
8268 return None;
8269}
8270
David Blaikie1ac9c982017-04-11 21:13:37 +00008271ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
David Blaikiee6b7c282017-04-11 20:46:34 +00008272 auto I = BodySource.find(FD);
8273 if (I == BodySource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008274 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008275 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008276}
8277
Guy Benyei11169dd2012-12-18 14:30:41 +00008278Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8279 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8280}
8281
8282Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8283 if (ID == 0)
8284 return Selector();
8285
8286 if (ID > SelectorsLoaded.size()) {
8287 Error("selector ID out of range in AST file");
8288 return Selector();
8289 }
8290
Craig Toppera13603a2014-05-22 05:54:18 +00008291 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008292 // Load this selector from the selector table.
8293 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8294 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8295 ModuleFile &M = *I->second;
8296 ASTSelectorLookupTrait Trait(*this, M);
8297 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8298 SelectorsLoaded[ID - 1] =
8299 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8300 if (DeserializationListener)
8301 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8302 }
8303
8304 return SelectorsLoaded[ID - 1];
8305}
8306
8307Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8308 return DecodeSelector(ID);
8309}
8310
8311uint32_t ASTReader::GetNumExternalSelectors() {
8312 // ID 0 (the null selector) is considered an external selector.
8313 return getTotalNumSelectors() + 1;
8314}
8315
8316serialization::SelectorID
8317ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8318 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8319 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008320
Richard Smith37a93df2017-02-18 00:32:02 +00008321 if (!M.ModuleOffsetMap.empty())
8322 ReadModuleOffsetMap(M);
8323
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8325 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008326 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008327 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008328
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 return LocalID + I->second;
8330}
8331
8332DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008333ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008334 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008335 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008336 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8337 switch (Kind) {
8338 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008339 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008340
8341 case DeclarationName::ObjCZeroArgSelector:
8342 case DeclarationName::ObjCOneArgSelector:
8343 case DeclarationName::ObjCMultiArgSelector:
8344 return DeclarationName(ReadSelector(F, Record, Idx));
8345
8346 case DeclarationName::CXXConstructorName:
8347 return Context.DeclarationNames.getCXXConstructorName(
8348 Context.getCanonicalType(readType(F, Record, Idx)));
8349
8350 case DeclarationName::CXXDestructorName:
8351 return Context.DeclarationNames.getCXXDestructorName(
8352 Context.getCanonicalType(readType(F, Record, Idx)));
8353
Richard Smith35845152017-02-07 01:37:30 +00008354 case DeclarationName::CXXDeductionGuideName:
8355 return Context.DeclarationNames.getCXXDeductionGuideName(
8356 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8357
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 case DeclarationName::CXXConversionFunctionName:
8359 return Context.DeclarationNames.getCXXConversionFunctionName(
8360 Context.getCanonicalType(readType(F, Record, Idx)));
8361
8362 case DeclarationName::CXXOperatorName:
8363 return Context.DeclarationNames.getCXXOperatorName(
8364 (OverloadedOperatorKind)Record[Idx++]);
8365
8366 case DeclarationName::CXXLiteralOperatorName:
8367 return Context.DeclarationNames.getCXXLiteralOperatorName(
8368 GetIdentifierInfo(F, Record, Idx));
8369
8370 case DeclarationName::CXXUsingDirective:
8371 return DeclarationName::getUsingDirectiveName();
8372 }
8373
8374 llvm_unreachable("Invalid NameKind!");
8375}
8376
8377void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8378 DeclarationNameLoc &DNLoc,
8379 DeclarationName Name,
8380 const RecordData &Record, unsigned &Idx) {
8381 switch (Name.getNameKind()) {
8382 case DeclarationName::CXXConstructorName:
8383 case DeclarationName::CXXDestructorName:
8384 case DeclarationName::CXXConversionFunctionName:
8385 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8386 break;
8387
8388 case DeclarationName::CXXOperatorName:
8389 DNLoc.CXXOperatorName.BeginOpNameLoc
8390 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8391 DNLoc.CXXOperatorName.EndOpNameLoc
8392 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8393 break;
8394
8395 case DeclarationName::CXXLiteralOperatorName:
8396 DNLoc.CXXLiteralOperatorName.OpNameLoc
8397 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8398 break;
8399
8400 case DeclarationName::Identifier:
8401 case DeclarationName::ObjCZeroArgSelector:
8402 case DeclarationName::ObjCOneArgSelector:
8403 case DeclarationName::ObjCMultiArgSelector:
8404 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008405 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008406 break;
8407 }
8408}
8409
8410void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8411 DeclarationNameInfo &NameInfo,
8412 const RecordData &Record, unsigned &Idx) {
8413 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8414 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8415 DeclarationNameLoc DNLoc;
8416 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8417 NameInfo.setInfo(DNLoc);
8418}
8419
8420void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8421 const RecordData &Record, unsigned &Idx) {
8422 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8423 unsigned NumTPLists = Record[Idx++];
8424 Info.NumTemplParamLists = NumTPLists;
8425 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008426 Info.TemplParamLists =
8427 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008428 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8430 }
8431}
8432
8433TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008434ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008435 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008436 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8438 switch (Kind) {
8439 case TemplateName::Template:
8440 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8441
8442 case TemplateName::OverloadedTemplate: {
8443 unsigned size = Record[Idx++];
8444 UnresolvedSet<8> Decls;
8445 while (size--)
8446 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8447
8448 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8449 }
8450
8451 case TemplateName::QualifiedTemplate: {
8452 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8453 bool hasTemplKeyword = Record[Idx++];
8454 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8455 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8456 }
8457
8458 case TemplateName::DependentTemplate: {
8459 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8460 if (Record[Idx++]) // isIdentifier
8461 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008462 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 Idx));
8464 return Context.getDependentTemplateName(NNS,
8465 (OverloadedOperatorKind)Record[Idx++]);
8466 }
8467
8468 case TemplateName::SubstTemplateTemplateParm: {
8469 TemplateTemplateParmDecl *param
8470 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8471 if (!param) return TemplateName();
8472 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8473 return Context.getSubstTemplateTemplateParm(param, replacement);
8474 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008475
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008477 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008478 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8479 if (!Param)
8480 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008481
Guy Benyei11169dd2012-12-18 14:30:41 +00008482 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8483 if (ArgPack.getKind() != TemplateArgument::Pack)
8484 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008485
Guy Benyei11169dd2012-12-18 14:30:41 +00008486 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8487 }
8488 }
8489
8490 llvm_unreachable("Unhandled template name kind!");
8491}
8492
Richard Smith2bb3c342015-08-09 01:05:31 +00008493TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8494 const RecordData &Record,
8495 unsigned &Idx,
8496 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008497 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008498 if (Canonicalize) {
8499 // The caller wants a canonical template argument. Sometimes the AST only
8500 // wants template arguments in canonical form (particularly as the template
8501 // argument lists of template specializations) so ensure we preserve that
8502 // canonical form across serialization.
8503 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8504 return Context.getCanonicalTemplateArgument(Arg);
8505 }
8506
Guy Benyei11169dd2012-12-18 14:30:41 +00008507 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8508 switch (Kind) {
8509 case TemplateArgument::Null:
8510 return TemplateArgument();
8511 case TemplateArgument::Type:
8512 return TemplateArgument(readType(F, Record, Idx));
8513 case TemplateArgument::Declaration: {
8514 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008515 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008516 }
8517 case TemplateArgument::NullPtr:
8518 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8519 case TemplateArgument::Integral: {
8520 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8521 QualType T = readType(F, Record, Idx);
8522 return TemplateArgument(Context, Value, T);
8523 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008524 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8526 case TemplateArgument::TemplateExpansion: {
8527 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008528 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 if (unsigned NumExpansions = Record[Idx++])
8530 NumTemplateExpansions = NumExpansions - 1;
8531 return TemplateArgument(Name, NumTemplateExpansions);
8532 }
8533 case TemplateArgument::Expression:
8534 return TemplateArgument(ReadExpr(F));
8535 case TemplateArgument::Pack: {
8536 unsigned NumArgs = Record[Idx++];
8537 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8538 for (unsigned I = 0; I != NumArgs; ++I)
8539 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008540 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 }
8542 }
8543
8544 llvm_unreachable("Unhandled template argument kind!");
8545}
8546
8547TemplateParameterList *
8548ASTReader::ReadTemplateParameterList(ModuleFile &F,
8549 const RecordData &Record, unsigned &Idx) {
8550 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8551 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8552 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8553
8554 unsigned NumParams = Record[Idx++];
8555 SmallVector<NamedDecl *, 16> Params;
8556 Params.reserve(NumParams);
8557 while (NumParams--)
8558 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8559
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008560 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008561 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8562 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008563 return TemplateParams;
8564}
8565
8566void
8567ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008568ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008569 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008570 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 unsigned NumTemplateArgs = Record[Idx++];
8572 TemplArgs.reserve(NumTemplateArgs);
8573 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008574 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008575}
8576
8577/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008578void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008579 const RecordData &Record, unsigned &Idx) {
8580 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008581 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008583 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008584 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008585 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008586 }
8587}
8588
8589CXXBaseSpecifier
8590ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8591 const RecordData &Record, unsigned &Idx) {
8592 bool isVirtual = static_cast<bool>(Record[Idx++]);
8593 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8594 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8595 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8596 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8597 SourceRange Range = ReadSourceRange(F, Record, Idx);
8598 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008599 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008600 EllipsisLoc);
8601 Result.setInheritConstructors(inheritConstructors);
8602 return Result;
8603}
8604
Richard Smithc2bb8182015-03-24 06:36:48 +00008605CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008606ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8607 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008608 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008609 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008610 assert(NumInitializers && "wrote ctor initializers but have no inits");
8611 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8612 for (unsigned i = 0; i != NumInitializers; ++i) {
8613 TypeSourceInfo *TInfo = nullptr;
8614 bool IsBaseVirtual = false;
8615 FieldDecl *Member = nullptr;
8616 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008617
Richard Smithc2bb8182015-03-24 06:36:48 +00008618 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8619 switch (Type) {
8620 case CTOR_INITIALIZER_BASE:
8621 TInfo = GetTypeSourceInfo(F, Record, Idx);
8622 IsBaseVirtual = Record[Idx++];
8623 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008624
Richard Smithc2bb8182015-03-24 06:36:48 +00008625 case CTOR_INITIALIZER_DELEGATING:
8626 TInfo = GetTypeSourceInfo(F, Record, Idx);
8627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008628
Richard Smithc2bb8182015-03-24 06:36:48 +00008629 case CTOR_INITIALIZER_MEMBER:
8630 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8631 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008632
Richard Smithc2bb8182015-03-24 06:36:48 +00008633 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8634 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8635 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008637
8638 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8639 Expr *Init = ReadExpr(F);
8640 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8641 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008642
8643 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008644 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008645 BOMInit = new (Context)
8646 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8647 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008648 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008649 BOMInit = new (Context)
8650 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008651 else if (Member)
8652 BOMInit = new (Context)
8653 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8654 Init, RParenLoc);
8655 else
8656 BOMInit = new (Context)
8657 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8658 LParenLoc, Init, RParenLoc);
8659
Richard Smith418ed822016-12-14 19:45:03 +00008660 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008661 unsigned SourceOrder = Record[Idx++];
8662 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008663 }
8664
Richard Smithc2bb8182015-03-24 06:36:48 +00008665 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008666 }
8667
Richard Smithc2bb8182015-03-24 06:36:48 +00008668 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008669}
8670
8671NestedNameSpecifier *
8672ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8673 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008674 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008675 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008676 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008677 for (unsigned I = 0; I != N; ++I) {
8678 NestedNameSpecifier::SpecifierKind Kind
8679 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8680 switch (Kind) {
8681 case NestedNameSpecifier::Identifier: {
8682 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8683 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8684 break;
8685 }
8686
8687 case NestedNameSpecifier::Namespace: {
8688 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8689 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8690 break;
8691 }
8692
8693 case NestedNameSpecifier::NamespaceAlias: {
8694 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8695 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8696 break;
8697 }
8698
8699 case NestedNameSpecifier::TypeSpec:
8700 case NestedNameSpecifier::TypeSpecWithTemplate: {
8701 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8702 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008703 return nullptr;
8704
Guy Benyei11169dd2012-12-18 14:30:41 +00008705 bool Template = Record[Idx++];
8706 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8707 break;
8708 }
8709
8710 case NestedNameSpecifier::Global: {
8711 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8712 // No associated value, and there can't be a prefix.
8713 break;
8714 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008715
8716 case NestedNameSpecifier::Super: {
8717 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8718 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8719 break;
8720 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008721 }
8722 Prev = NNS;
8723 }
8724 return NNS;
8725}
8726
8727NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008728ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008729 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008730 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 unsigned N = Record[Idx++];
8732 NestedNameSpecifierLocBuilder Builder;
8733 for (unsigned I = 0; I != N; ++I) {
8734 NestedNameSpecifier::SpecifierKind Kind
8735 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8736 switch (Kind) {
8737 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008738 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008739 SourceRange Range = ReadSourceRange(F, Record, Idx);
8740 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8741 break;
8742 }
8743
8744 case NestedNameSpecifier::Namespace: {
8745 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8746 SourceRange Range = ReadSourceRange(F, Record, Idx);
8747 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8748 break;
8749 }
8750
8751 case NestedNameSpecifier::NamespaceAlias: {
8752 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8753 SourceRange Range = ReadSourceRange(F, Record, Idx);
8754 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8755 break;
8756 }
8757
8758 case NestedNameSpecifier::TypeSpec:
8759 case NestedNameSpecifier::TypeSpecWithTemplate: {
8760 bool Template = Record[Idx++];
8761 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8762 if (!T)
8763 return NestedNameSpecifierLoc();
8764 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8765
8766 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008767 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008768 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8769 T->getTypeLoc(), ColonColonLoc);
8770 break;
8771 }
8772
8773 case NestedNameSpecifier::Global: {
8774 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8775 Builder.MakeGlobal(Context, ColonColonLoc);
8776 break;
8777 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008778
8779 case NestedNameSpecifier::Super: {
8780 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8781 SourceRange Range = ReadSourceRange(F, Record, Idx);
8782 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8783 break;
8784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008785 }
8786 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008787
Guy Benyei11169dd2012-12-18 14:30:41 +00008788 return Builder.getWithLocInContext(Context);
8789}
8790
8791SourceRange
8792ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8793 unsigned &Idx) {
8794 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8795 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8796 return SourceRange(beg, end);
8797}
8798
8799/// \brief Read an integral value
8800llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8801 unsigned BitWidth = Record[Idx++];
8802 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8803 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8804 Idx += NumWords;
8805 return Result;
8806}
8807
8808/// \brief Read a signed integral value
8809llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8810 bool isUnsigned = Record[Idx++];
8811 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8812}
8813
8814/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008815llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8816 const llvm::fltSemantics &Sem,
8817 unsigned &Idx) {
8818 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008819}
8820
8821// \brief Read a string
8822std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8823 unsigned Len = Record[Idx++];
8824 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8825 Idx += Len;
8826 return Result;
8827}
8828
Richard Smith7ed1bc92014-12-05 22:42:13 +00008829std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8830 unsigned &Idx) {
8831 std::string Filename = ReadString(Record, Idx);
8832 ResolveImportedPath(F, Filename);
8833 return Filename;
8834}
8835
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008836VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008837 unsigned &Idx) {
8838 unsigned Major = Record[Idx++];
8839 unsigned Minor = Record[Idx++];
8840 unsigned Subminor = Record[Idx++];
8841 if (Minor == 0)
8842 return VersionTuple(Major);
8843 if (Subminor == 0)
8844 return VersionTuple(Major, Minor - 1);
8845 return VersionTuple(Major, Minor - 1, Subminor - 1);
8846}
8847
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008848CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 const RecordData &Record,
8850 unsigned &Idx) {
8851 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008852 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008853}
8854
Richard Smith37a93df2017-02-18 00:32:02 +00008855DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008856 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008857}
8858
Richard Smith37a93df2017-02-18 00:32:02 +00008859DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008860 return Diags.Report(Loc, DiagID);
8861}
8862
8863/// \brief Retrieve the identifier table associated with the
8864/// preprocessor.
8865IdentifierTable &ASTReader::getIdentifierTable() {
8866 return PP.getIdentifierTable();
8867}
8868
8869/// \brief Record that the given ID maps to the given switch-case
8870/// statement.
8871void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008872 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008873 "Already have a SwitchCase with this ID");
8874 (*CurrSwitchCaseStmts)[ID] = SC;
8875}
8876
8877/// \brief Retrieve the switch-case statement with the given ID.
8878SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008879 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008880 return (*CurrSwitchCaseStmts)[ID];
8881}
8882
8883void ASTReader::ClearSwitchCaseIDs() {
8884 CurrSwitchCaseStmts->clear();
8885}
8886
8887void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008888 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008889 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008890 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008891 serialization::ModuleFile *> >::iterator
8892 I = CommentsCursors.begin(),
8893 E = CommentsCursors.end();
8894 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008895 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008896 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008897 serialization::ModuleFile &F = *I->second;
8898 SavedStreamPosition SavedPosition(Cursor);
8899
8900 RecordData Record;
8901 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008902 llvm::BitstreamEntry Entry =
8903 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008904
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008905 switch (Entry.Kind) {
8906 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8907 case llvm::BitstreamEntry::Error:
8908 Error("malformed block record in AST file");
8909 return;
8910 case llvm::BitstreamEntry::EndBlock:
8911 goto NextCursor;
8912 case llvm::BitstreamEntry::Record:
8913 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008914 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008915 }
8916
8917 // Read a record.
8918 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008919 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008920 case COMMENTS_RAW_COMMENT: {
8921 unsigned Idx = 0;
8922 SourceRange SR = ReadSourceRange(F, Record, Idx);
8923 RawComment::CommentKind Kind =
8924 (RawComment::CommentKind) Record[Idx++];
8925 bool IsTrailingComment = Record[Idx++];
8926 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008927 Comments.push_back(new (Context) RawComment(
8928 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8929 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008930 break;
8931 }
8932 }
8933 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008934 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008935 // De-serialized SourceLocations get negative FileIDs for other modules,
8936 // potentially invalidating the original order. Sort it again.
8937 std::sort(Comments.begin(), Comments.end(),
8938 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008939 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008940 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008941}
8942
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008943void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8944 bool IncludeSystem, bool Complain,
8945 llvm::function_ref<void(const serialization::InputFile &IF,
8946 bool isSystem)> Visitor) {
8947 unsigned NumUserInputs = MF.NumUserInputFiles;
8948 unsigned NumInputs = MF.InputFilesLoaded.size();
8949 assert(NumUserInputs <= NumInputs);
8950 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8951 for (unsigned I = 0; I < N; ++I) {
8952 bool IsSystem = I >= NumUserInputs;
8953 InputFile IF = getInputFile(MF, I+1, Complain);
8954 Visitor(IF, IsSystem);
8955 }
8956}
8957
Richard Smithf3f84612017-06-29 02:19:42 +00008958void ASTReader::visitTopLevelModuleMaps(
8959 serialization::ModuleFile &MF,
8960 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
8961 unsigned NumInputs = MF.InputFilesLoaded.size();
8962 for (unsigned I = 0; I < NumInputs; ++I) {
8963 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
8964 if (IFI.TopLevelModuleMap)
8965 // FIXME: This unnecessarily re-reads the InputFileInfo.
8966 if (auto *FE = getInputFile(MF, I + 1).getFile())
8967 Visitor(FE);
8968 }
8969}
8970
Richard Smithcd45dbc2014-04-19 03:48:30 +00008971std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8972 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008973 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008974 return M->getFullModuleName();
8975
8976 // Otherwise, use the name of the top-level module the decl is within.
8977 if (ModuleFile *M = getOwningModuleFile(D))
8978 return M->ModuleName;
8979
8980 // Not from a module.
8981 return "";
8982}
8983
Guy Benyei11169dd2012-12-18 14:30:41 +00008984void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008985 while (!PendingIdentifierInfos.empty() ||
8986 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008987 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008988 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008989 // If any identifiers with corresponding top-level declarations have
8990 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008991 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8992 TopLevelDeclsMap;
8993 TopLevelDeclsMap TopLevelDecls;
8994
Guy Benyei11169dd2012-12-18 14:30:41 +00008995 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008996 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008997 SmallVector<uint32_t, 4> DeclIDs =
8998 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008999 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009000
9001 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009002 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009003
Richard Smith851072e2014-05-19 20:59:20 +00009004 // For each decl chain that we wanted to complete while deserializing, mark
9005 // it as "still needs to be completed".
9006 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9007 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9008 }
9009 PendingIncompleteDeclChains.clear();
9010
Guy Benyei11169dd2012-12-18 14:30:41 +00009011 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00009012 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00009013 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009014 PendingDeclChains.clear();
9015
Douglas Gregor6168bd22013-02-18 15:53:43 +00009016 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00009017 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9018 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009019 IdentifierInfo *II = TLD->first;
9020 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009021 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009022 }
9023 }
9024
Guy Benyei11169dd2012-12-18 14:30:41 +00009025 // Load any pending macro definitions.
9026 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009027 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9028 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9029 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9030 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009031 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009032 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009033 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009034 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009035 resolvePendingMacro(II, Info);
9036 }
9037 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009038 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009039 ++IDIdx) {
9040 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009041 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009042 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009043 }
9044 }
9045 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009046
9047 // Wire up the DeclContexts for Decls that we delayed setting until
9048 // recursive loading is completed.
9049 while (!PendingDeclContextInfos.empty()) {
9050 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9051 PendingDeclContextInfos.pop_front();
9052 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9053 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9054 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9055 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009056
Richard Smithd1c46742014-04-30 02:24:17 +00009057 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009058 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009059 auto Update = PendingUpdateRecords.pop_back_val();
9060 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009061 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009062 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009063 }
Richard Smith8a639892015-01-24 01:07:20 +00009064
9065 // At this point, all update records for loaded decls are in place, so any
9066 // fake class definitions should have become real.
9067 assert(PendingFakeDefinitionData.empty() &&
9068 "faked up a class definition but never saw the real one");
9069
Guy Benyei11169dd2012-12-18 14:30:41 +00009070 // If we deserialized any C++ or Objective-C class definitions, any
9071 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009072 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009073 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00009074 for (Decl *D : PendingDefinitions) {
9075 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00009076 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009077 // Make sure that the TagType points at the definition.
9078 const_cast<TagType*>(TagT)->decl = TD;
9079 }
Richard Smith8ce51082015-03-11 01:44:51 +00009080
Craig Topperc6914d02014-08-25 04:15:02 +00009081 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009082 for (auto *R = getMostRecentExistingDecl(RD); R;
9083 R = R->getPreviousDecl()) {
9084 assert((R == D) ==
9085 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009086 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009087 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009088 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009089 }
9090
9091 continue;
9092 }
Richard Smith8ce51082015-03-11 01:44:51 +00009093
Craig Topperc6914d02014-08-25 04:15:02 +00009094 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009095 // Make sure that the ObjCInterfaceType points at the definition.
9096 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9097 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009098
9099 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9100 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9101
Guy Benyei11169dd2012-12-18 14:30:41 +00009102 continue;
9103 }
Richard Smith8ce51082015-03-11 01:44:51 +00009104
Craig Topperc6914d02014-08-25 04:15:02 +00009105 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009106 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9107 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9108
Guy Benyei11169dd2012-12-18 14:30:41 +00009109 continue;
9110 }
Richard Smith8ce51082015-03-11 01:44:51 +00009111
Craig Topperc6914d02014-08-25 04:15:02 +00009112 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009113 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9114 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009115 }
9116 PendingDefinitions.clear();
9117
9118 // Load the bodies of any functions or methods we've encountered. We do
9119 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00009120 // have been fully wired up (hasBody relies on this).
9121 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00009122 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9123 PBEnd = PendingBodies.end();
9124 PB != PBEnd; ++PB) {
9125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9126 // FIXME: Check for =delete/=default?
9127 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00009128 const FunctionDecl *Defn = nullptr;
David Blaikiee6b7c282017-04-11 20:46:34 +00009129 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009130 FD->setLazyBody(PB->second);
David Blaikiee6b7c282017-04-11 20:46:34 +00009131 } else
Richard Smith6561f922016-09-12 21:06:40 +00009132 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00009133 continue;
9134 }
9135
9136 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9137 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9138 MD->setLazyBody(PB->second);
9139 }
9140 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00009141
9142 // Do some cleanup.
9143 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9144 getContext().deduplicateMergedDefinitonsFor(ND);
9145 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009146}
9147
9148void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00009149 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9150 return;
9151
Richard Smitha0ce9c42014-07-29 23:23:27 +00009152 // Trigger the import of the full definition of each class that had any
9153 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009154 // These updates may in turn find and diagnose some ODR failures, so take
9155 // ownership of the set first.
9156 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9157 PendingOdrMergeFailures.clear();
9158 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009159 Merge.first->buildLookup();
9160 Merge.first->decls_begin();
9161 Merge.first->bases_begin();
9162 Merge.first->vbases_begin();
9163 for (auto *RD : Merge.second) {
9164 RD->decls_begin();
9165 RD->bases_begin();
9166 RD->vbases_begin();
9167 }
9168 }
9169
9170 // For each declaration from a merged context, check that the canonical
9171 // definition of that context also contains a declaration of the same
9172 // entity.
9173 //
9174 // Caution: this loop does things that might invalidate iterators into
9175 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9176 while (!PendingOdrMergeChecks.empty()) {
9177 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9178
9179 // FIXME: Skip over implicit declarations for now. This matters for things
9180 // like implicitly-declared special member functions. This isn't entirely
9181 // correct; we can end up with multiple unmerged declarations of the same
9182 // implicit entity.
9183 if (D->isImplicit())
9184 continue;
9185
9186 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009187
9188 bool Found = false;
9189 const Decl *DCanon = D->getCanonicalDecl();
9190
Richard Smith01bdb7a2014-08-28 05:44:07 +00009191 for (auto RI : D->redecls()) {
9192 if (RI->getLexicalDeclContext() == CanonDef) {
9193 Found = true;
9194 break;
9195 }
9196 }
9197 if (Found)
9198 continue;
9199
Richard Smith0f4e2c42015-08-06 04:23:48 +00009200 // Quick check failed, time to do the slow thing. Note, we can't just
9201 // look up the name of D in CanonDef here, because the member that is
9202 // in CanonDef might not be found by name lookup (it might have been
9203 // replaced by a more recent declaration in the lookup table), and we
9204 // can't necessarily find it in the redeclaration chain because it might
9205 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009206 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009207 for (auto *CanonMember : CanonDef->decls()) {
9208 if (CanonMember->getCanonicalDecl() == DCanon) {
9209 // This can happen if the declaration is merely mergeable and not
9210 // actually redeclarable (we looked for redeclarations earlier).
9211 //
9212 // FIXME: We should be able to detect this more efficiently, without
9213 // pulling in all of the members of CanonDef.
9214 Found = true;
9215 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009216 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009217 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9218 if (ND->getDeclName() == D->getDeclName())
9219 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009220 }
9221
9222 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009223 // The AST doesn't like TagDecls becoming invalid after they've been
9224 // completed. We only really need to mark FieldDecls as invalid here.
9225 if (!isa<TagDecl>(D))
9226 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009227
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009228 // Ensure we don't accidentally recursively enter deserialization while
9229 // we're producing our diagnostic.
9230 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009231
9232 std::string CanonDefModule =
9233 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9234 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9235 << D << getOwningModuleNameForDiagnostic(D)
9236 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9237
9238 if (Candidates.empty())
9239 Diag(cast<Decl>(CanonDef)->getLocation(),
9240 diag::note_module_odr_violation_no_possible_decls) << D;
9241 else {
9242 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9243 Diag(Candidates[I]->getLocation(),
9244 diag::note_module_odr_violation_possible_decl)
9245 << Candidates[I];
9246 }
9247
9248 DiagnosedOdrMergeFailures.insert(CanonDef);
9249 }
9250 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009251
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009252 if (OdrMergeFailures.empty())
9253 return;
9254
9255 // Ensure we don't accidentally recursively enter deserialization while
9256 // we're producing our diagnostics.
9257 Deserializing RecursionGuard(this);
9258
Richard Smithcd45dbc2014-04-19 03:48:30 +00009259 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009260 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009261 // If we've already pointed out a specific problem with this class, don't
9262 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009263 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009264 continue;
9265
9266 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009267 CXXRecordDecl *FirstRecord = Merge.first;
9268 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9269 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00009270 // Multiple different declarations got merged together; tell the user
9271 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009272 if (FirstRecord == SecondRecord)
9273 continue;
9274
9275 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9276 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009277
9278 const ClassTemplateDecl *FirstTemplate =
9279 FirstRecord->getDescribedClassTemplate();
9280 const ClassTemplateDecl *SecondTemplate =
9281 SecondRecord->getDescribedClassTemplate();
9282
9283 assert(!FirstTemplate == !SecondTemplate &&
9284 "Both pointers should be null or non-null");
9285
9286 enum ODRTemplateDifference {
9287 ParamEmptyName,
9288 ParamName,
9289 ParamSingleDefaultArgument,
9290 ParamDifferentDefaultArgument,
9291 };
9292
9293 if (FirstTemplate && SecondTemplate) {
9294 DeclHashes FirstTemplateHashes;
9295 DeclHashes SecondTemplateHashes;
9296 ODRHash Hash;
9297
9298 auto PopulateTemplateParameterHashs =
9299 [&Hash](DeclHashes &Hashes, const ClassTemplateDecl *TD) {
9300 for (auto *D : TD->getTemplateParameters()->asArray()) {
9301 Hash.clear();
9302 Hash.AddSubDecl(D);
9303 Hashes.emplace_back(D, Hash.CalculateHash());
9304 }
9305 };
9306
9307 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9308 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9309
9310 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9311 "Number of template parameters should be equal.");
9312
9313 auto FirstIt = FirstTemplateHashes.begin();
9314 auto FirstEnd = FirstTemplateHashes.end();
9315 auto SecondIt = SecondTemplateHashes.begin();
9316 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9317 if (FirstIt->second == SecondIt->second)
9318 continue;
9319
9320 auto ODRDiagError = [FirstRecord, &FirstModule,
9321 this](SourceLocation Loc, SourceRange Range,
9322 ODRTemplateDifference DiffType) {
9323 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9324 << FirstRecord << FirstModule.empty() << FirstModule << Range
9325 << DiffType;
9326 };
9327 auto ODRDiagNote = [&SecondModule,
9328 this](SourceLocation Loc, SourceRange Range,
9329 ODRTemplateDifference DiffType) {
9330 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9331 << SecondModule << Range << DiffType;
9332 };
9333
9334 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9335 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9336
9337 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9338 "Parameter Decl's should be the same kind.");
9339
9340 DeclarationName FirstName = FirstDecl->getDeclName();
9341 DeclarationName SecondName = SecondDecl->getDeclName();
9342
9343 if (FirstName != SecondName) {
9344 const bool FirstNameEmpty =
9345 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9346 const bool SecondNameEmpty =
9347 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9348 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9349 "Both template parameters cannot be unnamed.");
9350 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9351 FirstNameEmpty ? ParamEmptyName : ParamName)
9352 << FirstName;
9353 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9354 SecondNameEmpty ? ParamEmptyName : ParamName)
9355 << SecondName;
9356 break;
9357 }
9358
9359 switch (FirstDecl->getKind()) {
9360 default:
9361 llvm_unreachable("Invalid template parameter type.");
9362 case Decl::TemplateTypeParm: {
9363 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9364 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9365 const bool HasFirstDefaultArgument =
9366 FirstParam->hasDefaultArgument() &&
9367 !FirstParam->defaultArgumentWasInherited();
9368 const bool HasSecondDefaultArgument =
9369 SecondParam->hasDefaultArgument() &&
9370 !SecondParam->defaultArgumentWasInherited();
9371
9372 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9373 ODRDiagError(FirstDecl->getLocation(),
9374 FirstDecl->getSourceRange(),
9375 ParamSingleDefaultArgument)
9376 << HasFirstDefaultArgument;
9377 ODRDiagNote(SecondDecl->getLocation(),
9378 SecondDecl->getSourceRange(),
9379 ParamSingleDefaultArgument)
9380 << HasSecondDefaultArgument;
9381 break;
9382 }
9383
9384 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9385 "Expecting default arguments.");
9386
9387 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9388 ParamDifferentDefaultArgument);
9389 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9390 ParamDifferentDefaultArgument);
9391
9392 break;
9393 }
9394 case Decl::NonTypeTemplateParm: {
9395 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9396 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9397 const bool HasFirstDefaultArgument =
9398 FirstParam->hasDefaultArgument() &&
9399 !FirstParam->defaultArgumentWasInherited();
9400 const bool HasSecondDefaultArgument =
9401 SecondParam->hasDefaultArgument() &&
9402 !SecondParam->defaultArgumentWasInherited();
9403
9404 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9405 ODRDiagError(FirstDecl->getLocation(),
9406 FirstDecl->getSourceRange(),
9407 ParamSingleDefaultArgument)
9408 << HasFirstDefaultArgument;
9409 ODRDiagNote(SecondDecl->getLocation(),
9410 SecondDecl->getSourceRange(),
9411 ParamSingleDefaultArgument)
9412 << HasSecondDefaultArgument;
9413 break;
9414 }
9415
9416 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9417 "Expecting default arguments.");
9418
9419 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9420 ParamDifferentDefaultArgument);
9421 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9422 ParamDifferentDefaultArgument);
9423
9424 break;
9425 }
9426 case Decl::TemplateTemplateParm: {
9427 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9428 const auto *SecondParam =
9429 cast<TemplateTemplateParmDecl>(SecondDecl);
9430 const bool HasFirstDefaultArgument =
9431 FirstParam->hasDefaultArgument() &&
9432 !FirstParam->defaultArgumentWasInherited();
9433 const bool HasSecondDefaultArgument =
9434 SecondParam->hasDefaultArgument() &&
9435 !SecondParam->defaultArgumentWasInherited();
9436
9437 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9438 ODRDiagError(FirstDecl->getLocation(),
9439 FirstDecl->getSourceRange(),
9440 ParamSingleDefaultArgument)
9441 << HasFirstDefaultArgument;
9442 ODRDiagNote(SecondDecl->getLocation(),
9443 SecondDecl->getSourceRange(),
9444 ParamSingleDefaultArgument)
9445 << HasSecondDefaultArgument;
9446 break;
9447 }
9448
9449 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9450 "Expecting default arguments.");
9451
9452 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9453 ParamDifferentDefaultArgument);
9454 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9455 ParamDifferentDefaultArgument);
9456
9457 break;
9458 }
9459 }
9460
9461 break;
9462 }
9463
9464 if (FirstIt != FirstEnd) {
9465 Diagnosed = true;
9466 break;
9467 }
9468 }
9469
Richard Trieue7f7ed22017-02-22 01:11:25 +00009470 DeclHashes FirstHashes;
9471 DeclHashes SecondHashes;
9472 ODRHash Hash;
9473
9474 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9475 CXXRecordDecl *Record) {
9476 for (auto *D : Record->decls()) {
9477 // Due to decl merging, the first CXXRecordDecl is the parent of
9478 // Decls in both records.
9479 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9480 continue;
9481 Hash.clear();
9482 Hash.AddSubDecl(D);
9483 Hashes.emplace_back(D, Hash.CalculateHash());
9484 }
9485 };
9486 PopulateHashes(FirstHashes, FirstRecord);
9487 PopulateHashes(SecondHashes, SecondRecord);
9488
9489 // Used with err_module_odr_violation_mismatch_decl and
9490 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009491 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009492 enum {
9493 EndOfClass,
9494 PublicSpecifer,
9495 PrivateSpecifer,
9496 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009497 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009498 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009499 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009500 TypeAlias,
9501 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009502 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009503 Friend,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009504 Other
9505 } FirstDiffType = Other,
9506 SecondDiffType = Other;
9507
9508 auto DifferenceSelector = [](Decl *D) {
9509 assert(D && "valid Decl required");
9510 switch (D->getKind()) {
9511 default:
9512 return Other;
9513 case Decl::AccessSpec:
9514 switch (D->getAccess()) {
9515 case AS_public:
9516 return PublicSpecifer;
9517 case AS_private:
9518 return PrivateSpecifer;
9519 case AS_protected:
9520 return ProtectedSpecifer;
9521 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009522 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009523 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009524 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009525 case Decl::StaticAssert:
9526 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009527 case Decl::Field:
9528 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009529 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009530 case Decl::CXXConstructor:
9531 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009532 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009533 case Decl::TypeAlias:
9534 return TypeAlias;
9535 case Decl::Typedef:
9536 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009537 case Decl::Var:
9538 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009539 case Decl::Friend:
9540 return Friend;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009541 }
9542 };
9543
9544 Decl *FirstDecl = nullptr;
9545 Decl *SecondDecl = nullptr;
9546 auto FirstIt = FirstHashes.begin();
9547 auto SecondIt = SecondHashes.begin();
9548
9549 // If there is a diagnoseable difference, FirstDiffType and
9550 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9551 // filled in if not EndOfClass.
9552 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009553 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9554 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009555 ++FirstIt;
9556 ++SecondIt;
9557 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009558 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009559
Richard Trieue7f7ed22017-02-22 01:11:25 +00009560 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9561 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9562
9563 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9564 SecondDiffType =
9565 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9566
9567 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009568 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009569
9570 if (FirstDiffType == Other || SecondDiffType == Other) {
9571 // Reaching this point means an unexpected Decl was encountered
9572 // or no difference was detected. This causes a generic error
9573 // message to be emitted.
9574 Diag(FirstRecord->getLocation(),
9575 diag::err_module_odr_violation_different_definitions)
9576 << FirstRecord << FirstModule.empty() << FirstModule;
9577
Richard Trieuca48d362017-06-21 01:43:13 +00009578 if (FirstDecl) {
9579 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9580 << FirstRecord << FirstDecl->getSourceRange();
9581 }
9582
Richard Trieue7f7ed22017-02-22 01:11:25 +00009583 Diag(SecondRecord->getLocation(),
9584 diag::note_module_odr_violation_different_definitions)
9585 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009586
9587 if (SecondDecl) {
9588 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9589 << SecondDecl->getSourceRange();
9590 }
9591
Richard Trieue7f7ed22017-02-22 01:11:25 +00009592 Diagnosed = true;
9593 break;
9594 }
9595
9596 if (FirstDiffType != SecondDiffType) {
9597 SourceLocation FirstLoc;
9598 SourceRange FirstRange;
9599 if (FirstDiffType == EndOfClass) {
9600 FirstLoc = FirstRecord->getBraceRange().getEnd();
9601 } else {
9602 FirstLoc = FirstIt->first->getLocation();
9603 FirstRange = FirstIt->first->getSourceRange();
9604 }
9605 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9606 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9607 << FirstDiffType;
9608
9609 SourceLocation SecondLoc;
9610 SourceRange SecondRange;
9611 if (SecondDiffType == EndOfClass) {
9612 SecondLoc = SecondRecord->getBraceRange().getEnd();
9613 } else {
9614 SecondLoc = SecondDecl->getLocation();
9615 SecondRange = SecondDecl->getSourceRange();
9616 }
9617 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9618 << SecondModule << SecondRange << SecondDiffType;
9619 Diagnosed = true;
9620 break;
9621 }
9622
Richard Trieu639d7b62017-02-22 22:22:42 +00009623 assert(FirstDiffType == SecondDiffType);
9624
9625 // Used with err_module_odr_violation_mismatch_decl_diff and
9626 // note_module_odr_violation_mismatch_decl_diff
9627 enum ODRDeclDifference{
9628 StaticAssertCondition,
9629 StaticAssertMessage,
9630 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009631 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009632 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009633 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009634 FieldDifferentWidthBitField,
9635 FieldSingleMutable,
9636 FieldSingleInitializer,
9637 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009638 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009639 MethodDeleted,
9640 MethodVirtual,
9641 MethodStatic,
9642 MethodVolatile,
9643 MethodConst,
9644 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009645 MethodNumberParameters,
9646 MethodParameterType,
9647 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009648 MethodParameterSingleDefaultArgument,
9649 MethodParameterDifferentDefaultArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009650 TypedefName,
9651 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009652 VarName,
9653 VarType,
9654 VarSingleInitializer,
9655 VarDifferentInitializer,
9656 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009657 FriendTypeFunction,
9658 FriendType,
9659 FriendFunction,
Richard Trieu639d7b62017-02-22 22:22:42 +00009660 };
9661
9662 // These lambdas have the common portions of the ODR diagnostics. This
9663 // has the same return as Diag(), so addition parameters can be passed
9664 // in with operator<<
9665 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9666 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9667 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9668 << FirstRecord << FirstModule.empty() << FirstModule << Range
9669 << DiffType;
9670 };
9671 auto ODRDiagNote = [&SecondModule, this](
9672 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9673 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9674 << SecondModule << Range << DiffType;
9675 };
9676
9677 auto ComputeODRHash = [&Hash](const Stmt* S) {
9678 assert(S);
9679 Hash.clear();
9680 Hash.AddStmt(S);
9681 return Hash.CalculateHash();
9682 };
9683
Richard Trieu02552272017-05-02 23:58:52 +00009684 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9685 Hash.clear();
9686 Hash.AddQualType(Ty);
9687 return Hash.CalculateHash();
9688 };
9689
Richard Trieu639d7b62017-02-22 22:22:42 +00009690 switch (FirstDiffType) {
9691 case Other:
9692 case EndOfClass:
9693 case PublicSpecifer:
9694 case PrivateSpecifer:
9695 case ProtectedSpecifer:
9696 llvm_unreachable("Invalid diff type");
9697
9698 case StaticAssert: {
9699 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9700 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9701
9702 Expr *FirstExpr = FirstSA->getAssertExpr();
9703 Expr *SecondExpr = SecondSA->getAssertExpr();
9704 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9705 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9706 if (FirstODRHash != SecondODRHash) {
9707 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9708 StaticAssertCondition);
9709 ODRDiagNote(SecondExpr->getLocStart(),
9710 SecondExpr->getSourceRange(), StaticAssertCondition);
9711 Diagnosed = true;
9712 break;
9713 }
9714
9715 StringLiteral *FirstStr = FirstSA->getMessage();
9716 StringLiteral *SecondStr = SecondSA->getMessage();
9717 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9718 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9719 SourceLocation FirstLoc, SecondLoc;
9720 SourceRange FirstRange, SecondRange;
9721 if (FirstStr) {
9722 FirstLoc = FirstStr->getLocStart();
9723 FirstRange = FirstStr->getSourceRange();
9724 } else {
9725 FirstLoc = FirstSA->getLocStart();
9726 FirstRange = FirstSA->getSourceRange();
9727 }
9728 if (SecondStr) {
9729 SecondLoc = SecondStr->getLocStart();
9730 SecondRange = SecondStr->getSourceRange();
9731 } else {
9732 SecondLoc = SecondSA->getLocStart();
9733 SecondRange = SecondSA->getSourceRange();
9734 }
9735 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9736 << (FirstStr == nullptr);
9737 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9738 << (SecondStr == nullptr);
9739 Diagnosed = true;
9740 break;
9741 }
9742
9743 if (FirstStr && SecondStr &&
9744 FirstStr->getString() != SecondStr->getString()) {
9745 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9746 StaticAssertMessage);
9747 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9748 StaticAssertMessage);
9749 Diagnosed = true;
9750 break;
9751 }
9752 break;
9753 }
Richard Trieud0786092017-02-23 00:23:01 +00009754 case Field: {
9755 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9756 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9757 IdentifierInfo *FirstII = FirstField->getIdentifier();
9758 IdentifierInfo *SecondII = SecondField->getIdentifier();
9759 if (FirstII->getName() != SecondII->getName()) {
9760 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9761 FieldName)
9762 << FirstII;
9763 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9764 FieldName)
9765 << SecondII;
9766
9767 Diagnosed = true;
9768 break;
9769 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009770
Richard Smithdbafb6c2017-06-29 23:23:46 +00009771 assert(getContext().hasSameType(FirstField->getType(),
9772 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +00009773
9774 QualType FirstType = FirstField->getType();
9775 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +00009776 if (ComputeQualTypeODRHash(FirstType) !=
9777 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +00009778 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9779 FieldTypeName)
9780 << FirstII << FirstType;
9781 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9782 FieldTypeName)
9783 << SecondII << SecondType;
9784
9785 Diagnosed = true;
9786 break;
9787 }
9788
Richard Trieu93772fc2017-02-24 20:59:28 +00009789 const bool IsFirstBitField = FirstField->isBitField();
9790 const bool IsSecondBitField = SecondField->isBitField();
9791 if (IsFirstBitField != IsSecondBitField) {
9792 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9793 FieldSingleBitField)
9794 << FirstII << IsFirstBitField;
9795 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9796 FieldSingleBitField)
9797 << SecondII << IsSecondBitField;
9798 Diagnosed = true;
9799 break;
9800 }
9801
9802 if (IsFirstBitField && IsSecondBitField) {
9803 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9804 FieldDifferentWidthBitField)
9805 << FirstII << FirstField->getBitWidth()->getSourceRange();
9806 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9807 FieldDifferentWidthBitField)
9808 << SecondII << SecondField->getBitWidth()->getSourceRange();
9809 Diagnosed = true;
9810 break;
9811 }
9812
Richard Trieu8d543e22017-02-24 23:35:37 +00009813 const bool IsFirstMutable = FirstField->isMutable();
9814 const bool IsSecondMutable = SecondField->isMutable();
9815 if (IsFirstMutable != IsSecondMutable) {
9816 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9817 FieldSingleMutable)
9818 << FirstII << IsFirstMutable;
9819 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9820 FieldSingleMutable)
9821 << SecondII << IsSecondMutable;
9822 Diagnosed = true;
9823 break;
9824 }
9825
9826 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9827 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9828 if ((!FirstInitializer && SecondInitializer) ||
9829 (FirstInitializer && !SecondInitializer)) {
9830 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9831 FieldSingleInitializer)
9832 << FirstII << (FirstInitializer != nullptr);
9833 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9834 FieldSingleInitializer)
9835 << SecondII << (SecondInitializer != nullptr);
9836 Diagnosed = true;
9837 break;
9838 }
9839
9840 if (FirstInitializer && SecondInitializer) {
9841 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9842 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9843 if (FirstInitHash != SecondInitHash) {
9844 ODRDiagError(FirstField->getLocation(),
9845 FirstField->getSourceRange(),
9846 FieldDifferentInitializers)
9847 << FirstII << FirstInitializer->getSourceRange();
9848 ODRDiagNote(SecondField->getLocation(),
9849 SecondField->getSourceRange(),
9850 FieldDifferentInitializers)
9851 << SecondII << SecondInitializer->getSourceRange();
9852 Diagnosed = true;
9853 break;
9854 }
9855 }
9856
Richard Trieud0786092017-02-23 00:23:01 +00009857 break;
9858 }
Richard Trieu48143742017-02-28 21:24:38 +00009859 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +00009860 enum {
9861 DiagMethod,
9862 DiagConstructor,
9863 DiagDestructor,
9864 } FirstMethodType,
9865 SecondMethodType;
9866 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
9867 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
9868 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
9869 return DiagMethod;
9870 };
Richard Trieu48143742017-02-28 21:24:38 +00009871 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9872 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +00009873 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
9874 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +00009875 auto FirstName = FirstMethod->getDeclName();
9876 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +00009877 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009878 ODRDiagError(FirstMethod->getLocation(),
9879 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +00009880 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009881 ODRDiagNote(SecondMethod->getLocation(),
9882 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +00009883 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009884
9885 Diagnosed = true;
9886 break;
9887 }
9888
Richard Trieu583e2c12017-03-04 00:08:58 +00009889 const bool FirstDeleted = FirstMethod->isDeleted();
9890 const bool SecondDeleted = SecondMethod->isDeleted();
9891 if (FirstDeleted != SecondDeleted) {
9892 ODRDiagError(FirstMethod->getLocation(),
9893 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +00009894 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +00009895
9896 ODRDiagNote(SecondMethod->getLocation(),
9897 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +00009898 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +00009899 Diagnosed = true;
9900 break;
9901 }
9902
9903 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9904 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9905 const bool FirstPure = FirstMethod->isPure();
9906 const bool SecondPure = SecondMethod->isPure();
9907 if ((FirstVirtual || SecondVirtual) &&
9908 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9909 ODRDiagError(FirstMethod->getLocation(),
9910 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +00009911 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +00009912 ODRDiagNote(SecondMethod->getLocation(),
9913 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +00009914 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +00009915 Diagnosed = true;
9916 break;
9917 }
9918
9919 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9920 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9921 // class needs to be checked instead.
9922 const auto FirstStorage = FirstMethod->getStorageClass();
9923 const auto SecondStorage = SecondMethod->getStorageClass();
9924 const bool FirstStatic = FirstStorage == SC_Static;
9925 const bool SecondStatic = SecondStorage == SC_Static;
9926 if (FirstStatic != SecondStatic) {
9927 ODRDiagError(FirstMethod->getLocation(),
9928 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +00009929 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +00009930 ODRDiagNote(SecondMethod->getLocation(),
9931 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +00009932 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +00009933 Diagnosed = true;
9934 break;
9935 }
9936
9937 const bool FirstVolatile = FirstMethod->isVolatile();
9938 const bool SecondVolatile = SecondMethod->isVolatile();
9939 if (FirstVolatile != SecondVolatile) {
9940 ODRDiagError(FirstMethod->getLocation(),
9941 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +00009942 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +00009943 ODRDiagNote(SecondMethod->getLocation(),
9944 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +00009945 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +00009946 Diagnosed = true;
9947 break;
9948 }
9949
9950 const bool FirstConst = FirstMethod->isConst();
9951 const bool SecondConst = SecondMethod->isConst();
9952 if (FirstConst != SecondConst) {
9953 ODRDiagError(FirstMethod->getLocation(),
9954 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +00009955 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +00009956 ODRDiagNote(SecondMethod->getLocation(),
9957 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +00009958 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +00009959 Diagnosed = true;
9960 break;
9961 }
9962
9963 const bool FirstInline = FirstMethod->isInlineSpecified();
9964 const bool SecondInline = SecondMethod->isInlineSpecified();
9965 if (FirstInline != SecondInline) {
9966 ODRDiagError(FirstMethod->getLocation(),
9967 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +00009968 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +00009969 ODRDiagNote(SecondMethod->getLocation(),
9970 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +00009971 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +00009972 Diagnosed = true;
9973 break;
9974 }
9975
Richard Trieu02552272017-05-02 23:58:52 +00009976 const unsigned FirstNumParameters = FirstMethod->param_size();
9977 const unsigned SecondNumParameters = SecondMethod->param_size();
9978 if (FirstNumParameters != SecondNumParameters) {
9979 ODRDiagError(FirstMethod->getLocation(),
9980 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +00009981 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +00009982 ODRDiagNote(SecondMethod->getLocation(),
9983 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +00009984 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +00009985 Diagnosed = true;
9986 break;
9987 }
9988
9989 // Need this status boolean to know when break out of the switch.
9990 bool ParameterMismatch = false;
9991 for (unsigned I = 0; I < FirstNumParameters; ++I) {
9992 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9993 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9994
9995 QualType FirstParamType = FirstParam->getType();
9996 QualType SecondParamType = SecondParam->getType();
9997 if (FirstParamType != SecondParamType &&
9998 ComputeQualTypeODRHash(FirstParamType) !=
9999 ComputeQualTypeODRHash(SecondParamType)) {
10000 if (const DecayedType *ParamDecayedType =
10001 FirstParamType->getAs<DecayedType>()) {
10002 ODRDiagError(FirstMethod->getLocation(),
10003 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010004 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10005 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010006 } else {
10007 ODRDiagError(FirstMethod->getLocation(),
10008 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010009 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10010 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010011 }
10012
10013 if (const DecayedType *ParamDecayedType =
10014 SecondParamType->getAs<DecayedType>()) {
10015 ODRDiagNote(SecondMethod->getLocation(),
10016 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010017 << SecondMethodType << SecondName << (I + 1)
10018 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010019 << ParamDecayedType->getOriginalType();
10020 } else {
10021 ODRDiagNote(SecondMethod->getLocation(),
10022 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010023 << SecondMethodType << SecondName << (I + 1)
10024 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010025 }
10026 ParameterMismatch = true;
10027 break;
10028 }
10029
10030 DeclarationName FirstParamName = FirstParam->getDeclName();
10031 DeclarationName SecondParamName = SecondParam->getDeclName();
10032 if (FirstParamName != SecondParamName) {
10033 ODRDiagError(FirstMethod->getLocation(),
10034 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010035 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010036 ODRDiagNote(SecondMethod->getLocation(),
10037 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010038 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010039 ParameterMismatch = true;
10040 break;
10041 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010042
10043 const Expr *FirstInit = FirstParam->getInit();
10044 const Expr *SecondInit = SecondParam->getInit();
10045 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10046 ODRDiagError(FirstMethod->getLocation(),
10047 FirstMethod->getSourceRange(),
10048 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010049 << FirstMethodType << FirstName << (I + 1)
10050 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010051 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10052 ODRDiagNote(SecondMethod->getLocation(),
10053 SecondMethod->getSourceRange(),
10054 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010055 << SecondMethodType << SecondName << (I + 1)
10056 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010057 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10058 ParameterMismatch = true;
10059 break;
10060 }
10061
10062 if (FirstInit && SecondInit &&
10063 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10064 ODRDiagError(FirstMethod->getLocation(),
10065 FirstMethod->getSourceRange(),
10066 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010067 << FirstMethodType << FirstName << (I + 1)
10068 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010069 ODRDiagNote(SecondMethod->getLocation(),
10070 SecondMethod->getSourceRange(),
10071 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010072 << SecondMethodType << SecondName << (I + 1)
10073 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010074 ParameterMismatch = true;
10075 break;
10076
10077 }
Richard Trieu02552272017-05-02 23:58:52 +000010078 }
10079
10080 if (ParameterMismatch) {
10081 Diagnosed = true;
10082 break;
10083 }
10084
Richard Trieu48143742017-02-28 21:24:38 +000010085 break;
10086 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010087 case TypeAlias:
10088 case TypeDef: {
10089 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10090 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10091 auto FirstName = FirstTD->getDeclName();
10092 auto SecondName = SecondTD->getDeclName();
10093 if (FirstName != SecondName) {
10094 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10095 TypedefName)
10096 << (FirstDiffType == TypeAlias) << FirstName;
10097 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10098 TypedefName)
10099 << (FirstDiffType == TypeAlias) << SecondName;
10100 Diagnosed = true;
10101 break;
10102 }
10103
10104 QualType FirstType = FirstTD->getUnderlyingType();
10105 QualType SecondType = SecondTD->getUnderlyingType();
10106 if (ComputeQualTypeODRHash(FirstType) !=
10107 ComputeQualTypeODRHash(SecondType)) {
10108 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10109 TypedefType)
10110 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10111 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10112 TypedefType)
10113 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10114 Diagnosed = true;
10115 break;
10116 }
10117 break;
10118 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010119 case Var: {
10120 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10121 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10122 auto FirstName = FirstVD->getDeclName();
10123 auto SecondName = SecondVD->getDeclName();
10124 if (FirstName != SecondName) {
10125 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10126 VarName)
10127 << FirstName;
10128 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10129 VarName)
10130 << SecondName;
10131 Diagnosed = true;
10132 break;
10133 }
10134
10135 QualType FirstType = FirstVD->getType();
10136 QualType SecondType = SecondVD->getType();
10137 if (ComputeQualTypeODRHash(FirstType) !=
10138 ComputeQualTypeODRHash(SecondType)) {
10139 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10140 VarType)
10141 << FirstName << FirstType;
10142 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10143 VarType)
10144 << SecondName << SecondType;
10145 Diagnosed = true;
10146 break;
10147 }
10148
10149 const Expr *FirstInit = FirstVD->getInit();
10150 const Expr *SecondInit = SecondVD->getInit();
10151 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10152 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10153 VarSingleInitializer)
10154 << FirstName << (FirstInit == nullptr)
10155 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10156 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10157 VarSingleInitializer)
10158 << SecondName << (SecondInit == nullptr)
10159 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10160 Diagnosed = true;
10161 break;
10162 }
10163
10164 if (FirstInit && SecondInit &&
10165 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10166 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10167 VarDifferentInitializer)
10168 << FirstName << FirstInit->getSourceRange();
10169 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10170 VarDifferentInitializer)
10171 << SecondName << SecondInit->getSourceRange();
10172 Diagnosed = true;
10173 break;
10174 }
10175
10176 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10177 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10178 if (FirstIsConstexpr != SecondIsConstexpr) {
10179 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10180 VarConstexpr)
10181 << FirstName << FirstIsConstexpr;
10182 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10183 VarConstexpr)
10184 << SecondName << SecondIsConstexpr;
10185 Diagnosed = true;
10186 break;
10187 }
10188 break;
10189 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010190 case Friend: {
10191 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10192 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10193
10194 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10195 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10196
10197 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10198 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10199
10200 if (FirstND && SecondND) {
10201 ODRDiagError(FirstFriend->getFriendLoc(),
10202 FirstFriend->getSourceRange(), FriendFunction)
10203 << FirstND;
10204 ODRDiagNote(SecondFriend->getFriendLoc(),
10205 SecondFriend->getSourceRange(), FriendFunction)
10206 << SecondND;
10207
10208 Diagnosed = true;
10209 break;
10210 }
10211
10212 if (FirstTSI && SecondTSI) {
10213 QualType FirstFriendType = FirstTSI->getType();
10214 QualType SecondFriendType = SecondTSI->getType();
10215 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10216 ComputeQualTypeODRHash(SecondFriendType));
10217 ODRDiagError(FirstFriend->getFriendLoc(),
10218 FirstFriend->getSourceRange(), FriendType)
10219 << FirstFriendType;
10220 ODRDiagNote(SecondFriend->getFriendLoc(),
10221 SecondFriend->getSourceRange(), FriendType)
10222 << SecondFriendType;
10223 Diagnosed = true;
10224 break;
10225 }
10226
10227 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10228 FriendTypeFunction)
10229 << (FirstTSI == nullptr);
10230 ODRDiagNote(SecondFriend->getFriendLoc(),
10231 SecondFriend->getSourceRange(), FriendTypeFunction)
10232 << (SecondTSI == nullptr);
10233
10234 Diagnosed = true;
10235 break;
10236 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010237 }
10238
Richard Trieue7f7ed22017-02-22 01:11:25 +000010239 if (Diagnosed == true)
10240 continue;
10241
Richard Trieu708859a2017-06-08 00:56:21 +000010242 Diag(FirstDecl->getLocation(),
10243 diag::err_module_odr_violation_mismatch_decl_unknown)
10244 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10245 << FirstDecl->getSourceRange();
10246 Diag(SecondDecl->getLocation(),
10247 diag::note_module_odr_violation_mismatch_decl_unknown)
10248 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010249 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010250 }
10251
10252 if (!Diagnosed) {
10253 // All definitions are updates to the same declaration. This happens if a
10254 // module instantiates the declaration of a class template specialization
10255 // and two or more other modules instantiate its definition.
10256 //
10257 // FIXME: Indicate which modules had instantiations of this definition.
10258 // FIXME: How can this even happen?
10259 Diag(Merge.first->getLocation(),
10260 diag::err_module_odr_violation_different_instantiations)
10261 << Merge.first;
10262 }
10263 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010264}
10265
Richard Smithce18a182015-07-14 00:26:00 +000010266void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010267 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000010268 ReadTimer->startTimer();
10269}
10270
Guy Benyei11169dd2012-12-18 14:30:41 +000010271void ASTReader::FinishedDeserializing() {
10272 assert(NumCurrentElementsDeserializing &&
10273 "FinishedDeserializing not paired with StartedDeserializing");
10274 if (NumCurrentElementsDeserializing == 1) {
10275 // We decrease NumCurrentElementsDeserializing only after pending actions
10276 // are finished, to avoid recursively re-calling finishPendingActions().
10277 finishPendingActions();
10278 }
10279 --NumCurrentElementsDeserializing;
10280
Richard Smitha0ce9c42014-07-29 23:23:27 +000010281 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010282 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000010283 while (!PendingExceptionSpecUpdates.empty()) {
10284 auto Updates = std::move(PendingExceptionSpecUpdates);
10285 PendingExceptionSpecUpdates.clear();
10286 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000010287 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000010288 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000010289 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000010290 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000010291 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000010292 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000010293 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000010294 }
Richard Smith9e2341d2015-03-23 03:25:59 +000010295 }
10296
Richard Smithce18a182015-07-14 00:26:00 +000010297 if (ReadTimer)
10298 ReadTimer->stopTimer();
10299
Richard Smith0f4e2c42015-08-06 04:23:48 +000010300 diagnoseOdrViolations();
10301
Richard Smith04d05b52014-03-23 00:27:18 +000010302 // We are not in recursive loading, so it's safe to pass the "interesting"
10303 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010304 if (Consumer)
10305 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000010306 }
10307}
10308
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010309void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010310 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10311 // Remove any fake results before adding any real ones.
10312 auto It = PendingFakeLookupResults.find(II);
10313 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000010314 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000010315 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000010316 // FIXME: this works around module+PCH performance issue.
10317 // Rather than erase the result from the map, which is O(n), just clear
10318 // the vector of NamedDecls.
10319 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000010320 }
10321 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010322
10323 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10324 SemaObj->TUScope->AddDecl(D);
10325 } else if (SemaObj->TUScope) {
10326 // Adding the decl to IdResolver may have failed because it was already in
10327 // (even though it was not added in scope). If it is already in, make sure
10328 // it gets in the scope as well.
10329 if (std::find(SemaObj->IdResolver.begin(Name),
10330 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10331 SemaObj->TUScope->AddDecl(D);
10332 }
10333}
10334
Richard Smithdbafb6c2017-06-29 23:23:46 +000010335ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000010336 const PCHContainerReader &PCHContainerRdr,
10337 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10338 StringRef isysroot, bool DisableValidation,
10339 bool AllowASTWithCompilerErrors,
10340 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10341 bool UseGlobalIndex,
10342 std::unique_ptr<llvm::Timer> ReadTimer)
10343 : Listener(DisableValidation
10344 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10345 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000010346 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010347 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000010348 ContextObj(Context),
Victor Leschukdb689112017-08-30 11:31:56 +000010349 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000010350 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10351 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000010352 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000010353 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10354 AllowConfigurationMismatch(AllowConfigurationMismatch),
10355 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010356 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000010357 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010358
10359 for (const auto &Ext : Extensions) {
10360 auto BlockName = Ext->getExtensionMetadata().BlockName;
10361 auto Known = ModuleFileExtensions.find(BlockName);
10362 if (Known != ModuleFileExtensions.end()) {
10363 Diags.Report(diag::warn_duplicate_module_file_extension)
10364 << BlockName;
10365 continue;
10366 }
10367
10368 ModuleFileExtensions.insert({BlockName, Ext});
10369 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010370}
10371
10372ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000010373 if (OwnsDeserializationListener)
10374 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000010375}
Richard Smith10379092016-05-06 23:14:07 +000010376
10377IdentifierResolver &ASTReader::getIdResolver() {
10378 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10379}
David L. Jonesbe1557a2016-12-21 00:17:49 +000010380
10381unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10382 unsigned AbbrevID) {
10383 Idx = 0;
10384 Record.clear();
10385 return Cursor.readRecord(AbbrevID, Record);
10386}