blob: d9033c830a857f85f5a1490080791e364d5b6fcc [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
Guy Benyei11169dd2012-12-18 14:30:41 +0000295 return false;
296}
297
298/// \brief Compare the given set of target options against an existing set of
299/// target options.
300///
301/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
302///
303/// \returns true if the target options mis-match, false otherwise.
304static bool checkTargetOptions(const TargetOptions &TargetOpts,
305 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 DiagnosticsEngine *Diags,
307 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308#define CHECK_TARGET_OPT(Field, Name) \
309 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
310 if (Diags) \
311 Diags->Report(diag::err_pch_targetopt_mismatch) \
312 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
313 return true; \
314 }
315
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000319
320 // We can tolerate different CPUs in many cases, notably when one CPU
321 // supports a strict superset of another. When allowing compatible
322 // differences skip this check.
323 if (!AllowCompatibleDifferences)
324 CHECK_TARGET_OPT(CPU, "target CPU");
325
Guy Benyei11169dd2012-12-18 14:30:41 +0000326#undef CHECK_TARGET_OPT
327
328 // Compare feature sets.
329 SmallVector<StringRef, 4> ExistingFeatures(
330 ExistingTargetOpts.FeaturesAsWritten.begin(),
331 ExistingTargetOpts.FeaturesAsWritten.end());
332 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
333 TargetOpts.FeaturesAsWritten.end());
334 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
335 std::sort(ReadFeatures.begin(), ReadFeatures.end());
336
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000337 // We compute the set difference in both directions explicitly so that we can
338 // diagnose the differences differently.
339 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
340 std::set_difference(
341 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
342 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
343 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
344 ExistingFeatures.begin(), ExistingFeatures.end(),
345 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000346
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000347 // If we are allowing compatible differences and the read feature set is
348 // a strict subset of the existing feature set, there is nothing to diagnose.
349 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
350 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000351
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000352 if (Diags) {
353 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000355 << /* is-existing-feature */ false << Feature;
356 for (StringRef Feature : UnmatchedExistingFeatures)
357 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
358 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000359 }
360
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000361 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000362}
363
364bool
365PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000366 bool Complain,
367 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 const LangOptions &ExistingLangOpts = PP.getLangOpts();
369 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000370 Complain ? &Reader.Diags : nullptr,
371 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000372}
373
374bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000375 bool Complain,
376 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000377 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
378 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000379 Complain ? &Reader.Diags : nullptr,
380 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000381}
382
383namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000384
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
386 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000387 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
388 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000389
390} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000391
Ben Langmuirb92de022014-04-29 16:25:26 +0000392static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
393 DiagnosticsEngine &Diags,
394 bool Complain) {
395 typedef DiagnosticsEngine::Level Level;
396
397 // Check current mappings for new -Werror mappings, and the stored mappings
398 // for cases that were explicitly mapped to *not* be errors that are now
399 // errors because of options like -Werror.
400 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
401
402 for (DiagnosticsEngine *MappingSource : MappingSources) {
403 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
404 diag::kind DiagID = DiagIDMappingPair.first;
405 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
406 if (CurLevel < DiagnosticsEngine::Error)
407 continue; // not significant
408 Level StoredLevel =
409 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
410 if (StoredLevel < DiagnosticsEngine::Error) {
411 if (Complain)
412 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
413 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
414 return true;
415 }
416 }
417 }
418
419 return false;
420}
421
Alp Tokerac4e8e52014-06-22 21:58:33 +0000422static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
423 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
424 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
425 return true;
426 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000427}
428
429static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
430 DiagnosticsEngine &Diags,
431 bool IsSystem, bool Complain) {
432 // Top-level options
433 if (IsSystem) {
434 if (Diags.getSuppressSystemWarnings())
435 return false;
436 // If -Wsystem-headers was not enabled before, be conservative
437 if (StoredDiags.getSuppressSystemWarnings()) {
438 if (Complain)
439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
440 return true;
441 }
442 }
443
444 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
445 if (Complain)
446 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
447 return true;
448 }
449
450 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
451 !StoredDiags.getEnableAllWarnings()) {
452 if (Complain)
453 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
454 return true;
455 }
456
457 if (isExtHandlingFromDiagsError(Diags) &&
458 !isExtHandlingFromDiagsError(StoredDiags)) {
459 if (Complain)
460 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
461 return true;
462 }
463
464 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
465}
466
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000467/// Return the top import module if it is implicit, nullptr otherwise.
468static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
469 Preprocessor &PP) {
470 // If the original import came from a file explicitly generated by the user,
471 // don't check the diagnostic mappings.
472 // FIXME: currently this is approximated by checking whether this is not a
473 // module import of an implicitly-loaded module file.
474 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
475 // the transitive closure of its imports, since unrelated modules cannot be
476 // imported until after this module finishes validation.
477 ModuleFile *TopImport = &*ModuleMgr.rbegin();
478 while (!TopImport->ImportedBy.empty())
479 TopImport = TopImport->ImportedBy[0];
480 if (TopImport->Kind != MK_ImplicitModule)
481 return nullptr;
482
483 StringRef ModuleName = TopImport->ModuleName;
484 assert(!ModuleName.empty() && "diagnostic options read before module name");
485
486 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
487 assert(M && "missing module");
488 return M;
489}
490
Ben Langmuirb92de022014-04-29 16:25:26 +0000491bool PCHValidator::ReadDiagnosticOptions(
492 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
493 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
494 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
495 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000496 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000497 // This should never fail, because we would have processed these options
498 // before writing them to an ASTFile.
499 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
500
501 ModuleManager &ModuleMgr = Reader.getModuleManager();
502 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
503
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000504 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
505 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000506 return false;
507
Ben Langmuirb92de022014-04-29 16:25:26 +0000508 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
509 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000510 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
511 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000512}
513
Guy Benyei11169dd2012-12-18 14:30:41 +0000514/// \brief Collect the macro definitions provided by the given preprocessor
515/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000516static void
517collectMacroDefinitions(const PreprocessorOptions &PPOpts,
518 MacroDefinitionsMap &Macros,
519 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000520 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
521 StringRef Macro = PPOpts.Macros[I].first;
522 bool IsUndef = PPOpts.Macros[I].second;
523
524 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
525 StringRef MacroName = MacroPair.first;
526 StringRef MacroBody = MacroPair.second;
527
528 // For an #undef'd macro, we only care about the name.
529 if (IsUndef) {
530 if (MacroNames && !Macros.count(MacroName))
531 MacroNames->push_back(MacroName);
532
533 Macros[MacroName] = std::make_pair("", true);
534 continue;
535 }
536
537 // For a #define'd macro, figure out the actual definition.
538 if (MacroName.size() == Macro.size())
539 MacroBody = "1";
540 else {
541 // Note: GCC drops anything following an end-of-line character.
542 StringRef::size_type End = MacroBody.find_first_of("\n\r");
543 MacroBody = MacroBody.substr(0, End);
544 }
545
546 if (MacroNames && !Macros.count(MacroName))
547 MacroNames->push_back(MacroName);
548 Macros[MacroName] = std::make_pair(MacroBody, false);
549 }
550}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552/// \brief Check the preprocessor options deserialized from the control block
553/// against the preprocessor options in an existing preprocessor.
554///
555/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000556/// \param Validate If true, validate preprocessor options. If false, allow
557/// macros defined by \p ExistingPPOpts to override those defined by
558/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000559static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
560 const PreprocessorOptions &ExistingPPOpts,
561 DiagnosticsEngine *Diags,
562 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000563 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000564 const LangOptions &LangOpts,
565 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Check macro definitions.
567 MacroDefinitionsMap ASTFileMacros;
568 collectMacroDefinitions(PPOpts, ASTFileMacros);
569 MacroDefinitionsMap ExistingMacros;
570 SmallVector<StringRef, 4> ExistingMacroNames;
571 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
572
573 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
574 // Dig out the macro definition in the existing preprocessor options.
575 StringRef MacroName = ExistingMacroNames[I];
576 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
577
578 // Check whether we know anything about this macro name or not.
579 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
580 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000581 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 // FIXME: Check whether this identifier was referenced anywhere in the
583 // AST file. If so, we should reject the AST file. Unfortunately, this
584 // information isn't in the control block. What shall we do about it?
585
586 if (Existing.second) {
587 SuggestedPredefines += "#undef ";
588 SuggestedPredefines += MacroName.str();
589 SuggestedPredefines += '\n';
590 } else {
591 SuggestedPredefines += "#define ";
592 SuggestedPredefines += MacroName.str();
593 SuggestedPredefines += ' ';
594 SuggestedPredefines += Existing.first.str();
595 SuggestedPredefines += '\n';
596 }
597 continue;
598 }
599
600 // If the macro was defined in one but undef'd in the other, we have a
601 // conflict.
602 if (Existing.second != Known->second.second) {
603 if (Diags) {
604 Diags->Report(diag::err_pch_macro_def_undef)
605 << MacroName << Known->second.second;
606 }
607 return true;
608 }
609
610 // If the macro was #undef'd in both, or if the macro bodies are identical,
611 // it's fine.
612 if (Existing.second || Existing.first == Known->second.first)
613 continue;
614
615 // The macro bodies differ; complain.
616 if (Diags) {
617 Diags->Report(diag::err_pch_macro_def_conflict)
618 << MacroName << Known->second.first << Existing.first;
619 }
620 return true;
621 }
622
623 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000624 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000625 if (Diags) {
626 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
627 }
628 return true;
629 }
630
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000631 // Detailed record is important since it is used for the module cache hash.
632 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000633 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000634 if (Diags) {
635 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
636 }
637 return true;
638 }
639
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 // Compute the #include and #include_macros lines we need.
641 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
642 StringRef File = ExistingPPOpts.Includes[I];
643 if (File == ExistingPPOpts.ImplicitPCHInclude)
644 continue;
645
646 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
647 != PPOpts.Includes.end())
648 continue;
649
650 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 SuggestedPredefines += "\"\n";
653 }
654
655 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
656 StringRef File = ExistingPPOpts.MacroIncludes[I];
657 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
658 File)
659 != PPOpts.MacroIncludes.end())
660 continue;
661
662 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000663 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 SuggestedPredefines += "\"\n##\n";
665 }
666
667 return false;
668}
669
670bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
671 bool Complain,
672 std::string &SuggestedPredefines) {
673 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
674
675 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000676 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000678 SuggestedPredefines,
679 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
Yaxun Liu43712e02016-09-07 18:40:20 +0000682bool SimpleASTReaderListener::ReadPreprocessorOptions(
683 const PreprocessorOptions &PPOpts,
684 bool Complain,
685 std::string &SuggestedPredefines) {
686 return checkPreprocessorOptions(PPOpts,
687 PP.getPreprocessorOpts(),
688 nullptr,
689 PP.getFileManager(),
690 SuggestedPredefines,
691 PP.getLangOpts(),
692 false);
693}
694
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000695/// Check the header search options deserialized from the control block
696/// against the header search options in an existing preprocessor.
697///
698/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
699static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
700 StringRef SpecificModuleCachePath,
701 StringRef ExistingModuleCachePath,
702 DiagnosticsEngine *Diags,
703 const LangOptions &LangOpts) {
704 if (LangOpts.Modules) {
705 if (SpecificModuleCachePath != ExistingModuleCachePath) {
706 if (Diags)
707 Diags->Report(diag::err_pch_modulecache_mismatch)
708 << SpecificModuleCachePath << ExistingModuleCachePath;
709 return true;
710 }
711 }
712
713 return false;
714}
715
716bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
717 StringRef SpecificModuleCachePath,
718 bool Complain) {
719 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
720 PP.getHeaderSearchInfo().getModuleCachePath(),
721 Complain ? &Reader.Diags : nullptr,
722 PP.getLangOpts());
723}
724
Guy Benyei11169dd2012-12-18 14:30:41 +0000725void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
726 PP.setCounterValue(Value);
727}
728
729//===----------------------------------------------------------------------===//
730// AST reader implementation
731//===----------------------------------------------------------------------===//
732
Nico Weber824285e2014-05-08 04:26:47 +0000733void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
734 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000736 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000737}
738
Guy Benyei11169dd2012-12-18 14:30:41 +0000739unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
740 return serialization::ComputeHash(Sel);
741}
742
Guy Benyei11169dd2012-12-18 14:30:41 +0000743std::pair<unsigned, unsigned>
744ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000745 using namespace llvm::support;
746 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
747 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 return std::make_pair(KeyLen, DataLen);
749}
750
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000751ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000752ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000753 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000755 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
756 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
757 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 if (N == 0)
759 return SelTable.getNullarySelector(FirstII);
760 else if (N == 1)
761 return SelTable.getUnarySelector(FirstII);
762
763 SmallVector<IdentifierInfo *, 16> Args;
764 Args.push_back(FirstII);
765 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 Args.push_back(Reader.getLocalIdentifier(
767 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000768
769 return SelTable.getSelector(N, Args.data());
770}
771
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000772ASTSelectorLookupTrait::data_type
773ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000775 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000776
777 data_type Result;
778
Justin Bogner57ba0b22014-03-28 22:03:24 +0000779 Result.ID = Reader.getGlobalSelectorID(
780 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000781 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
782 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
783 Result.InstanceBits = FullInstanceBits & 0x3;
784 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
785 Result.FactoryBits = FullFactoryBits & 0x3;
786 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
787 unsigned NumInstanceMethods = FullInstanceBits >> 3;
788 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000789
790 // Load instance methods
791 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000792 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
793 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000794 Result.Instance.push_back(Method);
795 }
796
797 // Load factory methods
798 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000799 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
800 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 Result.Factory.push_back(Method);
802 }
803
804 return Result;
805}
806
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000807unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
808 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000809}
810
811std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000812ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000813 using namespace llvm::support;
814 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
815 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 return std::make_pair(KeyLen, DataLen);
817}
818
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000819ASTIdentifierLookupTraitBase::internal_key_type
820ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000822 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823}
824
Douglas Gregordcf25082013-02-11 18:16:18 +0000825/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000826static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
827 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000828 return II.hadMacroDefinition() ||
829 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000830 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000831 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000832 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
833 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000834}
835
Richard Smith76c2f2c2015-07-17 20:09:43 +0000836static bool readBit(unsigned &Bits) {
837 bool Value = Bits & 0x1;
838 Bits >>= 1;
839 return Value;
840}
841
Richard Smith79bf9202015-08-24 03:33:22 +0000842IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
843 using namespace llvm::support;
844 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
845 return Reader.getGlobalIdentifierID(F, RawID >> 1);
846}
847
Richard Smitheb4b58f62016-02-05 01:40:54 +0000848static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
849 if (!II.isFromAST()) {
850 II.setIsFromAST();
851 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
852 if (isInterestingIdentifier(Reader, II, IsModule))
853 II.setChangedSinceDeserialization();
854 }
855}
856
Guy Benyei11169dd2012-12-18 14:30:41 +0000857IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
858 const unsigned char* d,
859 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000860 using namespace llvm::support;
861 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 bool IsInteresting = RawID & 0x01;
863
864 // Wipe out the "is interesting" bit.
865 RawID = RawID >> 1;
866
Richard Smith76c2f2c2015-07-17 20:09:43 +0000867 // Build the IdentifierInfo and link the identifier ID with it.
868 IdentifierInfo *II = KnownII;
869 if (!II) {
870 II = &Reader.getIdentifierTable().getOwn(k);
871 KnownII = II;
872 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000873 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000874 Reader.markIdentifierUpToDate(II);
875
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
877 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000878 // For uninteresting identifiers, there's nothing else to do. Just notify
879 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000880 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 return II;
882 }
883
Justin Bogner57ba0b22014-03-28 22:03:24 +0000884 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
885 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000886 bool CPlusPlusOperatorKeyword = readBit(Bits);
887 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000888 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000889 bool Poisoned = readBit(Bits);
890 bool ExtensionToken = readBit(Bits);
891 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892
893 assert(Bits == 0 && "Extra bits in the identifier?");
894 DataLen -= 8;
895
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 // Set or check the various bits in the IdentifierInfo structure.
897 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000898 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000899 II->revertTokenIDToIdentifier();
900 if (!F.isModule())
901 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
902 else if (HasRevertedBuiltin && II->getBuiltinID()) {
903 II->revertBuiltin();
904 assert((II->hasRevertedBuiltin() ||
905 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
906 "Incorrect ObjC keyword or builtin ID");
907 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 assert(II->isExtensionToken() == ExtensionToken &&
909 "Incorrect extension token flag");
910 (void)ExtensionToken;
911 if (Poisoned)
912 II->setIsPoisoned(true);
913 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
914 "Incorrect C++ operator keyword flag");
915 (void)CPlusPlusOperatorKeyword;
916
917 // If this identifier is a macro, deserialize the macro
918 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000919 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000920 uint32_t MacroDirectivesOffset =
921 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000922 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000923
Richard Smithd7329392015-04-21 21:46:32 +0000924 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 }
926
927 Reader.SetIdentifierInfo(ID, II);
928
929 // Read all of the declarations visible at global scope with this
930 // name.
931 if (DataLen > 0) {
932 SmallVector<uint32_t, 4> DeclIDs;
933 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000934 DeclIDs.push_back(Reader.getGlobalDeclID(
935 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 Reader.SetGloballyVisibleDecls(II, DeclIDs);
937 }
938
939 return II;
940}
941
Richard Smitha06c7e62015-08-26 23:55:49 +0000942DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
943 : Kind(Name.getNameKind()) {
944 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000946 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::ObjCZeroArgSelector:
949 case DeclarationName::ObjCOneArgSelector:
950 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000951 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 break;
953 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000954 Data = Name.getCXXOverloadedOperator();
955 break;
956 case DeclarationName::CXXLiteralOperatorName:
957 Data = (uint64_t)Name.getCXXLiteralIdentifier();
958 break;
Richard Smith35845152017-02-07 01:37:30 +0000959 case DeclarationName::CXXDeductionGuideName:
960 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
961 ->getDeclName().getAsIdentifierInfo();
962 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000963 case DeclarationName::CXXConstructorName:
964 case DeclarationName::CXXDestructorName:
965 case DeclarationName::CXXConversionFunctionName:
966 case DeclarationName::CXXUsingDirective:
967 Data = 0;
968 break;
969 }
970}
971
972unsigned DeclarationNameKey::getHash() const {
973 llvm::FoldingSetNodeID ID;
974 ID.AddInteger(Kind);
975
976 switch (Kind) {
977 case DeclarationName::Identifier:
978 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000979 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000980 ID.AddString(((IdentifierInfo*)Data)->getName());
981 break;
982 case DeclarationName::ObjCZeroArgSelector:
983 case DeclarationName::ObjCOneArgSelector:
984 case DeclarationName::ObjCMultiArgSelector:
985 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
986 break;
987 case DeclarationName::CXXOperatorName:
988 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 break;
990 case DeclarationName::CXXConstructorName:
991 case DeclarationName::CXXDestructorName:
992 case DeclarationName::CXXConversionFunctionName:
993 case DeclarationName::CXXUsingDirective:
994 break;
995 }
996
997 return ID.ComputeHash();
998}
999
Richard Smithd88a7f12015-09-01 20:35:42 +00001000ModuleFile *
1001ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1002 using namespace llvm::support;
1003 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1004 return Reader.getLocalModuleFile(F, ModuleFileID);
1005}
1006
Guy Benyei11169dd2012-12-18 14:30:41 +00001007std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001008ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001009 using namespace llvm::support;
1010 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1011 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 return std::make_pair(KeyLen, DataLen);
1013}
1014
Richard Smitha06c7e62015-08-26 23:55:49 +00001015ASTDeclContextNameLookupTrait::internal_key_type
1016ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001017 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001018
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 auto Kind = (DeclarationName::NameKind)*d++;
1020 uint64_t Data;
1021 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001023 case DeclarationName::CXXLiteralOperatorName:
1024 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001026 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001032 (uint64_t)Reader.getLocalSelector(
1033 F, endian::readNext<uint32_t, little, unaligned>(
1034 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 break;
1036 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001037 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 case DeclarationName::CXXConstructorName:
1040 case DeclarationName::CXXDestructorName:
1041 case DeclarationName::CXXConversionFunctionName:
1042 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001043 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 break;
1045 }
1046
Richard Smitha06c7e62015-08-26 23:55:49 +00001047 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
Richard Smithd88a7f12015-09-01 20:35:42 +00001050void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1051 const unsigned char *d,
1052 unsigned DataLen,
1053 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001054 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001055 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1056 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1057 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001059}
1060
Richard Smith0f4e2c42015-08-06 04:23:48 +00001061bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1062 BitstreamCursor &Cursor,
1063 uint64_t Offset,
1064 DeclContext *DC) {
1065 assert(Offset != 0);
1066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001068 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069
Richard Smith0f4e2c42015-08-06 04:23:48 +00001070 RecordData Record;
1071 StringRef Blob;
1072 unsigned Code = Cursor.ReadCode();
1073 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1074 if (RecCode != DECL_CONTEXT_LEXICAL) {
1075 Error("Expected lexical block");
1076 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001077 }
1078
Richard Smith82f8fcd2015-08-06 22:07:25 +00001079 assert(!isa<TranslationUnitDecl>(DC) &&
1080 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001081 // If we are handling a C++ class template instantiation, we can see multiple
1082 // lexical updates for the same record. It's important that we select only one
1083 // of them, so that field numbering works properly. Just pick the first one we
1084 // see.
1085 auto &Lex = LexicalDecls[DC];
1086 if (!Lex.first) {
1087 Lex = std::make_pair(
1088 &M, llvm::makeArrayRef(
1089 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1090 Blob.data()),
1091 Blob.size() / 4));
1092 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001093 DC->setHasExternalLexicalStorage(true);
1094 return false;
1095}
Guy Benyei11169dd2012-12-18 14:30:41 +00001096
Richard Smith0f4e2c42015-08-06 04:23:48 +00001097bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1098 BitstreamCursor &Cursor,
1099 uint64_t Offset,
1100 DeclID ID) {
1101 assert(Offset != 0);
1102
1103 SavedStreamPosition SavedPosition(Cursor);
1104 Cursor.JumpToBit(Offset);
1105
1106 RecordData Record;
1107 StringRef Blob;
1108 unsigned Code = Cursor.ReadCode();
1109 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1110 if (RecCode != DECL_CONTEXT_VISIBLE) {
1111 Error("Expected visible lookup table block");
1112 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 }
1114
Richard Smith0f4e2c42015-08-06 04:23:48 +00001115 // We can't safely determine the primary context yet, so delay attaching the
1116 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001117 auto *Data = (const unsigned char*)Blob.data();
1118 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 return false;
1120}
1121
Richard Smith37a93df2017-02-18 00:32:02 +00001122void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001124 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1125 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001126 Diag(diag::note_module_cache_path)
1127 << PP.getHeaderSearchInfo().getModuleCachePath();
1128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001129}
1130
1131void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001132 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 if (Diags.isDiagnosticInFlight())
1134 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1135 else
1136 Diag(DiagID) << Arg1 << Arg2;
1137}
1138
1139//===----------------------------------------------------------------------===//
1140// Source Manager Deserialization
1141//===----------------------------------------------------------------------===//
1142
1143/// \brief Read the line table in the source manager block.
1144/// \returns true if there was an error.
1145bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001146 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 unsigned Idx = 0;
1148 LineTableInfo &LineTable = SourceMgr.getLineTable();
1149
1150 // Parse the file names
1151 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001152 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001154 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1156 }
Richard Smith63078492015-09-01 07:41:55 +00001157 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001158
1159 // Parse the line entries
1160 std::vector<LineEntry> Entries;
1161 while (Idx < Record.size()) {
1162 int FID = Record[Idx++];
1163 assert(FID >= 0 && "Serialized line entries for non-local file.");
1164 // Remap FileID from 1-based old view.
1165 FID += F.SLocEntryBaseID - 1;
1166
1167 // Extract the line entries
1168 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001169 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Entries.clear();
1171 Entries.reserve(NumEntries);
1172 for (unsigned I = 0; I != NumEntries; ++I) {
1173 unsigned FileOffset = Record[Idx++];
1174 unsigned LineNo = Record[Idx++];
1175 int FilenameID = FileIDs[Record[Idx++]];
1176 SrcMgr::CharacteristicKind FileKind
1177 = (SrcMgr::CharacteristicKind)Record[Idx++];
1178 unsigned IncludeOffset = Record[Idx++];
1179 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1180 FileKind, IncludeOffset));
1181 }
1182 LineTable.AddEntry(FileID::get(FID), Entries);
1183 }
1184
1185 return false;
1186}
1187
1188/// \brief Read a source manager block
1189bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1190 using namespace SrcMgr;
1191
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001192 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
1194 // Set the source-location entry cursor to the current position in
1195 // the stream. This cursor will be used to read the contents of the
1196 // source manager block initially, and then lazily read
1197 // source-location entries as needed.
1198 SLocEntryCursor = F.Stream;
1199
1200 // The stream itself is going to skip over the source manager block.
1201 if (F.Stream.SkipBlock()) {
1202 Error("malformed block record in AST file");
1203 return true;
1204 }
1205
1206 // Enter the source manager block.
1207 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1208 Error("malformed source manager block record in AST file");
1209 return true;
1210 }
1211
1212 RecordData Record;
1213 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001214 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001215
Chris Lattnere7b154b2013-01-19 21:39:22 +00001216 switch (E.Kind) {
1217 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1218 case llvm::BitstreamEntry::Error:
1219 Error("malformed block record in AST file");
1220 return true;
1221 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001223 case llvm::BitstreamEntry::Record:
1224 // The interesting case.
1225 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001227
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001230 StringRef Blob;
1231 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 default: // Default behavior: ignore.
1233 break;
1234
1235 case SM_SLOC_FILE_ENTRY:
1236 case SM_SLOC_BUFFER_ENTRY:
1237 case SM_SLOC_EXPANSION_ENTRY:
1238 // Once we hit one of the source location entries, we're done.
1239 return false;
1240 }
1241 }
1242}
1243
1244/// \brief If a header file is not found at the path that we expect it to be
1245/// and the PCH file was moved from its original location, try to resolve the
1246/// file by assuming that header+PCH were moved together and the header is in
1247/// the same place relative to the PCH.
1248static std::string
1249resolveFileRelativeToOriginalDir(const std::string &Filename,
1250 const std::string &OriginalDir,
1251 const std::string &CurrDir) {
1252 assert(OriginalDir != CurrDir &&
1253 "No point trying to resolve the file if the PCH dir didn't change");
1254 using namespace llvm::sys;
1255 SmallString<128> filePath(Filename);
1256 fs::make_absolute(filePath);
1257 assert(path::is_absolute(OriginalDir));
1258 SmallString<128> currPCHPath(CurrDir);
1259
1260 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1261 fileDirE = path::end(path::parent_path(filePath));
1262 path::const_iterator origDirI = path::begin(OriginalDir),
1263 origDirE = path::end(OriginalDir);
1264 // Skip the common path components from filePath and OriginalDir.
1265 while (fileDirI != fileDirE && origDirI != origDirE &&
1266 *fileDirI == *origDirI) {
1267 ++fileDirI;
1268 ++origDirI;
1269 }
1270 for (; origDirI != origDirE; ++origDirI)
1271 path::append(currPCHPath, "..");
1272 path::append(currPCHPath, fileDirI, fileDirE);
1273 path::append(currPCHPath, path::filename(Filename));
1274 return currPCHPath.str();
1275}
1276
1277bool ASTReader::ReadSLocEntry(int ID) {
1278 if (ID == 0)
1279 return false;
1280
1281 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282 Error("source location entry ID out-of-range for AST file");
1283 return true;
1284 }
1285
Richard Smithaada85c2016-02-06 02:06:43 +00001286 // Local helper to read the (possibly-compressed) buffer data following the
1287 // entry record.
1288 auto ReadBuffer = [this](
1289 BitstreamCursor &SLocEntryCursor,
1290 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1291 RecordData Record;
1292 StringRef Blob;
1293 unsigned Code = SLocEntryCursor.ReadCode();
1294 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1295
1296 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001297 if (!llvm::zlib::isAvailable()) {
1298 Error("zlib is not available");
1299 return nullptr;
1300 }
Richard Smithaada85c2016-02-06 02:06:43 +00001301 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001302 if (llvm::Error E =
1303 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1304 Error("could not decompress embedded file contents: " +
1305 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001306 return nullptr;
1307 }
1308 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1309 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1310 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1311 } else {
1312 Error("AST record has invalid code");
1313 return nullptr;
1314 }
1315 };
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1318 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 unsigned BaseOffset = F->SLocEntryBaseOffset;
1321
1322 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001323 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1324 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 Error("incorrectly-formatted source location entry in AST file");
1326 return true;
1327 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001328
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001330 StringRef Blob;
1331 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 default:
1333 Error("incorrectly-formatted source location entry in AST file");
1334 return true;
1335
1336 case SM_SLOC_FILE_ENTRY: {
1337 // We will detect whether a file changed and return 'Failure' for it, but
1338 // we will also try to fail gracefully by setting up the SLocEntry.
1339 unsigned InputID = Record[4];
1340 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001341 const FileEntry *File = IF.getFile();
1342 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001343
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001344 // Note that we only check if a File was returned. If it was out-of-date
1345 // we have complained but we will continue creating a FileID to recover
1346 // gracefully.
1347 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 return true;
1349
1350 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1351 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1352 // This is the module's main file.
1353 IncludeLoc = getImportLocation(F);
1354 }
1355 SrcMgr::CharacteristicKind
1356 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1357 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1358 ID, BaseOffset + Record[0]);
1359 SrcMgr::FileInfo &FileInfo =
1360 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1361 FileInfo.NumCreatedFIDs = Record[5];
1362 if (Record[3])
1363 FileInfo.setHasLineDirectives();
1364
1365 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1366 unsigned NumFileDecls = Record[7];
1367 if (NumFileDecls) {
1368 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1369 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1370 NumFileDecls));
1371 }
Richard Smithaada85c2016-02-06 02:06:43 +00001372
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 const SrcMgr::ContentCache *ContentCache
1374 = SourceMgr.getOrCreateContentCache(File,
1375 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1376 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001377 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1378 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001379 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1380 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001382 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 }
1384
1385 break;
1386 }
1387
1388 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001389 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 unsigned Offset = Record[0];
1391 SrcMgr::CharacteristicKind
1392 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1393 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001394 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 IncludeLoc = getImportLocation(F);
1396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Richard Smithaada85c2016-02-06 02:06:43 +00001398 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1399 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001401 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001402 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 break;
1404 }
1405
1406 case SM_SLOC_EXPANSION_ENTRY: {
1407 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1408 SourceMgr.createExpansionLoc(SpellingLoc,
1409 ReadSourceLocation(*F, Record[2]),
1410 ReadSourceLocation(*F, Record[3]),
1411 Record[4],
1412 ID,
1413 BaseOffset + Record[0]);
1414 break;
1415 }
1416 }
1417
1418 return false;
1419}
1420
1421std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1422 if (ID == 0)
1423 return std::make_pair(SourceLocation(), "");
1424
1425 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1426 Error("source location entry ID out-of-range for AST file");
1427 return std::make_pair(SourceLocation(), "");
1428 }
1429
1430 // Find which module file this entry lands in.
1431 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001432 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 return std::make_pair(SourceLocation(), "");
1434
1435 // FIXME: Can we map this down to a particular submodule? That would be
1436 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001437 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001438}
1439
1440/// \brief Find the location where the module F is imported.
1441SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1442 if (F->ImportLoc.isValid())
1443 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001444
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 // Otherwise we have a PCH. It's considered to be "imported" at the first
1446 // location of its includer.
1447 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001448 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001449 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001450 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001452 return F->ImportedBy[0]->FirstLoc;
1453}
1454
1455/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1456/// specified cursor. Read the abbreviations that are at the top of the block
1457/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001458bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001459 if (Cursor.EnterSubBlock(BlockID))
1460 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001461
1462 while (true) {
1463 uint64_t Offset = Cursor.GetCurrentBitNo();
1464 unsigned Code = Cursor.ReadCode();
1465
1466 // We expect all abbrevs to be at the start of the block.
1467 if (Code != llvm::bitc::DEFINE_ABBREV) {
1468 Cursor.JumpToBit(Offset);
1469 return false;
1470 }
1471 Cursor.ReadAbbrevRecord();
1472 }
1473}
1474
Richard Smithe40f2ba2013-08-07 21:41:30 +00001475Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001476 unsigned &Idx) {
1477 Token Tok;
1478 Tok.startToken();
1479 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1480 Tok.setLength(Record[Idx++]);
1481 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1482 Tok.setIdentifierInfo(II);
1483 Tok.setKind((tok::TokenKind)Record[Idx++]);
1484 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1485 return Tok;
1486}
1487
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001488MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001489 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001490
1491 // Keep track of where we are in the stream, then jump back there
1492 // after reading this macro.
1493 SavedStreamPosition SavedPosition(Stream);
1494
1495 Stream.JumpToBit(Offset);
1496 RecordData Record;
1497 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001498 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001499
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001501 // Advance to the next record, but if we get to the end of the block, don't
1502 // pop it (removing all the abbreviations from the cursor) since we want to
1503 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001504 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001505 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001506
Chris Lattnerefa77172013-01-20 00:00:22 +00001507 switch (Entry.Kind) {
1508 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1509 case llvm::BitstreamEntry::Error:
1510 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001511 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001512 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001514 case llvm::BitstreamEntry::Record:
1515 // The interesting case.
1516 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 }
1518
1519 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 Record.clear();
1521 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001522 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001524 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001525 case PP_MACRO_DIRECTIVE_HISTORY:
1526 return Macro;
1527
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 case PP_MACRO_OBJECT_LIKE:
1529 case PP_MACRO_FUNCTION_LIKE: {
1530 // If we already have a macro, that means that we've hit the end
1531 // of the definition of the macro we were looking for. We're
1532 // done.
1533 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001534 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001535
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001536 unsigned NextIndex = 1; // Skip identifier ID.
1537 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001539 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001540 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001542 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1545 // Decode function-like macro info.
1546 bool isC99VarArgs = Record[NextIndex++];
1547 bool isGNUVarArgs = Record[NextIndex++];
1548 bool hasCommaPasting = Record[NextIndex++];
1549 MacroArgs.clear();
1550 unsigned NumArgs = Record[NextIndex++];
1551 for (unsigned i = 0; i != NumArgs; ++i)
1552 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1553
1554 // Install function-like macro info.
1555 MI->setIsFunctionLike();
1556 if (isC99VarArgs) MI->setIsC99Varargs();
1557 if (isGNUVarArgs) MI->setIsGNUVarargs();
1558 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001559 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 }
1561
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 // Remember that we saw this macro last so that we add the tokens that
1563 // form its body to it.
1564 Macro = MI;
1565
1566 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1567 Record[NextIndex]) {
1568 // We have a macro definition. Register the association
1569 PreprocessedEntityID
1570 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1571 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001572 PreprocessingRecord::PPEntityID PPID =
1573 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1574 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1575 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001576 if (PPDef)
1577 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 }
1579
1580 ++NumMacrosRead;
1581 break;
1582 }
1583
1584 case PP_TOKEN: {
1585 // If we see a TOKEN before a PP_MACRO_*, then the file is
1586 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001587 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001588
John McCallf413f5e2013-05-03 00:10:13 +00001589 unsigned Idx = 0;
1590 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 Macro->AddTokenToBody(Tok);
1592 break;
1593 }
1594 }
1595 }
1596}
1597
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001598PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001599ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1600 unsigned LocalID) const {
1601 if (!M.ModuleOffsetMap.empty())
1602 ReadModuleOffsetMap(M);
1603
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001606 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 return LocalID + I->second;
1610}
1611
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001612unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1613 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001614}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001615
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001616HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001617HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001618 internal_key_type ikey = {FE->getSize(),
1619 M.HasTimestamps ? FE->getModificationTime() : 0,
1620 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001621 return ikey;
1622}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001623
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001624bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001625 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 return false;
1627
Mehdi Amini004b9c72016-10-10 22:52:47 +00001628 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001629 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001632 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001633 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1634 if (!Key.Imported)
1635 return FileMgr.getFile(Key.Filename);
1636
1637 std::string Resolved = Key.Filename;
1638 Reader.ResolveImportedPath(M, Resolved);
1639 return FileMgr.getFile(Resolved);
1640 };
1641
1642 const FileEntry *FEA = GetFile(a);
1643 const FileEntry *FEB = GetFile(b);
1644 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001645}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001646
Guy Benyei11169dd2012-12-18 14:30:41 +00001647std::pair<unsigned, unsigned>
1648HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001649 using namespace llvm::support;
1650 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001652 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001653}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001654
1655HeaderFileInfoTrait::internal_key_type
1656HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001657 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001658 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001659 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1660 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001661 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001662 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001663 return ikey;
1664}
1665
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001666HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001667HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 unsigned DataLen) {
1669 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001670 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 HeaderFileInfo HFI;
1672 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001673 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1674 HFI.isImport |= (Flags >> 4) & 0x01;
1675 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1676 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001678 // FIXME: Find a better way to handle this. Maybe just store a
1679 // "has been included" flag?
1680 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1681 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001682 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1683 M, endian::readNext<uint32_t, little, unaligned>(d));
1684 if (unsigned FrameworkOffset =
1685 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001686 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 // since 0 is used as an indicator for "no framework name".
1688 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1689 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1690 }
Richard Smith386bb072015-08-18 23:42:23 +00001691
1692 assert((End - d) % 4 == 0 &&
1693 "Wrong data length in HeaderFileInfo deserialization");
1694 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001695 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001696 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1697 LocalSMID >>= 2;
1698
1699 // This header is part of a module. Associate it with the module to enable
1700 // implicit module import.
1701 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1702 Module *Mod = Reader.getSubmodule(GlobalSMID);
1703 FileManager &FileMgr = Reader.getFileManager();
1704 ModuleMap &ModMap =
1705 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1706
1707 std::string Filename = key.Filename;
1708 if (key.Imported)
1709 Reader.ResolveImportedPath(M, Filename);
1710 // FIXME: This is not always the right filename-as-written, but we're not
1711 // going to use this information to rebuild the module, so it doesn't make
1712 // a lot of difference.
1713 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001714 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1715 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001716 }
1717
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 // This HeaderFileInfo was externally loaded.
1719 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001720 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 return HFI;
1722}
1723
Richard Smithd7329392015-04-21 21:46:32 +00001724void ASTReader::addPendingMacro(IdentifierInfo *II,
1725 ModuleFile *M,
1726 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1728 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001729}
1730
1731void ASTReader::ReadDefinedMacros() {
1732 // Note that we are loading defined macros.
1733 Deserializing Macros(this);
1734
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001735 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1736 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737
1738 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001739 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 continue;
1741
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001742 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001743 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001744
1745 RecordData Record;
1746 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001748
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 switch (E.Kind) {
1750 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1751 case llvm::BitstreamEntry::Error:
1752 Error("malformed block record in AST file");
1753 return;
1754 case llvm::BitstreamEntry::EndBlock:
1755 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001756
Chris Lattnere7b154b2013-01-19 21:39:22 +00001757 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001758 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001759 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001760 default: // Default behavior: ignore.
1761 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001762
Chris Lattnere7b154b2013-01-19 21:39:22 +00001763 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001764 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001765 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001766 if (II->isOutOfDate())
1767 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001768 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001769 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001770
Chris Lattnere7b154b2013-01-19 21:39:22 +00001771 case PP_TOKEN:
1772 // Ignore tokens.
1773 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 break;
1776 }
1777 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001778 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 }
1780}
1781
1782namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001783
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 /// \brief Visitor class used to look up identifirs in an AST file.
1785 class IdentifierLookupVisitor {
1786 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001787 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001788 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001789 unsigned &NumIdentifierLookups;
1790 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001792
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001794 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1795 unsigned &NumIdentifierLookups,
1796 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001797 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1798 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001799 NumIdentifierLookups(NumIdentifierLookups),
1800 NumIdentifierLookupHits(NumIdentifierLookupHits),
1801 Found()
1802 {
1803 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001804
1805 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001807 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001809
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 ASTIdentifierLookupTable *IdTable
1811 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1812 if (!IdTable)
1813 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001814
1815 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001816 Found);
1817 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001818 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001819 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 if (Pos == IdTable->end())
1821 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001822
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 // Dereferencing the iterator has the effect of building the
1824 // IdentifierInfo node and populating it with the various
1825 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001826 ++NumIdentifierLookupHits;
1827 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 return true;
1829 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001830
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 // \brief Retrieve the identifier info found within the module
1832 // files.
1833 IdentifierInfo *getIdentifierInfo() const { return Found; }
1834 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001835
1836} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001837
1838void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1839 // Note that we are loading an identifier.
1840 Deserializing AnIdentifier(this);
1841
1842 unsigned PriorGeneration = 0;
1843 if (getContext().getLangOpts().Modules)
1844 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001845
1846 // If there is a global index, look there first to determine which modules
1847 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001848 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001849 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001850 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001851 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1852 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001853 }
1854 }
1855
Douglas Gregor7211ac12013-01-25 23:32:03 +00001856 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001857 NumIdentifierLookups,
1858 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001859 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 markIdentifierUpToDate(&II);
1861}
1862
1863void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1864 if (!II)
1865 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001866
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 II->setOutOfDate(false);
1868
1869 // Update the generation for this identifier.
1870 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001871 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001872}
1873
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001874void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1875 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001876 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
1878 BitstreamCursor &Cursor = M.MacroCursor;
1879 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001880 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001881
Richard Smith713369b2015-04-23 20:40:50 +00001882 struct ModuleMacroRecord {
1883 SubmoduleID SubModID;
1884 MacroInfo *MI;
1885 SmallVector<SubmoduleID, 8> Overrides;
1886 };
1887 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001888
Richard Smithd7329392015-04-21 21:46:32 +00001889 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1890 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1891 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001892 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001893 while (true) {
1894 llvm::BitstreamEntry Entry =
1895 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1896 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1897 Error("malformed block record in AST file");
1898 return;
1899 }
1900
1901 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001902 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001903 case PP_MACRO_DIRECTIVE_HISTORY:
1904 break;
1905
1906 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001907 ModuleMacros.push_back(ModuleMacroRecord());
1908 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001909 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1910 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001911 for (int I = 2, N = Record.size(); I != N; ++I)
1912 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001913 continue;
1914 }
1915
1916 default:
1917 Error("malformed block record in AST file");
1918 return;
1919 }
1920
1921 // We found the macro directive history; that's the last record
1922 // for this macro.
1923 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001924 }
1925
Richard Smithd7329392015-04-21 21:46:32 +00001926 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001927 {
1928 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001929 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001930 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001931 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001932 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001933 Module *Mod = getSubmodule(ModID);
1934 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001935 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001936 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001937 }
1938
1939 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001940 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001941 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001942 }
1943 }
1944
1945 // Don't read the directive history for a module; we don't have anywhere
1946 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001947 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001948 return;
1949
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001950 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001951 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001952 unsigned Idx = 0, N = Record.size();
1953 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001954 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001955 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001956 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1957 switch (K) {
1958 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001959 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001960 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001961 break;
1962 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001963 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001964 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001965 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001966 }
1967 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001968 bool isPublic = Record[Idx++];
1969 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1970 break;
1971 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001972
1973 if (!Latest)
1974 Latest = MD;
1975 if (Earliest)
1976 Earliest->setPrevious(MD);
1977 Earliest = MD;
1978 }
1979
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001980 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001981 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001982}
1983
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001984ASTReader::InputFileInfo
1985ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001986 // Go find this input file.
1987 BitstreamCursor &Cursor = F.InputFilesCursor;
1988 SavedStreamPosition SavedPosition(Cursor);
1989 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1990
1991 unsigned Code = Cursor.ReadCode();
1992 RecordData Record;
1993 StringRef Blob;
1994
1995 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1996 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1997 "invalid record type for input file");
1998 (void)Result;
1999
2000 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002001 InputFileInfo R;
2002 R.StoredSize = static_cast<off_t>(Record[1]);
2003 R.StoredTime = static_cast<time_t>(Record[2]);
2004 R.Overridden = static_cast<bool>(Record[3]);
2005 R.Transient = static_cast<bool>(Record[4]);
2006 R.Filename = Blob;
2007 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002008 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002009}
2010
Manman Renc8c94152016-10-21 23:35:03 +00002011static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002012InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 // If this ID is bogus, just return an empty input file.
2014 if (ID == 0 || ID > F.InputFilesLoaded.size())
2015 return InputFile();
2016
2017 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002018 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 return F.InputFilesLoaded[ID-1];
2020
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002021 if (F.InputFilesLoaded[ID-1].isNotFound())
2022 return InputFile();
2023
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002025 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 SavedStreamPosition SavedPosition(Cursor);
2027 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002028
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002029 InputFileInfo FI = readInputFileInfo(F, ID);
2030 off_t StoredSize = FI.StoredSize;
2031 time_t StoredTime = FI.StoredTime;
2032 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002033 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002034 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002035
Richard Smitha8cfffa2015-11-26 02:04:16 +00002036 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002037
2038 // If we didn't find the file, resolve it relative to the
2039 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002040 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 F.OriginalDir != CurrentDir) {
2042 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2043 F.OriginalDir,
2044 CurrentDir);
2045 if (!Resolved.empty())
2046 File = FileMgr.getFile(Resolved);
2047 }
2048
2049 // For an overridden file, create a virtual file with the stored
2050 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002051 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002053
Craig Toppera13603a2014-05-22 05:54:18 +00002054 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002055 if (Complain) {
2056 std::string ErrorStr = "could not find file '";
2057 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002058 ErrorStr += "' referenced by AST file '";
2059 ErrorStr += F.FileName;
2060 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002061 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002063 // Record that we didn't find the file.
2064 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2065 return InputFile();
2066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002067
Ben Langmuir198c1682014-03-07 07:27:49 +00002068 // Check if there was a request to override the contents of the file
2069 // that was part of the precompiled header. Overridding such a file
2070 // can lead to problems when lexing using the source locations from the
2071 // PCH.
2072 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002073 // FIXME: Reject if the overrides are different.
2074 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002075 if (Complain)
2076 Error(diag::err_fe_pch_file_overridden, Filename);
2077 // After emitting the diagnostic, recover by disabling the override so
2078 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002079 //
2080 // FIXME: This recovery is just as broken as the original state; there may
2081 // be another precompiled module that's using the overridden contents, or
2082 // we might be half way through parsing it. Instead, we should treat the
2083 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002084 SM.disableFileContentsOverride(File);
2085 // The FileEntry is a virtual file entry with the size of the contents
2086 // that would override the original contents. Set it to the original's
2087 // size/time.
2088 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2089 StoredSize, StoredTime);
2090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002091
Ben Langmuir198c1682014-03-07 07:27:49 +00002092 bool IsOutOfDate = false;
2093
2094 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002095 if (!Overridden && //
2096 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002097 (StoredTime && StoredTime != File->getModificationTime() &&
2098 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002099 )) {
2100 if (Complain) {
2101 // Build a list of the PCH imports that got us here (in reverse).
2102 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2103 while (ImportStack.back()->ImportedBy.size() > 0)
2104 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002105
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 // The top-level PCH is stale.
2107 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002108 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2109 if (DiagnosticKind == 0)
2110 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2111 else if (DiagnosticKind == 1)
2112 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2113 else
2114 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002115
Ben Langmuir198c1682014-03-07 07:27:49 +00002116 // Print the import stack.
2117 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2118 Diag(diag::note_pch_required_by)
2119 << Filename << ImportStack[0]->FileName;
2120 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002121 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002123 }
2124
Ben Langmuir198c1682014-03-07 07:27:49 +00002125 if (!Diags.isDiagnosticInFlight())
2126 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 }
2128
Ben Langmuir198c1682014-03-07 07:27:49 +00002129 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002131 // FIXME: If the file is overridden and we've already opened it,
2132 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002133
Richard Smitha8cfffa2015-11-26 02:04:16 +00002134 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002135
2136 // Note that we've loaded this input file.
2137 F.InputFilesLoaded[ID-1] = IF;
2138 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002139}
2140
Richard Smith7ed1bc92014-12-05 22:42:13 +00002141/// \brief If we are loading a relocatable PCH or module file, and the filename
2142/// is not an absolute path, add the system or module root to the beginning of
2143/// the file name.
2144void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2145 // Resolve relative to the base directory, if we have one.
2146 if (!M.BaseDirectory.empty())
2147 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002148}
2149
Richard Smith7ed1bc92014-12-05 22:42:13 +00002150void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2152 return;
2153
Richard Smith7ed1bc92014-12-05 22:42:13 +00002154 SmallString<128> Buffer;
2155 llvm::sys::path::append(Buffer, Prefix, Filename);
2156 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002157}
2158
Richard Smith0f99d6a2015-08-09 08:48:41 +00002159static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2160 switch (ARR) {
2161 case ASTReader::Failure: return true;
2162 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2163 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2164 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2165 case ASTReader::ConfigurationMismatch:
2166 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2167 case ASTReader::HadErrors: return true;
2168 case ASTReader::Success: return false;
2169 }
2170
2171 llvm_unreachable("unknown ASTReadResult");
2172}
2173
Richard Smith0516b182015-09-08 19:40:14 +00002174ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2175 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2176 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002177 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002178 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2179 return Failure;
2180
2181 // Read all of the records in the options block.
2182 RecordData Record;
2183 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002184 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002185 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002186
Richard Smith0516b182015-09-08 19:40:14 +00002187 switch (Entry.Kind) {
2188 case llvm::BitstreamEntry::Error:
2189 case llvm::BitstreamEntry::SubBlock:
2190 return Failure;
2191
2192 case llvm::BitstreamEntry::EndBlock:
2193 return Result;
2194
2195 case llvm::BitstreamEntry::Record:
2196 // The interesting case.
2197 break;
2198 }
2199
2200 // Read and process a record.
2201 Record.clear();
2202 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2203 case LANGUAGE_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2205 if (ParseLanguageOptions(Record, Complain, Listener,
2206 AllowCompatibleConfigurationMismatch))
2207 Result = ConfigurationMismatch;
2208 break;
2209 }
2210
2211 case TARGET_OPTIONS: {
2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2213 if (ParseTargetOptions(Record, Complain, Listener,
2214 AllowCompatibleConfigurationMismatch))
2215 Result = ConfigurationMismatch;
2216 break;
2217 }
2218
Richard Smith0516b182015-09-08 19:40:14 +00002219 case FILE_SYSTEM_OPTIONS: {
2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2221 if (!AllowCompatibleConfigurationMismatch &&
2222 ParseFileSystemOptions(Record, Complain, Listener))
2223 Result = ConfigurationMismatch;
2224 break;
2225 }
2226
2227 case HEADER_SEARCH_OPTIONS: {
2228 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2229 if (!AllowCompatibleConfigurationMismatch &&
2230 ParseHeaderSearchOptions(Record, Complain, Listener))
2231 Result = ConfigurationMismatch;
2232 break;
2233 }
2234
2235 case PREPROCESSOR_OPTIONS:
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2237 if (!AllowCompatibleConfigurationMismatch &&
2238 ParsePreprocessorOptions(Record, Complain, Listener,
2239 SuggestedPredefines))
2240 Result = ConfigurationMismatch;
2241 break;
2242 }
2243 }
2244}
2245
Guy Benyei11169dd2012-12-18 14:30:41 +00002246ASTReader::ASTReadResult
2247ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002248 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002249 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002251 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002252 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002253
2254 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2255 Error("malformed block record in AST file");
2256 return Failure;
2257 }
2258
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002259 // Lambda to read the unhashed control block the first time it's called.
2260 //
2261 // For PCM files, the unhashed control block cannot be read until after the
2262 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2263 // need to look ahead before reading the IMPORTS record. For consistency,
2264 // this block is always read somehow (see BitstreamEntry::EndBlock).
2265 bool HasReadUnhashedControlBlock = false;
2266 auto readUnhashedControlBlockOnce = [&]() {
2267 if (!HasReadUnhashedControlBlock) {
2268 HasReadUnhashedControlBlock = true;
2269 if (ASTReadResult Result =
2270 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2271 return Result;
2272 }
2273 return Success;
2274 };
2275
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 // Read all of the records and blocks in the control block.
2277 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002278 unsigned NumInputs = 0;
2279 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002280 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002281 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002282
Chris Lattnere7b154b2013-01-19 21:39:22 +00002283 switch (Entry.Kind) {
2284 case llvm::BitstreamEntry::Error:
2285 Error("malformed block record in AST file");
2286 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002287 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002288 // Validate the module before returning. This call catches an AST with
2289 // no module name and no imports.
2290 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2291 return Result;
2292
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002293 // Validate input files.
2294 const HeaderSearchOptions &HSOpts =
2295 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002296
Richard Smitha1825302014-10-23 22:18:29 +00002297 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002298 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2299 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002300 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2301 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002303
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002304 // If we are reading a module, we will create a verification timestamp,
2305 // so we verify all input files. Otherwise, verify only user input
2306 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002307
2308 unsigned N = NumUserInputs;
2309 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002310 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002311 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002312 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002313 N = NumInputs;
2314
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002315 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002316 InputFile IF = getInputFile(F, I+1, Complain);
2317 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002319 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002321
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002322 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002323 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002324
Ben Langmuircb69b572014-03-07 06:40:32 +00002325 if (Listener && Listener->needsInputFileVisitation()) {
2326 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2327 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002328 for (unsigned I = 0; I < N; ++I) {
2329 bool IsSystem = I >= NumUserInputs;
2330 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002331 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002332 F.Kind == MK_ExplicitModule ||
2333 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002334 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002335 }
2336
Richard Smith8a308ec2015-11-05 00:54:55 +00002337 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002338 }
2339
Chris Lattnere7b154b2013-01-19 21:39:22 +00002340 case llvm::BitstreamEntry::SubBlock:
2341 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 case INPUT_FILES_BLOCK_ID:
2343 F.InputFilesCursor = Stream;
2344 if (Stream.SkipBlock() || // Skip with the main cursor
2345 // Read the abbreviations
2346 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2347 Error("malformed block record in AST file");
2348 return Failure;
2349 }
2350 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002351
2352 case OPTIONS_BLOCK_ID:
2353 // If we're reading the first module for this group, check its options
2354 // are compatible with ours. For modules it imports, no further checking
2355 // is required, because we checked them when we built it.
2356 if (Listener && !ImportedBy) {
2357 // Should we allow the configuration of the module file to differ from
2358 // the configuration of the current translation unit in a compatible
2359 // way?
2360 //
2361 // FIXME: Allow this for files explicitly specified with -include-pch.
2362 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002363 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002364
Richard Smith8a308ec2015-11-05 00:54:55 +00002365 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2366 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002367 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002368 if (Result == Failure) {
2369 Error("malformed block record in AST file");
2370 return Result;
2371 }
2372
Richard Smith8a308ec2015-11-05 00:54:55 +00002373 if (DisableValidation ||
2374 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2375 Result = Success;
2376
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002377 // If we can't load the module, exit early since we likely
2378 // will rebuild the module anyway. The stream may be in the
2379 // middle of a block.
2380 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002381 return Result;
2382 } else if (Stream.SkipBlock()) {
2383 Error("malformed block record in AST file");
2384 return Failure;
2385 }
2386 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002387
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 if (Stream.SkipBlock()) {
2390 Error("malformed block record in AST file");
2391 return Failure;
2392 }
2393 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002395
Chris Lattnere7b154b2013-01-19 21:39:22 +00002396 case llvm::BitstreamEntry::Record:
2397 // The interesting case.
2398 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 }
2400
2401 // Read and process a record.
2402 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002403 StringRef Blob;
2404 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case METADATA: {
2406 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2407 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002408 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2409 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return VersionMismatch;
2411 }
2412
Richard Smithe75ee0f2015-08-17 07:13:32 +00002413 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2415 Diag(diag::err_pch_with_compiler_errors);
2416 return HadErrors;
2417 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002418 if (hasErrors) {
2419 Diags.ErrorOccurred = true;
2420 Diags.UncompilableErrorOccurred = true;
2421 Diags.UnrecoverableErrorOccurred = true;
2422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002423
2424 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002425 // Relative paths in a relocatable PCH are relative to our sysroot.
2426 if (F.RelocatablePCH)
2427 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428
Richard Smithe75ee0f2015-08-17 07:13:32 +00002429 F.HasTimestamps = Record[5];
2430
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2434 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002435 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return VersionMismatch;
2437 }
2438 break;
2439 }
2440
2441 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002442 // Validate the AST before processing any imports (otherwise, untangling
2443 // them can be error-prone and expensive). A module will have a name and
2444 // will already have been validated, but this catches the PCH case.
2445 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2446 return Result;
2447
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002448 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 unsigned Idx = 0, N = Record.size();
2450 while (Idx < N) {
2451 // Read information about the AST file.
2452 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2453 // The import location will be the local one for now; we will adjust
2454 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002455 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002457 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002458 off_t StoredSize = (off_t)Record[Idx++];
2459 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002460 ASTFileSignature StoredSignature = {
2461 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2462 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2463 (uint32_t)Record[Idx++]}}};
Richard Smith7ed1bc92014-12-05 22:42:13 +00002464 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002465
Richard Smith0f99d6a2015-08-09 08:48:41 +00002466 // If our client can't cope with us being out of date, we can't cope with
2467 // our dependency being missing.
2468 unsigned Capabilities = ClientLoadCapabilities;
2469 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2470 Capabilities &= ~ARR_Missing;
2471
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002473 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2474 Loaded, StoredSize, StoredModTime,
2475 StoredSignature, Capabilities);
2476
2477 // If we diagnosed a problem, produce a backtrace.
2478 if (isDiagnosedResult(Result, Capabilities))
2479 Diag(diag::note_module_file_imported_by)
2480 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2481
2482 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 case Failure: return Failure;
2484 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002485 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 case OutOfDate: return OutOfDate;
2487 case VersionMismatch: return VersionMismatch;
2488 case ConfigurationMismatch: return ConfigurationMismatch;
2489 case HadErrors: return HadErrors;
2490 case Success: break;
2491 }
2492 }
2493 break;
2494 }
2495
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 case ORIGINAL_FILE:
2497 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002498 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002500 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 break;
2502
2503 case ORIGINAL_FILE_ID:
2504 F.OriginalSourceFileID = FileID::get(Record[0]);
2505 break;
2506
2507 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002508 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 break;
2510
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002511 case MODULE_NAME:
2512 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002513 if (Listener)
2514 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002515
2516 // Validate the AST as soon as we have a name so we can exit early on
2517 // failure.
2518 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2519 return Result;
2520
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002521 break;
2522
Richard Smith223d3f22014-12-06 03:21:08 +00002523 case MODULE_DIRECTORY: {
2524 assert(!F.ModuleName.empty() &&
2525 "MODULE_DIRECTORY found before MODULE_NAME");
2526 // If we've already loaded a module map file covering this module, we may
2527 // have a better path for it (relative to the current build).
2528 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2529 if (M && M->Directory) {
2530 // If we're implicitly loading a module, the base directory can't
2531 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002532 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002533 const DirectoryEntry *BuildDir =
2534 PP.getFileManager().getDirectory(Blob);
2535 if (!BuildDir || BuildDir != M->Directory) {
2536 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2537 Diag(diag::err_imported_module_relocated)
2538 << F.ModuleName << Blob << M->Directory->getName();
2539 return OutOfDate;
2540 }
2541 }
2542 F.BaseDirectory = M->Directory->getName();
2543 } else {
2544 F.BaseDirectory = Blob;
2545 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002546 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002547 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002548
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002549 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002550 if (ASTReadResult Result =
2551 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2552 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002553 break;
2554
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002555 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002556 NumInputs = Record[0];
2557 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002558 F.InputFileOffsets =
2559 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002560 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002561 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 break;
2563 }
2564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002565}
2566
Ben Langmuir2c9af442014-04-10 17:57:43 +00002567ASTReader::ASTReadResult
2568ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002569 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570
2571 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2572 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
2575
2576 // Read all of the records and blocks for the AST file.
2577 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002578 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002579 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002580
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581 switch (Entry.Kind) {
2582 case llvm::BitstreamEntry::Error:
2583 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002586 // Outside of C++, we do not store a lookup map for the translation unit.
2587 // Instead, mark it as needing a lookup map to be built if this module
2588 // contains any declarations lexically within it (which it always does!).
2589 // This usually has no cost, since we very rarely need the lookup map for
2590 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002592 if (DC->hasExternalLexicalStorage() &&
2593 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002595
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 case llvm::BitstreamEntry::SubBlock:
2599 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 case DECLTYPES_BLOCK_ID:
2601 // We lazily load the decls block, but we want to set up the
2602 // DeclsCursor cursor to point into it. Clone our current bitcode
2603 // cursor to it, enter the block and read the abbrevs in that block.
2604 // With the main cursor, we just skip over it.
2605 F.DeclsCursor = Stream;
2606 if (Stream.SkipBlock() || // Skip with the main cursor.
2607 // Read the abbrevs.
2608 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2609 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002613
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 case PREPROCESSOR_BLOCK_ID:
2615 F.MacroCursor = Stream;
2616 if (!PP.getExternalSource())
2617 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 if (Stream.SkipBlock() ||
2620 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2621 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
2624 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2625 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002626
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 case PREPROCESSOR_DETAIL_BLOCK_ID:
2628 F.PreprocessorDetailCursor = Stream;
2629 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002630 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002632 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002636 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 if (!PP.getPreprocessingRecord())
2639 PP.createPreprocessingRecord();
2640 if (!PP.getPreprocessingRecord()->getExternalSource())
2641 PP.getPreprocessingRecord()->SetExternalSource(*this);
2642 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 case SOURCE_MANAGER_BLOCK_ID:
2645 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002646 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002648
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002650 if (ASTReadResult Result =
2651 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002654
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002656 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 if (Stream.SkipBlock() ||
2658 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2659 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002660 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 }
2662 CommentsCursors.push_back(std::make_pair(C, &F));
2663 break;
2664 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002665
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002667 if (Stream.SkipBlock()) {
2668 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002669 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002670 }
2671 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 }
2673 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002674
Chris Lattnere7b154b2013-01-19 21:39:22 +00002675 case llvm::BitstreamEntry::Record:
2676 // The interesting case.
2677 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 }
2679
2680 // Read and process a record.
2681 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002682 StringRef Blob;
2683 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 default: // Default behavior: ignore.
2685 break;
2686
2687 case TYPE_OFFSET: {
2688 if (F.LocalNumTypes != 0) {
2689 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002690 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 F.LocalNumTypes = Record[0];
2694 unsigned LocalBaseTypeIndex = Record[1];
2695 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002696
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 if (F.LocalNumTypes > 0) {
2698 // Introduce the global -> local mapping for types within this module.
2699 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002700
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 // Introduce the local -> global mapping for types within this module.
2702 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002703 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002705
2706 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 }
2708 break;
2709 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 case DECL_OFFSET: {
2712 if (F.LocalNumDecls != 0) {
2713 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002714 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002716 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 F.LocalNumDecls = Record[0];
2718 unsigned LocalBaseDeclID = Record[1];
2719 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002720
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002722 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 // module.
2724 GlobalDeclMap.insert(
2725 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002726
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 // Introduce the local -> global mapping for declarations within this
2728 // module.
2729 F.DeclRemap.insertOrReplace(
2730 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 // Introduce the global -> local mapping for declarations within this
2733 // module.
2734 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002735
Ben Langmuir52ca6782014-10-20 16:27:32 +00002736 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2737 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 break;
2739 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 case TU_UPDATE_LEXICAL: {
2742 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002743 LexicalContents Contents(
2744 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2745 Blob.data()),
2746 static_cast<unsigned int>(Blob.size() / 4));
2747 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 TU->setHasExternalLexicalStorage(true);
2749 break;
2750 }
2751
2752 case UPDATE_VISIBLE: {
2753 unsigned Idx = 0;
2754 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002755 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002756 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002757 // If we've already loaded the decl, perform the updates when we finish
2758 // loading this block.
2759 if (Decl *D = GetExistingDecl(ID))
2760 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
2762 }
2763
2764 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002765 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002767 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2768 (const unsigned char *)F.IdentifierTableData + Record[0],
2769 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2770 (const unsigned char *)F.IdentifierTableData,
2771 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002772
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2774 }
2775 break;
2776
2777 case IDENTIFIER_OFFSET: {
2778 if (F.LocalNumIdentifiers != 0) {
2779 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002780 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002782 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 F.LocalNumIdentifiers = Record[0];
2784 unsigned LocalBaseIdentifierID = Record[1];
2785 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002786
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 if (F.LocalNumIdentifiers > 0) {
2788 // Introduce the global -> local mapping for identifiers within this
2789 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002790 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002792
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 // Introduce the local -> global mapping for identifiers within this
2794 // module.
2795 F.IdentifierRemap.insertOrReplace(
2796 std::make_pair(LocalBaseIdentifierID,
2797 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002798
Ben Langmuir52ca6782014-10-20 16:27:32 +00002799 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2800 + F.LocalNumIdentifiers);
2801 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 break;
2803 }
2804
Richard Smith33e0f7e2015-07-22 02:08:40 +00002805 case INTERESTING_IDENTIFIERS:
2806 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2807 break;
2808
Ben Langmuir332aafe2014-01-31 01:06:56 +00002809 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002810 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2811 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002813 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 break;
2815
David Blaikie9ffe5a32017-01-30 05:00:26 +00002816 case MODULAR_CODEGEN_DECLS:
2817 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2818 // them (ie: if we're not codegenerating this module).
2819 if (F.Kind == MK_MainFile)
2820 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2822 break;
2823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002825 if (SpecialTypes.empty()) {
2826 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2828 break;
2829 }
2830
2831 if (SpecialTypes.size() != Record.size()) {
2832 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002833 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002834 }
2835
2836 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2837 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2838 if (!SpecialTypes[I])
2839 SpecialTypes[I] = ID;
2840 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2841 // merge step?
2842 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 break;
2844
2845 case STATISTICS:
2846 TotalNumStatements += Record[0];
2847 TotalNumMacros += Record[1];
2848 TotalLexicalDeclContexts += Record[2];
2849 TotalVisibleDeclContexts += Record[3];
2850 break;
2851
2852 case UNUSED_FILESCOPED_DECLS:
2853 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2855 break;
2856
2857 case DELEGATING_CTORS:
2858 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2859 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2860 break;
2861
2862 case WEAK_UNDECLARED_IDENTIFIERS:
2863 if (Record.size() % 4 != 0) {
2864 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002865 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002867
2868 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 // files. This isn't the way to do it :)
2870 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 // Translate the weak, undeclared identifiers into global IDs.
2873 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2874 WeakUndeclaredIdentifiers.push_back(
2875 getGlobalIdentifierID(F, Record[I++]));
2876 WeakUndeclaredIdentifiers.push_back(
2877 getGlobalIdentifierID(F, Record[I++]));
2878 WeakUndeclaredIdentifiers.push_back(
2879 ReadSourceLocation(F, Record, I).getRawEncoding());
2880 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2881 }
2882 break;
2883
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002885 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 F.LocalNumSelectors = Record[0];
2887 unsigned LocalBaseSelectorID = Record[1];
2888 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002889
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002891 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 // module.
2893 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002894
2895 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 // module.
2897 F.SelectorRemap.insertOrReplace(
2898 std::make_pair(LocalBaseSelectorID,
2899 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002900
2901 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 }
2903 break;
2904 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002905
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002907 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 if (Record[0])
2909 F.SelectorLookupTable
2910 = ASTSelectorLookupTable::Create(
2911 F.SelectorLookupTableData + Record[0],
2912 F.SelectorLookupTableData,
2913 ASTSelectorLookupTrait(*this, F));
2914 TotalNumMethodPoolEntries += Record[1];
2915 break;
2916
2917 case REFERENCED_SELECTOR_POOL:
2918 if (!Record.empty()) {
2919 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002920 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 Record[Idx++]));
2922 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2923 getRawEncoding());
2924 }
2925 }
2926 break;
2927
2928 case PP_COUNTER_VALUE:
2929 if (!Record.empty() && Listener)
2930 Listener->ReadCounter(F, Record[0]);
2931 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002932
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 F.NumFileSortedDecls = Record[0];
2936 break;
2937
2938 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002939 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 F.LocalNumSLocEntries = Record[0];
2941 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002942 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002943 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002945 if (!F.SLocEntryBaseID) {
2946 Error("ran out of source locations");
2947 break;
2948 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Make our entry in the range map. BaseID is negative and growing, so
2950 // we invert it. Because we invert it, though, we need the other end of
2951 // the range.
2952 unsigned RangeStart =
2953 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2954 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2955 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2956
2957 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2958 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2959 GlobalSLocOffsetMap.insert(
2960 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2961 - SLocSpaceSize,&F));
2962
2963 // Initialize the remapping table.
2964 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002965 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002967 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002969
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 TotalNumSLocEntries += F.LocalNumSLocEntries;
2971 break;
2972 }
2973
Richard Smith37a93df2017-02-18 00:32:02 +00002974 case MODULE_OFFSET_MAP:
2975 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002977
2978 case SOURCE_MANAGER_LINE_TABLE:
2979 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 break;
2982
2983 case SOURCE_LOCATION_PRELOADS: {
2984 // Need to transform from the local view (1-based IDs) to the global view,
2985 // which is based off F.SLocEntryBaseID.
2986 if (!F.PreloadSLocEntries.empty()) {
2987 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002988 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002990
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 F.PreloadSLocEntries.swap(Record);
2992 break;
2993 }
2994
2995 case EXT_VECTOR_DECLS:
2996 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2997 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2998 break;
2999
3000 case VTABLE_USES:
3001 if (Record.size() % 3 != 0) {
3002 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003003 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003005
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 // Later tables overwrite earlier ones.
3007 // FIXME: Modules will have some trouble with this. This is clearly not
3008 // the right way to do this.
3009 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003010
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3012 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3013 VTableUses.push_back(
3014 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3015 VTableUses.push_back(Record[Idx++]);
3016 }
3017 break;
3018
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 case PENDING_IMPLICIT_INSTANTIATIONS:
3020 if (PendingInstantiations.size() % 2 != 0) {
3021 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 }
3024
3025 if (Record.size() % 2 != 0) {
3026 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029
3030 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3031 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3032 PendingInstantiations.push_back(
3033 ReadSourceLocation(F, Record, I).getRawEncoding());
3034 }
3035 break;
3036
3037 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003038 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003039 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003040 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3043 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3044 break;
3045
3046 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003047 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3048 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3049 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003050
3051 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 unsigned StartingID;
3054 if (!PP.getPreprocessingRecord())
3055 PP.createPreprocessingRecord();
3056 if (!PP.getPreprocessingRecord()->getExternalSource())
3057 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003058 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003060 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 F.BasePreprocessedEntityID = StartingID;
3062
3063 if (F.NumPreprocessedEntities > 0) {
3064 // Introduce the global -> local mapping for preprocessed entities in
3065 // this module.
3066 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003067
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 // Introduce the local -> global mapping for preprocessed entities in
3069 // this module.
3070 F.PreprocessedEntityRemap.insertOrReplace(
3071 std::make_pair(LocalBasePreprocessedEntityID,
3072 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3073 }
3074
3075 break;
3076 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003077
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 case DECL_UPDATE_OFFSETS: {
3079 if (Record.size() % 2 != 0) {
3080 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003081 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003083 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3084 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3085 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3086
3087 // If we've already loaded the decl, perform the updates when we finish
3088 // loading this block.
3089 if (Decl *D = GetExistingDecl(ID))
3090 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 break;
3093 }
3094
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 case OBJC_CATEGORIES_MAP: {
3096 if (F.LocalNumObjCCategoriesInMap != 0) {
3097 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003098 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003102 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 break;
3104 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 case OBJC_CATEGORIES:
3107 F.ObjCCategories.swap(Record);
3108 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 case CUDA_SPECIAL_DECL_REFS:
3111 // Later tables overwrite earlier ones.
3112 // FIXME: Modules will have trouble with this.
3113 CUDASpecialDeclRefs.clear();
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3116 break;
3117
3118 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003119 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 if (Record[0]) {
3122 F.HeaderFileInfoTable
3123 = HeaderFileInfoLookupTable::Create(
3124 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3125 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003126 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003128 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003129
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 PP.getHeaderSearchInfo().SetExternalSource(this);
3131 if (!PP.getHeaderSearchInfo().getExternalLookup())
3132 PP.getHeaderSearchInfo().SetExternalLookup(this);
3133 }
3134 break;
3135 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 case FP_PRAGMA_OPTIONS:
3138 // Later tables overwrite earlier ones.
3139 FPPragmaOptions.swap(Record);
3140 break;
3141
3142 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003143 for (unsigned I = 0, E = Record.size(); I != E; ) {
3144 auto Name = ReadString(Record, I);
3145 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003146 Opt.Supported = Record[I++] != 0;
3147 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003148 Opt.Avail = Record[I++];
3149 Opt.Core = Record[I++];
3150 }
3151 break;
3152
3153 case OPENCL_EXTENSION_TYPES:
3154 for (unsigned I = 0, E = Record.size(); I != E;) {
3155 auto TypeID = static_cast<::TypeID>(Record[I++]);
3156 auto *Type = GetType(TypeID).getTypePtr();
3157 auto NumExt = static_cast<unsigned>(Record[I++]);
3158 for (unsigned II = 0; II != NumExt; ++II) {
3159 auto Ext = ReadString(Record, I);
3160 OpenCLTypeExtMap[Type].insert(Ext);
3161 }
3162 }
3163 break;
3164
3165 case OPENCL_EXTENSION_DECLS:
3166 for (unsigned I = 0, E = Record.size(); I != E;) {
3167 auto DeclID = static_cast<::DeclID>(Record[I++]);
3168 auto *Decl = GetDecl(DeclID);
3169 auto NumExt = static_cast<unsigned>(Record[I++]);
3170 for (unsigned II = 0; II != NumExt; ++II) {
3171 auto Ext = ReadString(Record, I);
3172 OpenCLDeclExtMap[Decl].insert(Ext);
3173 }
3174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003175 break;
3176
3177 case TENTATIVE_DEFINITIONS:
3178 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3179 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3180 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 case KNOWN_NAMESPACES:
3183 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3184 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3185 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003186
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003187 case UNDEFINED_BUT_USED:
3188 if (UndefinedButUsed.size() % 2 != 0) {
3189 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003190 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003191 }
3192
3193 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003194 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003195 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003196 }
3197 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003198 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3199 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003200 ReadSourceLocation(F, Record, I).getRawEncoding());
3201 }
3202 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003203 case DELETE_EXPRS_TO_ANALYZE:
3204 for (unsigned I = 0, N = Record.size(); I != N;) {
3205 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3206 const uint64_t Count = Record[I++];
3207 DelayedDeleteExprs.push_back(Count);
3208 for (uint64_t C = 0; C < Count; ++C) {
3209 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3210 bool IsArrayForm = Record[I++] == 1;
3211 DelayedDeleteExprs.push_back(IsArrayForm);
3212 }
3213 }
3214 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003215
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003217 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 // If we aren't loading a module (which has its own exports), make
3219 // all of the imported modules visible.
3220 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003221 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3222 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3223 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003224 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003225 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003226 if (DeserializationListener)
3227 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3228 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 }
3230 }
3231 break;
3232 }
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 case MACRO_OFFSET: {
3235 if (F.LocalNumMacros != 0) {
3236 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003237 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003239 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 F.LocalNumMacros = Record[0];
3241 unsigned LocalBaseMacroID = Record[1];
3242 F.BaseMacroID = getTotalNumMacros();
3243
3244 if (F.LocalNumMacros > 0) {
3245 // Introduce the global -> local mapping for macros within this module.
3246 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3247
3248 // Introduce the local -> global mapping for macros within this module.
3249 F.MacroRemap.insertOrReplace(
3250 std::make_pair(LocalBaseMacroID,
3251 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003252
3253 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 }
3255 break;
3256 }
3257
Richard Smithe40f2ba2013-08-07 21:41:30 +00003258 case LATE_PARSED_TEMPLATE: {
3259 LateParsedTemplates.append(Record.begin(), Record.end());
3260 break;
3261 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003262
3263 case OPTIMIZE_PRAGMA_OPTIONS:
3264 if (Record.size() != 1) {
3265 Error("invalid pragma optimize record");
3266 return Failure;
3267 }
3268 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3269 break;
Nico Weber72889432014-09-06 01:25:55 +00003270
Nico Weber779355f2016-03-02 23:22:00 +00003271 case MSSTRUCT_PRAGMA_OPTIONS:
3272 if (Record.size() != 1) {
3273 Error("invalid pragma ms_struct record");
3274 return Failure;
3275 }
3276 PragmaMSStructState = Record[0];
3277 break;
3278
Nico Weber42932312016-03-03 00:17:35 +00003279 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3280 if (Record.size() != 2) {
3281 Error("invalid pragma ms_struct record");
3282 return Failure;
3283 }
3284 PragmaMSPointersToMembersState = Record[0];
3285 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3286 break;
3287
Nico Weber72889432014-09-06 01:25:55 +00003288 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3289 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3290 UnusedLocalTypedefNameCandidates.push_back(
3291 getGlobalDeclID(F, Record[I]));
3292 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003293
3294 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3295 if (Record.size() != 1) {
3296 Error("invalid cuda pragma options record");
3297 return Failure;
3298 }
3299 ForceCUDAHostDeviceDepth = Record[0];
3300 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 }
3302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003303}
3304
Richard Smith37a93df2017-02-18 00:32:02 +00003305void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3306 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3307
3308 // Additional remapping information.
3309 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3310 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3311 F.ModuleOffsetMap = StringRef();
3312
3313 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3314 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3315 F.SLocRemap.insert(std::make_pair(0U, 0));
3316 F.SLocRemap.insert(std::make_pair(2U, 1));
3317 }
3318
3319 // Continuous range maps we may be updating in our module.
3320 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3321 RemapBuilder;
3322 RemapBuilder SLocRemap(F.SLocRemap);
3323 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3324 RemapBuilder MacroRemap(F.MacroRemap);
3325 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3326 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3327 RemapBuilder SelectorRemap(F.SelectorRemap);
3328 RemapBuilder DeclRemap(F.DeclRemap);
3329 RemapBuilder TypeRemap(F.TypeRemap);
3330
3331 while (Data < DataEnd) {
3332 // FIXME: Looking up dependency modules by filename is horrible.
3333 using namespace llvm::support;
3334 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3335 StringRef Name = StringRef((const char*)Data, Len);
3336 Data += Len;
3337 ModuleFile *OM = ModuleMgr.lookup(Name);
3338 if (!OM) {
3339 std::string Msg =
3340 "SourceLocation remap refers to unknown module, cannot find ";
3341 Msg.append(Name);
3342 Error(Msg);
3343 return;
3344 }
3345
3346 uint32_t SLocOffset =
3347 endian::readNext<uint32_t, little, unaligned>(Data);
3348 uint32_t IdentifierIDOffset =
3349 endian::readNext<uint32_t, little, unaligned>(Data);
3350 uint32_t MacroIDOffset =
3351 endian::readNext<uint32_t, little, unaligned>(Data);
3352 uint32_t PreprocessedEntityIDOffset =
3353 endian::readNext<uint32_t, little, unaligned>(Data);
3354 uint32_t SubmoduleIDOffset =
3355 endian::readNext<uint32_t, little, unaligned>(Data);
3356 uint32_t SelectorIDOffset =
3357 endian::readNext<uint32_t, little, unaligned>(Data);
3358 uint32_t DeclIDOffset =
3359 endian::readNext<uint32_t, little, unaligned>(Data);
3360 uint32_t TypeIndexOffset =
3361 endian::readNext<uint32_t, little, unaligned>(Data);
3362
3363 uint32_t None = std::numeric_limits<uint32_t>::max();
3364
3365 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3366 RemapBuilder &Remap) {
3367 if (Offset != None)
3368 Remap.insert(std::make_pair(Offset,
3369 static_cast<int>(BaseOffset - Offset)));
3370 };
3371 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3372 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3373 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3374 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3375 PreprocessedEntityRemap);
3376 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3377 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3378 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3379 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3380
3381 // Global -> local mappings.
3382 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3383 }
3384}
3385
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003386ASTReader::ASTReadResult
3387ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3388 const ModuleFile *ImportedBy,
3389 unsigned ClientLoadCapabilities) {
3390 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003391 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003392
Manman Ren11f2a472016-08-18 17:42:15 +00003393 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003394 // For an explicitly-loaded module, we don't care whether the original
3395 // module map file exists or matches.
3396 return Success;
3397 }
3398
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003399 // Try to resolve ModuleName in the current header search context and
3400 // verify that it is found in the same module map file as we saved. If the
3401 // top-level AST file is a main file, skip this check because there is no
3402 // usable header search context.
3403 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003404 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003405 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003406 // An implicitly-loaded module file should have its module listed in some
3407 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003409 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3410 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3411 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003412 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003413 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3414 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3415 // This module was defined by an imported (explicit) module.
3416 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3417 << ASTFE->getName();
3418 else
3419 // This module was built with a different module map.
3420 Diag(diag::err_imported_module_not_found)
3421 << F.ModuleName << F.FileName << ImportedBy->FileName
3422 << F.ModuleMapPath;
3423 }
3424 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003425 }
3426
Richard Smithe842a472014-10-22 02:05:46 +00003427 assert(M->Name == F.ModuleName && "found module with different name");
3428
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003429 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003430 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003431 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3432 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003433 assert(ImportedBy && "top-level import should be verified");
3434 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3435 Diag(diag::err_imported_module_modmap_changed)
3436 << F.ModuleName << ImportedBy->FileName
3437 << ModMap->getName() << F.ModuleMapPath;
3438 return OutOfDate;
3439 }
3440
3441 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3442 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3443 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003444 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003445 const FileEntry *F =
3446 FileMgr.getFile(Filename, false, false);
3447 if (F == nullptr) {
3448 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3449 Error("could not find file '" + Filename +"' referenced by AST file");
3450 return OutOfDate;
3451 }
3452 AdditionalStoredMaps.insert(F);
3453 }
3454
3455 // Check any additional module map files (e.g. module.private.modulemap)
3456 // that are not in the pcm.
3457 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3458 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3459 // Remove files that match
3460 // Note: SmallPtrSet::erase is really remove
3461 if (!AdditionalStoredMaps.erase(ModMap)) {
3462 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3463 Diag(diag::err_module_different_modmap)
3464 << F.ModuleName << /*new*/0 << ModMap->getName();
3465 return OutOfDate;
3466 }
3467 }
3468 }
3469
3470 // Check any additional module map files that are in the pcm, but not
3471 // found in header search. Cases that match are already removed.
3472 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3473 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3474 Diag(diag::err_module_different_modmap)
3475 << F.ModuleName << /*not new*/1 << ModMap->getName();
3476 return OutOfDate;
3477 }
3478 }
3479
3480 if (Listener)
3481 Listener->ReadModuleMapFile(F.ModuleMapPath);
3482 return Success;
3483}
3484
3485
Douglas Gregorc1489562013-02-12 23:36:21 +00003486/// \brief Move the given method to the back of the global list of methods.
3487static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3488 // Find the entry for this selector in the method pool.
3489 Sema::GlobalMethodPool::iterator Known
3490 = S.MethodPool.find(Method->getSelector());
3491 if (Known == S.MethodPool.end())
3492 return;
3493
3494 // Retrieve the appropriate method list.
3495 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3496 : Known->second.second;
3497 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003498 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003499 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003500 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003501 Found = true;
3502 } else {
3503 // Keep searching.
3504 continue;
3505 }
3506 }
3507
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003508 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003509 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003510 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003511 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003512 }
3513}
3514
Richard Smithde711422015-04-23 21:20:19 +00003515void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003516 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003517 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003518 bool wasHidden = D->Hidden;
3519 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003520
Richard Smith49f906a2014-03-01 00:08:04 +00003521 if (wasHidden && SemaObj) {
3522 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3523 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003524 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 }
3526 }
3527}
3528
Richard Smith49f906a2014-03-01 00:08:04 +00003529void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003530 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003531 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003533 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003534 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003536 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003537
3538 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003539 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 // there is nothing more to do.
3541 continue;
3542 }
Richard Smith49f906a2014-03-01 00:08:04 +00003543
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 if (!Mod->isAvailable()) {
3545 // Modules that aren't available cannot be made visible.
3546 continue;
3547 }
3548
3549 // Update the module's name visibility.
3550 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003551
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 // If we've already deserialized any names from this module,
3553 // mark them as visible.
3554 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3555 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003556 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003558 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003559 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3560 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003562
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003564 SmallVector<Module *, 16> Exports;
3565 Mod->getExportedModules(Exports);
3566 for (SmallVectorImpl<Module *>::iterator
3567 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3568 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003569 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003570 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003571 }
3572 }
3573}
3574
Richard Smith6561f922016-09-12 21:06:40 +00003575/// We've merged the definition \p MergedDef into the existing definition
3576/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3577/// visible.
3578void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3579 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003580 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3581 // in modules other than its owning module. We should instead give the
3582 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003583 if (Def->isHidden()) {
3584 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003585 if (!MergedDef->isHidden())
3586 Def->Hidden = false;
3587 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3588 getContext().mergeDefinitionIntoModule(
3589 Def, MergedDef->getImportedOwningModule(),
3590 /*NotifyListeners*/ false);
3591 PendingMergedDefinitionsToDeduplicate.insert(Def);
3592 } else {
3593 auto SubmoduleID = MergedDef->getOwningModuleID();
3594 assert(SubmoduleID && "hidden definition in no module");
3595 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3596 }
Richard Smith6561f922016-09-12 21:06:40 +00003597 }
3598}
3599
Douglas Gregore060e572013-01-25 01:03:03 +00003600bool ASTReader::loadGlobalIndex() {
3601 if (GlobalIndex)
3602 return false;
3603
3604 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3605 !Context.getLangOpts().Modules)
3606 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003607
Douglas Gregore060e572013-01-25 01:03:03 +00003608 // Try to load the global index.
3609 TriedLoadingGlobalIndex = true;
3610 StringRef ModuleCachePath
3611 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3612 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003613 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003614 if (!Result.first)
3615 return true;
3616
3617 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003618 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003619 return false;
3620}
3621
3622bool ASTReader::isGlobalIndexUnavailable() const {
3623 return Context.getLangOpts().Modules && UseGlobalIndex &&
3624 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3625}
3626
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003627static void updateModuleTimestamp(ModuleFile &MF) {
3628 // Overwrite the timestamp file contents so that file's mtime changes.
3629 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003630 std::error_code EC;
3631 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3632 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003633 return;
3634 OS << "Timestamp file\n";
3635}
3636
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003637/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3638/// cursor into the start of the given block ID, returning false on success and
3639/// true on failure.
3640static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003641 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003642 llvm::BitstreamEntry Entry = Cursor.advance();
3643 switch (Entry.Kind) {
3644 case llvm::BitstreamEntry::Error:
3645 case llvm::BitstreamEntry::EndBlock:
3646 return true;
3647
3648 case llvm::BitstreamEntry::Record:
3649 // Ignore top-level records.
3650 Cursor.skipRecord(Entry.ID);
3651 break;
3652
3653 case llvm::BitstreamEntry::SubBlock:
3654 if (Entry.ID == BlockID) {
3655 if (Cursor.EnterSubBlock(BlockID))
3656 return true;
3657 // Found it!
3658 return false;
3659 }
3660
3661 if (Cursor.SkipBlock())
3662 return true;
3663 }
3664 }
3665}
3666
Benjamin Kramer0772c422016-02-13 13:42:54 +00003667ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 ModuleKind Type,
3669 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003670 unsigned ClientLoadCapabilities,
3671 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003672 llvm::SaveAndRestore<SourceLocation>
3673 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3674
Richard Smithd1c46742014-04-30 02:24:17 +00003675 // Defer any pending actions until we get to the end of reading the AST file.
3676 Deserializing AnASTFile(this);
3677
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003679 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003680
3681 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003682 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003683 switch (ASTReadResult ReadResult =
3684 ReadASTCore(FileName, Type, ImportLoc,
3685 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3686 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003687 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003688 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 case OutOfDate:
3690 case VersionMismatch:
3691 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003692 case HadErrors: {
3693 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3694 for (const ImportedModule &IM : Loaded)
3695 LoadedSet.insert(IM.Mod);
3696
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003697 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003698 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003699 ? &PP.getHeaderSearchInfo().getModuleMap()
3700 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003701
3702 // If we find that any modules are unusable, the global index is going
3703 // to be out-of-date. Just remove it.
3704 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003705 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003707 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 case Success:
3709 break;
3710 }
3711
3712 // Here comes stuff that we only do once the entire chain is loaded.
3713
3714 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003715 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3716 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 M != MEnd; ++M) {
3718 ModuleFile &F = *M->Mod;
3719
3720 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003721 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3722 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003723
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003724 // Read the extension blocks.
3725 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3726 if (ASTReadResult Result = ReadExtensionBlock(F))
3727 return Result;
3728 }
3729
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003730 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 // bits of all files we've seen.
3732 F.GlobalBitOffset = TotalModulesSizeInBits;
3733 TotalModulesSizeInBits += F.SizeInBits;
3734 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003735
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 // Preload SLocEntries.
3737 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3738 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3739 // Load it through the SourceManager and don't call ReadSLocEntry()
3740 // directly because the entry may have already been loaded in which case
3741 // calling ReadSLocEntry() directly would trigger an assertion in
3742 // SourceManager.
3743 SourceMgr.getLoadedSLocEntryByID(Index);
3744 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003745
3746 // Preload all the pending interesting identifiers by marking them out of
3747 // date.
3748 for (auto Offset : F.PreloadIdentifierOffsets) {
3749 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3750 F.IdentifierTableData + Offset);
3751
3752 ASTIdentifierLookupTrait Trait(*this, F);
3753 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3754 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003755 auto &II = PP.getIdentifierTable().getOwn(Key);
3756 II.setOutOfDate(true);
3757
3758 // Mark this identifier as being from an AST file so that we can track
3759 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003760 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003761
3762 // Associate the ID with the identifier so that the writer can reuse it.
3763 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3764 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003765 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 }
3767
Douglas Gregor603cd862013-03-22 18:50:14 +00003768 // Setup the import locations and notify the module manager that we've
3769 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003770 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3771 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 M != MEnd; ++M) {
3773 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003774
3775 ModuleMgr.moduleFileAccepted(&F);
3776
3777 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003778 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003779 // FIXME: We assume that locations from PCH / preamble do not need
3780 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 if (!M->ImportedBy)
3782 F.ImportLoc = M->ImportLoc;
3783 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003784 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 }
3786
Richard Smith33e0f7e2015-07-22 02:08:40 +00003787 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003788 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3789 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003790 // Mark all of the identifiers in the identifier table as being out of date,
3791 // so that various accessors know to check the loaded modules when the
3792 // identifier is used.
3793 //
3794 // For C++ modules, we don't need information on many identifiers (just
3795 // those that provide macros or are poisoned), so we mark all of
3796 // the interesting ones via PreloadIdentifierOffsets.
3797 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3798 IdEnd = PP.getIdentifierTable().end();
3799 Id != IdEnd; ++Id)
3800 Id->second->setOutOfDate(true);
3801 }
Manman Rena0f31a02016-04-29 19:04:05 +00003802 // Mark selectors as out of date.
3803 for (auto Sel : SelectorGeneration)
3804 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003805
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003807 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3808 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3810 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003811
3812 switch (Unresolved.Kind) {
3813 case UnresolvedModuleRef::Conflict:
3814 if (ResolvedMod) {
3815 Module::Conflict Conflict;
3816 Conflict.Other = ResolvedMod;
3817 Conflict.Message = Unresolved.String.str();
3818 Unresolved.Mod->Conflicts.push_back(Conflict);
3819 }
3820 continue;
3821
3822 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003823 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003824 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003826
Douglas Gregorfb912652013-03-20 21:10:35 +00003827 case UnresolvedModuleRef::Export:
3828 if (ResolvedMod || Unresolved.IsWildcard)
3829 Unresolved.Mod->Exports.push_back(
3830 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3831 continue;
3832 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003834 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003835
Graydon Hoaree7196af2016-12-09 21:45:49 +00003836 if (Imported)
3837 Imported->append(ImportedModules.begin(),
3838 ImportedModules.end());
3839
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003840 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3841 // Might be unnecessary as use declarations are only used to build the
3842 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003843
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 InitializeContext();
3845
Richard Smith3d8e97e2013-10-18 06:54:39 +00003846 if (SemaObj)
3847 UpdateSema();
3848
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 if (DeserializationListener)
3850 DeserializationListener->ReaderInitialized(this);
3851
3852 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003853 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003854 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 = FileID::get(PrimaryModule.SLocEntryBaseID
3856 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3857
3858 // If this AST file is a precompiled preamble, then set the
3859 // preamble file ID of the source manager to the file source file
3860 // from which the preamble was built.
3861 if (Type == MK_Preamble) {
3862 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3863 } else if (Type == MK_MainFile) {
3864 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3865 }
3866 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003867
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 // For any Objective-C class definitions we have already loaded, make sure
3869 // that we load any additional categories.
3870 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003871 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 ObjCClassesLoaded[I],
3873 PreviousGeneration);
3874 }
Douglas Gregore060e572013-01-25 01:03:03 +00003875
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003876 if (PP.getHeaderSearchInfo()
3877 .getHeaderSearchOpts()
3878 .ModulesValidateOncePerBuildSession) {
3879 // Now we are certain that the module and all modules it depends on are
3880 // up to date. Create or update timestamp files for modules that are
3881 // located in the module cache (not for PCH files that could be anywhere
3882 // in the filesystem).
3883 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3884 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003885 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003886 updateModuleTimestamp(*M.Mod);
3887 }
3888 }
3889 }
3890
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 return Success;
3892}
3893
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003894static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003895
Ben Langmuir70a1b812015-03-24 04:43:52 +00003896/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3897static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003898 return Stream.canSkipToPos(4) &&
3899 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003900 Stream.Read(8) == 'P' &&
3901 Stream.Read(8) == 'C' &&
3902 Stream.Read(8) == 'H';
3903}
3904
Richard Smith0f99d6a2015-08-09 08:48:41 +00003905static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3906 switch (Kind) {
3907 case MK_PCH:
3908 return 0; // PCH
3909 case MK_ImplicitModule:
3910 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003911 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003912 return 1; // module
3913 case MK_MainFile:
3914 case MK_Preamble:
3915 return 2; // main source file
3916 }
3917 llvm_unreachable("unknown module kind");
3918}
3919
Guy Benyei11169dd2012-12-18 14:30:41 +00003920ASTReader::ASTReadResult
3921ASTReader::ReadASTCore(StringRef FileName,
3922 ModuleKind Type,
3923 SourceLocation ImportLoc,
3924 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003925 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003926 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003927 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 unsigned ClientLoadCapabilities) {
3929 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003931 ModuleManager::AddModuleResult AddResult
3932 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003933 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003934 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003935 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003936
Douglas Gregor7029ce12013-03-19 00:28:20 +00003937 switch (AddResult) {
3938 case ModuleManager::AlreadyLoaded:
3939 return Success;
3940
3941 case ModuleManager::NewlyLoaded:
3942 // Load module file below.
3943 break;
3944
3945 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003946 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003947 // it.
3948 if (ClientLoadCapabilities & ARR_Missing)
3949 return Missing;
3950
3951 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003952 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003953 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003954 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003955 return Failure;
3956
3957 case ModuleManager::OutOfDate:
3958 // We couldn't load the module file because it is out-of-date. If the
3959 // client can handle out-of-date, return it.
3960 if (ClientLoadCapabilities & ARR_OutOfDate)
3961 return OutOfDate;
3962
3963 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003964 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003965 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003966 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 return Failure;
3968 }
3969
Douglas Gregor7029ce12013-03-19 00:28:20 +00003970 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003971
3972 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3973 // module?
3974 if (FileName != "-") {
3975 CurrentDir = llvm::sys::path::parent_path(FileName);
3976 if (CurrentDir.empty()) CurrentDir = ".";
3977 }
3978
3979 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003980 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003981 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003982 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003983
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003985 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003986 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3987 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 return Failure;
3989 }
3990
3991 // This is used for compatibility with older PCH formats.
3992 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003993 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003994 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003995
Chris Lattnerefa77172013-01-20 00:00:22 +00003996 switch (Entry.Kind) {
3997 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003998 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003999 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 Error("invalid record at top-level of AST file");
4001 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004002
Chris Lattnerefa77172013-01-20 00:00:22 +00004003 case llvm::BitstreamEntry::SubBlock:
4004 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 }
4006
Chris Lattnerefa77172013-01-20 00:00:22 +00004007 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 case CONTROL_BLOCK_ID:
4009 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004010 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004012 // Check that we didn't try to load a non-module AST file as a module.
4013 //
4014 // FIXME: Should we also perform the converse check? Loading a module as
4015 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004016 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4017 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004018 F.ModuleName.empty()) {
4019 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4020 if (Result != OutOfDate ||
4021 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4022 Diag(diag::err_module_file_not_module) << FileName;
4023 return Result;
4024 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 break;
4026
4027 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004028 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 case OutOfDate: return OutOfDate;
4030 case VersionMismatch: return VersionMismatch;
4031 case ConfigurationMismatch: return ConfigurationMismatch;
4032 case HadErrors: return HadErrors;
4033 }
4034 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004035
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 case AST_BLOCK_ID:
4037 if (!HaveReadControlBlock) {
4038 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004039 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 return VersionMismatch;
4041 }
4042
4043 // Record that we've loaded this module.
4044 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4045 return Success;
4046
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004047 case UNHASHED_CONTROL_BLOCK_ID:
4048 // This block is handled using look-ahead during ReadControlBlock. We
4049 // shouldn't get here!
4050 Error("malformed block record in AST file");
4051 return Failure;
4052
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 default:
4054 if (Stream.SkipBlock()) {
4055 Error("malformed block record in AST file");
4056 return Failure;
4057 }
4058 break;
4059 }
4060 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004061
4062 return Success;
4063}
4064
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004065ASTReader::ASTReadResult
4066ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4067 unsigned ClientLoadCapabilities) {
4068 const HeaderSearchOptions &HSOpts =
4069 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4070 bool AllowCompatibleConfigurationMismatch =
4071 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4072
4073 ASTReadResult Result = readUnhashedControlBlockImpl(
4074 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4075 Listener.get(),
4076 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4077
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004078 // If F was directly imported by another module, it's implicitly validated by
4079 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004080 if (DisableValidation || WasImportedBy ||
4081 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4082 return Success;
4083
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004084 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004085 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004086 return Failure;
4087 }
4088
4089 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4090 // If this module has already been finalized in the PCMCache, we're stuck
4091 // with it; we can only load a single version of each module.
4092 //
4093 // This can happen when a module is imported in two contexts: in one, as a
4094 // user module; in another, as a system module (due to an import from
4095 // another module marked with the [system] flag). It usually indicates a
4096 // bug in the module map: this module should also be marked with [system].
4097 //
4098 // If -Wno-system-headers (the default), and the first import is as a
4099 // system module, then validation will fail during the as-user import,
4100 // since -Werror flags won't have been validated. However, it's reasonable
4101 // to treat this consistently as a system module.
4102 //
4103 // If -Wsystem-headers, the PCM on disk was built with
4104 // -Wno-system-headers, and the first import is as a user module, then
4105 // validation will fail during the as-system import since the PCM on disk
4106 // doesn't guarantee that -Werror was respected. However, the -Werror
4107 // flags were checked during the initial as-user import.
4108 if (PCMCache.isBufferFinal(F.FileName)) {
4109 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4110 return Success;
4111 }
4112 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004113
4114 return Result;
4115}
4116
4117ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4118 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4119 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4120 bool ValidateDiagnosticOptions) {
4121 // Initialize a stream.
4122 BitstreamCursor Stream(StreamData);
4123
4124 // Sniff for the signature.
4125 if (!startsWithASTFileMagic(Stream))
4126 return Failure;
4127
4128 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4129 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4130 return Failure;
4131
4132 // Read all of the records in the options block.
4133 RecordData Record;
4134 ASTReadResult Result = Success;
4135 while (1) {
4136 llvm::BitstreamEntry Entry = Stream.advance();
4137
4138 switch (Entry.Kind) {
4139 case llvm::BitstreamEntry::Error:
4140 case llvm::BitstreamEntry::SubBlock:
4141 return Failure;
4142
4143 case llvm::BitstreamEntry::EndBlock:
4144 return Result;
4145
4146 case llvm::BitstreamEntry::Record:
4147 // The interesting case.
4148 break;
4149 }
4150
4151 // Read and process a record.
4152 Record.clear();
4153 switch (
4154 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4155 case SIGNATURE: {
4156 if (F)
4157 std::copy(Record.begin(), Record.end(), F->Signature.data());
4158 break;
4159 }
4160 case DIAGNOSTIC_OPTIONS: {
4161 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4162 if (Listener && ValidateDiagnosticOptions &&
4163 !AllowCompatibleConfigurationMismatch &&
4164 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004165 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004166 break;
4167 }
4168 case DIAG_PRAGMA_MAPPINGS:
4169 if (!F)
4170 break;
4171 if (F->PragmaDiagMappings.empty())
4172 F->PragmaDiagMappings.swap(Record);
4173 else
4174 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4175 Record.begin(), Record.end());
4176 break;
4177 }
4178 }
4179}
4180
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004181/// Parse a record and blob containing module file extension metadata.
4182static bool parseModuleFileExtensionMetadata(
4183 const SmallVectorImpl<uint64_t> &Record,
4184 StringRef Blob,
4185 ModuleFileExtensionMetadata &Metadata) {
4186 if (Record.size() < 4) return true;
4187
4188 Metadata.MajorVersion = Record[0];
4189 Metadata.MinorVersion = Record[1];
4190
4191 unsigned BlockNameLen = Record[2];
4192 unsigned UserInfoLen = Record[3];
4193
4194 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4195
4196 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4197 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4198 Blob.data() + BlockNameLen + UserInfoLen);
4199 return false;
4200}
4201
4202ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4203 BitstreamCursor &Stream = F.Stream;
4204
4205 RecordData Record;
4206 while (true) {
4207 llvm::BitstreamEntry Entry = Stream.advance();
4208 switch (Entry.Kind) {
4209 case llvm::BitstreamEntry::SubBlock:
4210 if (Stream.SkipBlock())
4211 return Failure;
4212
4213 continue;
4214
4215 case llvm::BitstreamEntry::EndBlock:
4216 return Success;
4217
4218 case llvm::BitstreamEntry::Error:
4219 return HadErrors;
4220
4221 case llvm::BitstreamEntry::Record:
4222 break;
4223 }
4224
4225 Record.clear();
4226 StringRef Blob;
4227 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4228 switch (RecCode) {
4229 case EXTENSION_METADATA: {
4230 ModuleFileExtensionMetadata Metadata;
4231 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4232 return Failure;
4233
4234 // Find a module file extension with this block name.
4235 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4236 if (Known == ModuleFileExtensions.end()) break;
4237
4238 // Form a reader.
4239 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4240 F, Stream)) {
4241 F.ExtensionReaders.push_back(std::move(Reader));
4242 }
4243
4244 break;
4245 }
4246 }
4247 }
4248
4249 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004250}
4251
Richard Smitha7e2cc62015-05-01 01:53:09 +00004252void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 // If there's a listener, notify them that we "read" the translation unit.
4254 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004255 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 Context.getTranslationUnitDecl());
4257
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 // FIXME: Find a better way to deal with collisions between these
4259 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004260
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 // Load the special types.
4262 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4263 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4264 if (!Context.CFConstantStringTypeDecl)
4265 Context.setCFConstantStringType(GetType(String));
4266 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4269 QualType FileType = GetType(File);
4270 if (FileType.isNull()) {
4271 Error("FILE type is NULL");
4272 return;
4273 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004274
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 if (!Context.FILEDecl) {
4276 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4277 Context.setFILEDecl(Typedef->getDecl());
4278 else {
4279 const TagType *Tag = FileType->getAs<TagType>();
4280 if (!Tag) {
4281 Error("Invalid FILE type in AST file");
4282 return;
4283 }
4284 Context.setFILEDecl(Tag->getDecl());
4285 }
4286 }
4287 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004288
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4290 QualType Jmp_bufType = GetType(Jmp_buf);
4291 if (Jmp_bufType.isNull()) {
4292 Error("jmp_buf type is NULL");
4293 return;
4294 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004295
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 if (!Context.jmp_bufDecl) {
4297 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4298 Context.setjmp_bufDecl(Typedef->getDecl());
4299 else {
4300 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4301 if (!Tag) {
4302 Error("Invalid jmp_buf type in AST file");
4303 return;
4304 }
4305 Context.setjmp_bufDecl(Tag->getDecl());
4306 }
4307 }
4308 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004309
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4311 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4312 if (Sigjmp_bufType.isNull()) {
4313 Error("sigjmp_buf type is NULL");
4314 return;
4315 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004316
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 if (!Context.sigjmp_bufDecl) {
4318 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4319 Context.setsigjmp_bufDecl(Typedef->getDecl());
4320 else {
4321 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4322 assert(Tag && "Invalid sigjmp_buf type in AST file");
4323 Context.setsigjmp_bufDecl(Tag->getDecl());
4324 }
4325 }
4326 }
4327
4328 if (unsigned ObjCIdRedef
4329 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4330 if (Context.ObjCIdRedefinitionType.isNull())
4331 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4332 }
4333
4334 if (unsigned ObjCClassRedef
4335 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4336 if (Context.ObjCClassRedefinitionType.isNull())
4337 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4338 }
4339
4340 if (unsigned ObjCSelRedef
4341 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4342 if (Context.ObjCSelRedefinitionType.isNull())
4343 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4344 }
4345
4346 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4347 QualType Ucontext_tType = GetType(Ucontext_t);
4348 if (Ucontext_tType.isNull()) {
4349 Error("ucontext_t type is NULL");
4350 return;
4351 }
4352
4353 if (!Context.ucontext_tDecl) {
4354 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4355 Context.setucontext_tDecl(Typedef->getDecl());
4356 else {
4357 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4358 assert(Tag && "Invalid ucontext_t type in AST file");
4359 Context.setucontext_tDecl(Tag->getDecl());
4360 }
4361 }
4362 }
4363 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004364
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4366
4367 // If there were any CUDA special declarations, deserialize them.
4368 if (!CUDASpecialDeclRefs.empty()) {
4369 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4370 Context.setcudaConfigureCallDecl(
4371 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4372 }
Richard Smith56be7542014-03-21 00:33:59 +00004373
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004375 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004376 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004377 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004378 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004379 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004380 if (Import.ImportLoc.isValid())
4381 PP.makeModuleVisible(Imported, Import.ImportLoc);
4382 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 }
4385 ImportedModules.clear();
4386}
4387
4388void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004389 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004390}
4391
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004392/// \brief Reads and return the signature record from \p PCH's control block, or
4393/// else returns 0.
4394static ASTFileSignature readASTFileSignature(StringRef PCH) {
4395 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004396 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004397 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004398
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004399 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4400 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4401 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004402
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004403 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004404 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004405 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004406 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004407 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004408 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004409
4410 Record.clear();
4411 StringRef Blob;
4412 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004413 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4414 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004415 }
4416}
4417
Guy Benyei11169dd2012-12-18 14:30:41 +00004418/// \brief Retrieve the name of the original source file name
4419/// directly from the AST file, without actually loading the AST
4420/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004421std::string ASTReader::getOriginalSourceFile(
4422 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004423 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004425 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004427 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4428 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 return std::string();
4430 }
4431
4432 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004433 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
4435 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004436 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4438 return std::string();
4439 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004440
Chris Lattnere7b154b2013-01-19 21:39:22 +00004441 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004442 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004443 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4444 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004445 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004446
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004447 // Scan for ORIGINAL_FILE inside the control block.
4448 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004449 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004450 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004451 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4452 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004453
Chris Lattnere7b154b2013-01-19 21:39:22 +00004454 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4455 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4456 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004458
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004460 StringRef Blob;
4461 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4462 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004464}
4465
4466namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004467
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 class SimplePCHValidator : public ASTReaderListener {
4469 const LangOptions &ExistingLangOpts;
4470 const TargetOptions &ExistingTargetOpts;
4471 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004472 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004474
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 public:
4476 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4477 const TargetOptions &ExistingTargetOpts,
4478 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004479 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 FileManager &FileMgr)
4481 : ExistingLangOpts(ExistingLangOpts),
4482 ExistingTargetOpts(ExistingTargetOpts),
4483 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004484 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 FileMgr(FileMgr)
4486 {
4487 }
4488
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004489 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4490 bool AllowCompatibleDifferences) override {
4491 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4492 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004494
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004495 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4496 bool AllowCompatibleDifferences) override {
4497 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4498 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004500
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004501 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4502 StringRef SpecificModuleCachePath,
4503 bool Complain) override {
4504 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4505 ExistingModuleCachePath,
4506 nullptr, ExistingLangOpts);
4507 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004508
Craig Topper3e89dfe2014-03-13 02:13:41 +00004509 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4510 bool Complain,
4511 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004512 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004513 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004516
4517} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004518
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004519bool ASTReader::readASTFileControlBlock(
4520 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004521 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004522 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004523 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004525 // FIXME: This allows use of the VFS; we do not allow use of the
4526 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004527 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 if (!Buffer) {
4529 return true;
4530 }
4531
4532 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004533 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4534 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004535
4536 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004537 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004539
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004540 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004541 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004542 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004543
4544 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004545 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004546 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004547 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004548
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004550 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004551 bool DoneWithControlBlock = false;
4552 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004553 llvm::BitstreamEntry Entry = Stream.advance();
4554
4555 switch (Entry.Kind) {
4556 case llvm::BitstreamEntry::SubBlock: {
4557 switch (Entry.ID) {
4558 case OPTIONS_BLOCK_ID: {
4559 std::string IgnoredSuggestedPredefines;
4560 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4561 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004562 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004563 return true;
4564 break;
4565 }
4566
4567 case INPUT_FILES_BLOCK_ID:
4568 InputFilesCursor = Stream;
4569 if (Stream.SkipBlock() ||
4570 (NeedsInputFiles &&
4571 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4572 return true;
4573 break;
4574
4575 default:
4576 if (Stream.SkipBlock())
4577 return true;
4578 break;
4579 }
4580
4581 continue;
4582 }
4583
4584 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004585 DoneWithControlBlock = true;
4586 break;
Richard Smith0516b182015-09-08 19:40:14 +00004587
4588 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004589 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004590
4591 case llvm::BitstreamEntry::Record:
4592 break;
4593 }
4594
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004595 if (DoneWithControlBlock) break;
4596
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004598 StringRef Blob;
4599 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004600 switch ((ControlRecordTypes)RecCode) {
4601 case METADATA: {
4602 if (Record[0] != VERSION_MAJOR)
4603 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004605 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004606 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004607
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004608 break;
4609 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004610 case MODULE_NAME:
4611 Listener.ReadModuleName(Blob);
4612 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004613 case MODULE_DIRECTORY:
4614 ModuleDir = Blob;
4615 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004616 case MODULE_MAP_FILE: {
4617 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004618 auto Path = ReadString(Record, Idx);
4619 ResolveImportedPath(Path, ModuleDir);
4620 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004621 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004622 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004623 case INPUT_FILE_OFFSETS: {
4624 if (!NeedsInputFiles)
4625 break;
4626
4627 unsigned NumInputFiles = Record[0];
4628 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004629 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004630 for (unsigned I = 0; I != NumInputFiles; ++I) {
4631 // Go find this input file.
4632 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004633
4634 if (isSystemFile && !NeedsSystemInputFiles)
4635 break; // the rest are system input files
4636
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004637 BitstreamCursor &Cursor = InputFilesCursor;
4638 SavedStreamPosition SavedPosition(Cursor);
4639 Cursor.JumpToBit(InputFileOffs[I]);
4640
4641 unsigned Code = Cursor.ReadCode();
4642 RecordData Record;
4643 StringRef Blob;
4644 bool shouldContinue = false;
4645 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4646 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004647 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004648 std::string Filename = Blob;
4649 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004650 shouldContinue = Listener.visitInputFile(
4651 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004652 break;
4653 }
4654 if (!shouldContinue)
4655 break;
4656 }
4657 break;
4658 }
4659
Richard Smithd4b230b2014-10-27 23:01:16 +00004660 case IMPORTS: {
4661 if (!NeedsImports)
4662 break;
4663
4664 unsigned Idx = 0, N = Record.size();
4665 while (Idx < N) {
4666 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004667 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004668 std::string Filename = ReadString(Record, Idx);
4669 ResolveImportedPath(Filename, ModuleDir);
4670 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004671 }
4672 break;
4673 }
4674
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004675 default:
4676 // No other validation to perform.
4677 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 }
4679 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004680
4681 // Look for module file extension blocks, if requested.
4682 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004683 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004684 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4685 bool DoneWithExtensionBlock = false;
4686 while (!DoneWithExtensionBlock) {
4687 llvm::BitstreamEntry Entry = Stream.advance();
4688
4689 switch (Entry.Kind) {
4690 case llvm::BitstreamEntry::SubBlock:
4691 if (Stream.SkipBlock())
4692 return true;
4693
4694 continue;
4695
4696 case llvm::BitstreamEntry::EndBlock:
4697 DoneWithExtensionBlock = true;
4698 continue;
4699
4700 case llvm::BitstreamEntry::Error:
4701 return true;
4702
4703 case llvm::BitstreamEntry::Record:
4704 break;
4705 }
4706
4707 Record.clear();
4708 StringRef Blob;
4709 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4710 switch (RecCode) {
4711 case EXTENSION_METADATA: {
4712 ModuleFileExtensionMetadata Metadata;
4713 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4714 return true;
4715
4716 Listener.readModuleFileExtension(Metadata);
4717 break;
4718 }
4719 }
4720 }
4721 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004722 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004723 }
4724
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004725 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4726 if (readUnhashedControlBlockImpl(
4727 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4728 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4729 ValidateDiagnosticOptions) != Success)
4730 return true;
4731
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004732 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004733}
4734
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004735bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4736 const PCHContainerReader &PCHContainerRdr,
4737 const LangOptions &LangOpts,
4738 const TargetOptions &TargetOpts,
4739 const PreprocessorOptions &PPOpts,
4740 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004741 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4742 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004743 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004744 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004745 validator,
4746 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004747}
4748
Ben Langmuir2c9af442014-04-10 17:57:43 +00004749ASTReader::ASTReadResult
4750ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 // Enter the submodule block.
4752 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4753 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004754 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 }
4756
4757 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4758 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004759 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 RecordData Record;
4761 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004762 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004763
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004764 switch (Entry.Kind) {
4765 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4766 case llvm::BitstreamEntry::Error:
4767 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004768 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004769 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004770 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004771 case llvm::BitstreamEntry::Record:
4772 // The interesting case.
4773 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004775
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004777 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004779 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4780
4781 if ((Kind == SUBMODULE_METADATA) != First) {
4782 Error("submodule metadata record should be at beginning of block");
4783 return Failure;
4784 }
4785 First = false;
4786
4787 // Submodule information is only valid if we have a current module.
4788 // FIXME: Should we error on these cases?
4789 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4790 Kind != SUBMODULE_DEFINITION)
4791 continue;
4792
4793 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 default: // Default behavior: ignore.
4795 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004796
Richard Smith03478d92014-10-23 22:12:14 +00004797 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004798 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004800 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 }
Richard Smith03478d92014-10-23 22:12:14 +00004802
Chris Lattner0e6c9402013-01-20 02:38:54 +00004803 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004804 unsigned Idx = 0;
4805 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4806 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4807 bool IsFramework = Record[Idx++];
4808 bool IsExplicit = Record[Idx++];
4809 bool IsSystem = Record[Idx++];
4810 bool IsExternC = Record[Idx++];
4811 bool InferSubmodules = Record[Idx++];
4812 bool InferExplicitSubmodules = Record[Idx++];
4813 bool InferExportWildcard = Record[Idx++];
4814 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004815 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004816
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004817 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004818 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004820
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 // Retrieve this (sub)module from the module map, creating it if
4822 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004823 CurrentModule =
4824 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4825 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004826
4827 // FIXME: set the definition loc for CurrentModule, or call
4828 // ModMap.setInferredModuleAllowedBy()
4829
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4831 if (GlobalIndex >= SubmodulesLoaded.size() ||
4832 SubmodulesLoaded[GlobalIndex]) {
4833 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004834 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004836
Douglas Gregor7029ce12013-03-19 00:28:20 +00004837 if (!ParentModule) {
4838 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4839 if (CurFile != F.File) {
4840 if (!Diags.isDiagnosticInFlight()) {
4841 Diag(diag::err_module_file_conflict)
4842 << CurrentModule->getTopLevelModuleName()
4843 << CurFile->getName()
4844 << F.File->getName();
4845 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004846 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004847 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004848 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004849
4850 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004851 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004852
Adrian Prantl15bcf702015-06-30 17:39:43 +00004853 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 CurrentModule->IsFromModuleFile = true;
4855 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004856 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 CurrentModule->InferSubmodules = InferSubmodules;
4858 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4859 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004860 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004861 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 if (DeserializationListener)
4863 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004864
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004866
Richard Smith8a3e39a2016-03-28 21:31:09 +00004867 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004868 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004869 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004870 CurrentModule->UnresolvedConflicts.clear();
4871 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004872
4873 // The module is available unless it's missing a requirement; relevant
4874 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4875 // Missing headers that were present when the module was built do not
4876 // make it unavailable -- if we got this far, this must be an explicitly
4877 // imported module file.
4878 CurrentModule->Requirements.clear();
4879 CurrentModule->MissingHeaders.clear();
4880 CurrentModule->IsMissingRequirement =
4881 ParentModule && ParentModule->IsMissingRequirement;
4882 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 break;
4884 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004885
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004887 std::string Filename = Blob;
4888 ResolveImportedPath(F, Filename);
4889 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004891 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4892 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004893 // This can be a spurious difference caused by changing the VFS to
4894 // point to a different copy of the file, and it is too late to
4895 // to rebuild safely.
4896 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4897 // after input file validation only real problems would remain and we
4898 // could just error. For now, assume it's okay.
4899 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 }
4901 }
4902 break;
4903 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004904
Richard Smith202210b2014-10-24 20:23:01 +00004905 case SUBMODULE_HEADER:
4906 case SUBMODULE_EXCLUDED_HEADER:
4907 case SUBMODULE_PRIVATE_HEADER:
4908 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004909 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4910 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004911 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004912
Richard Smith202210b2014-10-24 20:23:01 +00004913 case SUBMODULE_TEXTUAL_HEADER:
4914 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4915 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4916 // them here.
4917 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004918
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004920 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 break;
4922 }
4923
4924 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004925 std::string Dirname = Blob;
4926 ResolveImportedPath(F, Dirname);
4927 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004929 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4930 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004931 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4932 Error("mismatched umbrella directories in submodule");
4933 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 }
4935 }
4936 break;
4937 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004938
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 F.BaseSubmoduleID = getTotalNumSubmodules();
4941 F.LocalNumSubmodules = Record[0];
4942 unsigned LocalBaseSubmoduleID = Record[1];
4943 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004944 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 // module.
4946 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004947
4948 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 // module.
4950 F.SubmoduleRemap.insertOrReplace(
4951 std::make_pair(LocalBaseSubmoduleID,
4952 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004953
Ben Langmuir52ca6782014-10-20 16:27:32 +00004954 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4955 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 break;
4957 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004958
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004961 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 Unresolved.File = &F;
4963 Unresolved.Mod = CurrentModule;
4964 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004965 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004967 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 }
4969 break;
4970 }
4971
4972 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004974 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 Unresolved.File = &F;
4976 Unresolved.Mod = CurrentModule;
4977 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004978 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004980 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004982
4983 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 // the parsed, unresolved exports around.
4985 CurrentModule->UnresolvedExports.clear();
4986 break;
4987 }
4988 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004989 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 Context.getTargetInfo());
4991 break;
4992 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004993
4994 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004995 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004996 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004997 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004998
4999 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005000 CurrentModule->ConfigMacros.push_back(Blob.str());
5001 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005002
5003 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005004 UnresolvedModuleRef Unresolved;
5005 Unresolved.File = &F;
5006 Unresolved.Mod = CurrentModule;
5007 Unresolved.ID = Record[0];
5008 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5009 Unresolved.IsWildcard = false;
5010 Unresolved.String = Blob;
5011 UnresolvedModuleRefs.push_back(Unresolved);
5012 break;
5013 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005014
5015 case SUBMODULE_INITIALIZERS:
5016 SmallVector<uint32_t, 16> Inits;
5017 for (auto &ID : Record)
5018 Inits.push_back(getGlobalDeclID(F, ID));
5019 Context.addLazyModuleInitializers(CurrentModule, Inits);
5020 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 }
5022 }
5023}
5024
5025/// \brief Parse the record that corresponds to a LangOptions data
5026/// structure.
5027///
5028/// This routine parses the language options from the AST file and then gives
5029/// them to the AST listener if one is set.
5030///
5031/// \returns true if the listener deems the file unacceptable, false otherwise.
5032bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5033 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005034 ASTReaderListener &Listener,
5035 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 LangOptions LangOpts;
5037 unsigned Idx = 0;
5038#define LANGOPT(Name, Bits, Default, Description) \
5039 LangOpts.Name = Record[Idx++];
5040#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5041 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5042#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005043#define SANITIZER(NAME, ID) \
5044 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005045#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005046
Ben Langmuircd98cb72015-06-23 18:20:18 +00005047 for (unsigned N = Record[Idx++]; N; --N)
5048 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5049
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5051 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5052 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005053
Ben Langmuird4a667a2015-06-23 18:20:23 +00005054 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005055
5056 // Comment options.
5057 for (unsigned N = Record[Idx++]; N; --N) {
5058 LangOpts.CommentOpts.BlockCommandNames.push_back(
5059 ReadString(Record, Idx));
5060 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005061 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005062
Samuel Antaoee8fb302016-01-06 13:42:12 +00005063 // OpenMP offloading options.
5064 for (unsigned N = Record[Idx++]; N; --N) {
5065 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5066 }
5067
5068 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5069
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005070 return Listener.ReadLanguageOptions(LangOpts, Complain,
5071 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005072}
5073
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005074bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5075 ASTReaderListener &Listener,
5076 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 unsigned Idx = 0;
5078 TargetOptions TargetOpts;
5079 TargetOpts.Triple = ReadString(Record, Idx);
5080 TargetOpts.CPU = ReadString(Record, Idx);
5081 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 for (unsigned N = Record[Idx++]; N; --N) {
5083 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5084 }
5085 for (unsigned N = Record[Idx++]; N; --N) {
5086 TargetOpts.Features.push_back(ReadString(Record, Idx));
5087 }
5088
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005089 return Listener.ReadTargetOptions(TargetOpts, Complain,
5090 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005091}
5092
5093bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5094 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005097#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005098#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005099 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005100#include "clang/Basic/DiagnosticOptions.def"
5101
Richard Smith3be1cb22014-08-07 00:24:21 +00005102 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005103 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005104 for (unsigned N = Record[Idx++]; N; --N)
5105 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005106
5107 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5108}
5109
5110bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5111 ASTReaderListener &Listener) {
5112 FileSystemOptions FSOpts;
5113 unsigned Idx = 0;
5114 FSOpts.WorkingDir = ReadString(Record, Idx);
5115 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5116}
5117
5118bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5119 bool Complain,
5120 ASTReaderListener &Listener) {
5121 HeaderSearchOptions HSOpts;
5122 unsigned Idx = 0;
5123 HSOpts.Sysroot = ReadString(Record, Idx);
5124
5125 // Include entries.
5126 for (unsigned N = Record[Idx++]; N; --N) {
5127 std::string Path = ReadString(Record, Idx);
5128 frontend::IncludeDirGroup Group
5129 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 bool IsFramework = Record[Idx++];
5131 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005132 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5133 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 }
5135
5136 // System header prefixes.
5137 for (unsigned N = Record[Idx++]; N; --N) {
5138 std::string Prefix = ReadString(Record, Idx);
5139 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005140 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 }
5142
5143 HSOpts.ResourceDir = ReadString(Record, Idx);
5144 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005145 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 HSOpts.DisableModuleHash = Record[Idx++];
5147 HSOpts.UseBuiltinIncludes = Record[Idx++];
5148 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5149 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5150 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005151 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005152
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005153 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5154 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005155}
5156
5157bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5158 bool Complain,
5159 ASTReaderListener &Listener,
5160 std::string &SuggestedPredefines) {
5161 PreprocessorOptions PPOpts;
5162 unsigned Idx = 0;
5163
5164 // Macro definitions/undefs
5165 for (unsigned N = Record[Idx++]; N; --N) {
5166 std::string Macro = ReadString(Record, Idx);
5167 bool IsUndef = Record[Idx++];
5168 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5169 }
5170
5171 // Includes
5172 for (unsigned N = Record[Idx++]; N; --N) {
5173 PPOpts.Includes.push_back(ReadString(Record, Idx));
5174 }
5175
5176 // Macro Includes
5177 for (unsigned N = Record[Idx++]; N; --N) {
5178 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5179 }
5180
5181 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005182 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005183 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5184 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5185 PPOpts.ObjCXXARCStandardLibrary =
5186 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5187 SuggestedPredefines.clear();
5188 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5189 SuggestedPredefines);
5190}
5191
5192std::pair<ModuleFile *, unsigned>
5193ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5194 GlobalPreprocessedEntityMapType::iterator
5195 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005196 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 "Corrupted global preprocessed entity map");
5198 ModuleFile *M = I->second;
5199 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5200 return std::make_pair(M, LocalIndex);
5201}
5202
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005203llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005204ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5205 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5206 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5207 Mod.NumPreprocessedEntities);
5208
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005209 return llvm::make_range(PreprocessingRecord::iterator(),
5210 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005211}
5212
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005213llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005214ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005215 return llvm::make_range(
5216 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5217 ModuleDeclIterator(this, &Mod,
5218 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005219}
5220
5221PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5222 PreprocessedEntityID PPID = Index+1;
5223 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5224 ModuleFile &M = *PPInfo.first;
5225 unsigned LocalIndex = PPInfo.second;
5226 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5227
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 if (!PP.getPreprocessingRecord()) {
5229 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005230 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005231 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005232
5233 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005234 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5235
5236 llvm::BitstreamEntry Entry =
5237 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5238 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005239 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005240
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005242 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5243 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005245 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005246 RecordData Record;
5247 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005248 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5249 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 switch (RecType) {
5251 case PPD_MACRO_EXPANSION: {
5252 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005253 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005254 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 if (isBuiltin)
5256 Name = getLocalIdentifier(M, Record[1]);
5257 else {
Richard Smith66a81862015-05-04 02:25:31 +00005258 PreprocessedEntityID GlobalID =
5259 getGlobalPreprocessedEntityID(M, Record[1]);
5260 Def = cast<MacroDefinitionRecord>(
5261 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 }
5263
5264 MacroExpansion *ME;
5265 if (isBuiltin)
5266 ME = new (PPRec) MacroExpansion(Name, Range);
5267 else
5268 ME = new (PPRec) MacroExpansion(Def, Range);
5269
5270 return ME;
5271 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005272
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 case PPD_MACRO_DEFINITION: {
5274 // Decode the identifier info and then check again; if the macro is
5275 // still defined and associated with the identifier,
5276 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005277 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005278
5279 if (DeserializationListener)
5280 DeserializationListener->MacroDefinitionRead(PPID, MD);
5281
5282 return MD;
5283 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005284
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005286 const char *FullFileNameStart = Blob.data() + Record[0];
5287 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005288 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 if (!FullFileName.empty())
5290 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005291
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 // FIXME: Stable encoding
5293 InclusionDirective::InclusionKind Kind
5294 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5295 InclusionDirective *ID
5296 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005297 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 Record[1], Record[3],
5299 File,
5300 Range);
5301 return ID;
5302 }
5303 }
5304
5305 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5306}
5307
5308/// \brief \arg SLocMapI points at a chunk of a module that contains no
5309/// preprocessed entities or the entities it contains are not the ones we are
5310/// looking for. Find the next module that contains entities and return the ID
5311/// of the first entry.
5312PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5313 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5314 ++SLocMapI;
5315 for (GlobalSLocOffsetMapType::const_iterator
5316 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5317 ModuleFile &M = *SLocMapI->second;
5318 if (M.NumPreprocessedEntities)
5319 return M.BasePreprocessedEntityID;
5320 }
5321
5322 return getTotalNumPreprocessedEntities();
5323}
5324
5325namespace {
5326
Guy Benyei11169dd2012-12-18 14:30:41 +00005327struct PPEntityComp {
5328 const ASTReader &Reader;
5329 ModuleFile &M;
5330
5331 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5332
5333 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5334 SourceLocation LHS = getLoc(L);
5335 SourceLocation RHS = getLoc(R);
5336 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5337 }
5338
5339 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5340 SourceLocation LHS = getLoc(L);
5341 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5342 }
5343
5344 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5345 SourceLocation RHS = getLoc(R);
5346 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5347 }
5348
5349 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005350 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 }
5352};
5353
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005354} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005355
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005356PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5357 bool EndsAfter) const {
5358 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005359 return getTotalNumPreprocessedEntities();
5360
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005361 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5362 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5364 "Corrupted global sloc offset map");
5365
5366 if (SLocMapI->second->NumPreprocessedEntities == 0)
5367 return findNextPreprocessedEntity(SLocMapI);
5368
5369 ModuleFile &M = *SLocMapI->second;
5370 typedef const PPEntityOffset *pp_iterator;
5371 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5372 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5373
5374 size_t Count = M.NumPreprocessedEntities;
5375 size_t Half;
5376 pp_iterator First = pp_begin;
5377 pp_iterator PPI;
5378
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005379 if (EndsAfter) {
5380 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005381 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005382 } else {
5383 // Do a binary search manually instead of using std::lower_bound because
5384 // The end locations of entities may be unordered (when a macro expansion
5385 // is inside another macro argument), but for this case it is not important
5386 // whether we get the first macro expansion or its containing macro.
5387 while (Count > 0) {
5388 Half = Count / 2;
5389 PPI = First;
5390 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005391 if (SourceMgr.isBeforeInTranslationUnit(
5392 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005393 First = PPI;
5394 ++First;
5395 Count = Count - Half - 1;
5396 } else
5397 Count = Half;
5398 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 }
5400
5401 if (PPI == pp_end)
5402 return findNextPreprocessedEntity(SLocMapI);
5403
5404 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5405}
5406
Guy Benyei11169dd2012-12-18 14:30:41 +00005407/// \brief Returns a pair of [Begin, End) indices of preallocated
5408/// preprocessed entities that \arg Range encompasses.
5409std::pair<unsigned, unsigned>
5410 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5411 if (Range.isInvalid())
5412 return std::make_pair(0,0);
5413 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5414
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005415 PreprocessedEntityID BeginID =
5416 findPreprocessedEntity(Range.getBegin(), false);
5417 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 return std::make_pair(BeginID, EndID);
5419}
5420
5421/// \brief Optionally returns true or false if the preallocated preprocessed
5422/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005423Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 FileID FID) {
5425 if (FID.isInvalid())
5426 return false;
5427
5428 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5429 ModuleFile &M = *PPInfo.first;
5430 unsigned LocalIndex = PPInfo.second;
5431 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005432
Richard Smithcb34bd32016-03-27 07:28:06 +00005433 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 if (Loc.isInvalid())
5435 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005436
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5438 return true;
5439 else
5440 return false;
5441}
5442
5443namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005444
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 /// \brief Visitor used to search for information about a header file.
5446 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005448
David Blaikie05785d12013-02-20 22:23:23 +00005449 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005450
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005452 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5453 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005454
5455 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 HeaderFileInfoLookupTable *Table
5457 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5458 if (!Table)
5459 return false;
5460
5461 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005462 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005463 if (Pos == Table->end())
5464 return false;
5465
Richard Smithbdf2d932015-07-30 03:37:16 +00005466 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 return true;
5468 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005469
David Blaikie05785d12013-02-20 22:23:23 +00005470 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005472
5473} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005474
5475HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005476 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005477 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005478 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005480
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 return HeaderFileInfo();
5482}
5483
5484void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005485 using DiagState = DiagnosticsEngine::DiagState;
5486 SmallVector<DiagState *, 32> DiagStates;
5487
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005488 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005489 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005490 auto &Record = F.PragmaDiagMappings;
5491 if (Record.empty())
5492 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005493
Richard Smithd230de22017-01-26 01:01:01 +00005494 DiagStates.clear();
5495
5496 auto ReadDiagState =
5497 [&](const DiagState &BasedOn, SourceLocation Loc,
5498 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5499 unsigned BackrefID = Record[Idx++];
5500 if (BackrefID != 0)
5501 return DiagStates[BackrefID - 1];
5502
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005504 Diag.DiagStates.push_back(BasedOn);
5505 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005507 unsigned Size = Record[Idx++];
5508 assert(Idx + Size * 2 <= Record.size() &&
5509 "Invalid data, not enough diag/map pairs");
5510 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005511 unsigned DiagID = Record[Idx++];
5512 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005513 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005514 if (Mapping.isPragma() || IncludeNonPragmaStates)
5515 NewState->setMapping(DiagID, Mapping);
5516 }
Richard Smithd230de22017-01-26 01:01:01 +00005517 return NewState;
5518 };
5519
5520 auto *FirstState = ReadDiagState(
5521 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5522 SourceLocation(), F.isModule());
5523 SourceLocation CurStateLoc =
5524 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5525 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5526
5527 if (!F.isModule()) {
5528 Diag.DiagStatesByLoc.CurDiagState = CurState;
5529 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5530
5531 // Preserve the property that the imaginary root file describes the
5532 // current state.
5533 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5534 if (T.empty())
5535 T.push_back({CurState, 0});
5536 else
5537 T[0].State = CurState;
5538 }
5539
5540 while (Idx < Record.size()) {
5541 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5542 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5543 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5544 unsigned Transitions = Record[Idx++];
5545
5546 // Note that we don't need to set up Parent/ParentOffset here, because
5547 // we won't be changing the diagnostic state within imported FileIDs
5548 // (other than perhaps appending to the main source file, which has no
5549 // parent).
5550 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5551 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5552 for (unsigned I = 0; I != Transitions; ++I) {
5553 unsigned Offset = Record[Idx++];
5554 auto *State =
5555 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5556 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 }
5558 }
Richard Smithd230de22017-01-26 01:01:01 +00005559
5560 // Don't try to read these mappings again.
5561 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 }
5563}
5564
5565/// \brief Get the correct cursor and offset for loading a type.
5566ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5567 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5568 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5569 ModuleFile *M = I->second;
5570 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5571}
5572
5573/// \brief Read and return the type with the given index..
5574///
5575/// The index is the type ID, shifted and minus the number of predefs. This
5576/// routine actually reads the record corresponding to the type at the given
5577/// location. It is a helper routine for GetType, which deals with reading type
5578/// IDs.
5579QualType ASTReader::readTypeRecord(unsigned Index) {
5580 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005581 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005582
5583 // Keep track of where we are in the stream, then jump back there
5584 // after reading this type.
5585 SavedStreamPosition SavedPosition(DeclsCursor);
5586
5587 ReadingKindTracker ReadingKind(Read_Type, *this);
5588
5589 // Note that we are loading a type record.
5590 Deserializing AType(this);
5591
5592 unsigned Idx = 0;
5593 DeclsCursor.JumpToBit(Loc.Offset);
5594 RecordData Record;
5595 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005596 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 case TYPE_EXT_QUAL: {
5598 if (Record.size() != 2) {
5599 Error("Incorrect encoding of extended qualifier type");
5600 return QualType();
5601 }
5602 QualType Base = readType(*Loc.F, Record, Idx);
5603 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5604 return Context.getQualifiedType(Base, Quals);
5605 }
5606
5607 case TYPE_COMPLEX: {
5608 if (Record.size() != 1) {
5609 Error("Incorrect encoding of complex type");
5610 return QualType();
5611 }
5612 QualType ElemType = readType(*Loc.F, Record, Idx);
5613 return Context.getComplexType(ElemType);
5614 }
5615
5616 case TYPE_POINTER: {
5617 if (Record.size() != 1) {
5618 Error("Incorrect encoding of pointer type");
5619 return QualType();
5620 }
5621 QualType PointeeType = readType(*Loc.F, Record, Idx);
5622 return Context.getPointerType(PointeeType);
5623 }
5624
Reid Kleckner8a365022013-06-24 17:51:48 +00005625 case TYPE_DECAYED: {
5626 if (Record.size() != 1) {
5627 Error("Incorrect encoding of decayed type");
5628 return QualType();
5629 }
5630 QualType OriginalType = readType(*Loc.F, Record, Idx);
5631 QualType DT = Context.getAdjustedParameterType(OriginalType);
5632 if (!isa<DecayedType>(DT))
5633 Error("Decayed type does not decay");
5634 return DT;
5635 }
5636
Reid Kleckner0503a872013-12-05 01:23:43 +00005637 case TYPE_ADJUSTED: {
5638 if (Record.size() != 2) {
5639 Error("Incorrect encoding of adjusted type");
5640 return QualType();
5641 }
5642 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5643 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5644 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5645 }
5646
Guy Benyei11169dd2012-12-18 14:30:41 +00005647 case TYPE_BLOCK_POINTER: {
5648 if (Record.size() != 1) {
5649 Error("Incorrect encoding of block pointer type");
5650 return QualType();
5651 }
5652 QualType PointeeType = readType(*Loc.F, Record, Idx);
5653 return Context.getBlockPointerType(PointeeType);
5654 }
5655
5656 case TYPE_LVALUE_REFERENCE: {
5657 if (Record.size() != 2) {
5658 Error("Incorrect encoding of lvalue reference type");
5659 return QualType();
5660 }
5661 QualType PointeeType = readType(*Loc.F, Record, Idx);
5662 return Context.getLValueReferenceType(PointeeType, Record[1]);
5663 }
5664
5665 case TYPE_RVALUE_REFERENCE: {
5666 if (Record.size() != 1) {
5667 Error("Incorrect encoding of rvalue reference type");
5668 return QualType();
5669 }
5670 QualType PointeeType = readType(*Loc.F, Record, Idx);
5671 return Context.getRValueReferenceType(PointeeType);
5672 }
5673
5674 case TYPE_MEMBER_POINTER: {
5675 if (Record.size() != 2) {
5676 Error("Incorrect encoding of member pointer type");
5677 return QualType();
5678 }
5679 QualType PointeeType = readType(*Loc.F, Record, Idx);
5680 QualType ClassType = readType(*Loc.F, Record, Idx);
5681 if (PointeeType.isNull() || ClassType.isNull())
5682 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005683
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5685 }
5686
5687 case TYPE_CONSTANT_ARRAY: {
5688 QualType ElementType = readType(*Loc.F, Record, Idx);
5689 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5690 unsigned IndexTypeQuals = Record[2];
5691 unsigned Idx = 3;
5692 llvm::APInt Size = ReadAPInt(Record, Idx);
5693 return Context.getConstantArrayType(ElementType, Size,
5694 ASM, IndexTypeQuals);
5695 }
5696
5697 case TYPE_INCOMPLETE_ARRAY: {
5698 QualType ElementType = readType(*Loc.F, Record, Idx);
5699 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5700 unsigned IndexTypeQuals = Record[2];
5701 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5702 }
5703
5704 case TYPE_VARIABLE_ARRAY: {
5705 QualType ElementType = readType(*Loc.F, Record, Idx);
5706 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5707 unsigned IndexTypeQuals = Record[2];
5708 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5709 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5710 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5711 ASM, IndexTypeQuals,
5712 SourceRange(LBLoc, RBLoc));
5713 }
5714
5715 case TYPE_VECTOR: {
5716 if (Record.size() != 3) {
5717 Error("incorrect encoding of vector type in AST file");
5718 return QualType();
5719 }
5720
5721 QualType ElementType = readType(*Loc.F, Record, Idx);
5722 unsigned NumElements = Record[1];
5723 unsigned VecKind = Record[2];
5724 return Context.getVectorType(ElementType, NumElements,
5725 (VectorType::VectorKind)VecKind);
5726 }
5727
5728 case TYPE_EXT_VECTOR: {
5729 if (Record.size() != 3) {
5730 Error("incorrect encoding of extended vector type in AST file");
5731 return QualType();
5732 }
5733
5734 QualType ElementType = readType(*Loc.F, Record, Idx);
5735 unsigned NumElements = Record[1];
5736 return Context.getExtVectorType(ElementType, NumElements);
5737 }
5738
5739 case TYPE_FUNCTION_NO_PROTO: {
5740 if (Record.size() != 6) {
5741 Error("incorrect encoding of no-proto function type");
5742 return QualType();
5743 }
5744 QualType ResultType = readType(*Loc.F, Record, Idx);
5745 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5746 (CallingConv)Record[4], Record[5]);
5747 return Context.getFunctionNoProtoType(ResultType, Info);
5748 }
5749
5750 case TYPE_FUNCTION_PROTO: {
5751 QualType ResultType = readType(*Loc.F, Record, Idx);
5752
5753 FunctionProtoType::ExtProtoInfo EPI;
5754 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5755 /*hasregparm*/ Record[2],
5756 /*regparm*/ Record[3],
5757 static_cast<CallingConv>(Record[4]),
5758 /*produces*/ Record[5]);
5759
5760 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005761
5762 EPI.Variadic = Record[Idx++];
5763 EPI.HasTrailingReturn = Record[Idx++];
5764 EPI.TypeQuals = Record[Idx++];
5765 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005766 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005767 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005768
5769 unsigned NumParams = Record[Idx++];
5770 SmallVector<QualType, 16> ParamTypes;
5771 for (unsigned I = 0; I != NumParams; ++I)
5772 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5773
John McCall18afab72016-03-01 00:49:02 +00005774 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5775 if (Idx != Record.size()) {
5776 for (unsigned I = 0; I != NumParams; ++I)
5777 ExtParameterInfos.push_back(
5778 FunctionProtoType::ExtParameterInfo
5779 ::getFromOpaqueValue(Record[Idx++]));
5780 EPI.ExtParameterInfos = ExtParameterInfos.data();
5781 }
5782
5783 assert(Idx == Record.size());
5784
Jordan Rose5c382722013-03-08 21:51:21 +00005785 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 }
5787
5788 case TYPE_UNRESOLVED_USING: {
5789 unsigned Idx = 0;
5790 return Context.getTypeDeclType(
5791 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5792 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005793
Guy Benyei11169dd2012-12-18 14:30:41 +00005794 case TYPE_TYPEDEF: {
5795 if (Record.size() != 2) {
5796 Error("incorrect encoding of typedef type");
5797 return QualType();
5798 }
5799 unsigned Idx = 0;
5800 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5801 QualType Canonical = readType(*Loc.F, Record, Idx);
5802 if (!Canonical.isNull())
5803 Canonical = Context.getCanonicalType(Canonical);
5804 return Context.getTypedefType(Decl, Canonical);
5805 }
5806
5807 case TYPE_TYPEOF_EXPR:
5808 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5809
5810 case TYPE_TYPEOF: {
5811 if (Record.size() != 1) {
5812 Error("incorrect encoding of typeof(type) in AST file");
5813 return QualType();
5814 }
5815 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5816 return Context.getTypeOfType(UnderlyingType);
5817 }
5818
5819 case TYPE_DECLTYPE: {
5820 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5821 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5822 }
5823
5824 case TYPE_UNARY_TRANSFORM: {
5825 QualType BaseType = readType(*Loc.F, Record, Idx);
5826 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5827 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5828 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5829 }
5830
Richard Smith74aeef52013-04-26 16:15:35 +00005831 case TYPE_AUTO: {
5832 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005833 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005834 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005835 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005836 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005837
Richard Smith600b5262017-01-26 20:40:47 +00005838 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5839 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5840 QualType Deduced = readType(*Loc.F, Record, Idx);
5841 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5842 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5843 IsDependent);
5844 }
5845
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 case TYPE_RECORD: {
5847 if (Record.size() != 2) {
5848 Error("incorrect encoding of record type");
5849 return QualType();
5850 }
5851 unsigned Idx = 0;
5852 bool IsDependent = Record[Idx++];
5853 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5854 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5855 QualType T = Context.getRecordType(RD);
5856 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5857 return T;
5858 }
5859
5860 case TYPE_ENUM: {
5861 if (Record.size() != 2) {
5862 Error("incorrect encoding of enum type");
5863 return QualType();
5864 }
5865 unsigned Idx = 0;
5866 bool IsDependent = Record[Idx++];
5867 QualType T
5868 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5869 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5870 return T;
5871 }
5872
5873 case TYPE_ATTRIBUTED: {
5874 if (Record.size() != 3) {
5875 Error("incorrect encoding of attributed type");
5876 return QualType();
5877 }
5878 QualType modifiedType = readType(*Loc.F, Record, Idx);
5879 QualType equivalentType = readType(*Loc.F, Record, Idx);
5880 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5881 return Context.getAttributedType(kind, modifiedType, equivalentType);
5882 }
5883
5884 case TYPE_PAREN: {
5885 if (Record.size() != 1) {
5886 Error("incorrect encoding of paren type");
5887 return QualType();
5888 }
5889 QualType InnerType = readType(*Loc.F, Record, Idx);
5890 return Context.getParenType(InnerType);
5891 }
5892
5893 case TYPE_PACK_EXPANSION: {
5894 if (Record.size() != 2) {
5895 Error("incorrect encoding of pack expansion type");
5896 return QualType();
5897 }
5898 QualType Pattern = readType(*Loc.F, Record, Idx);
5899 if (Pattern.isNull())
5900 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005901 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 if (Record[1])
5903 NumExpansions = Record[1] - 1;
5904 return Context.getPackExpansionType(Pattern, NumExpansions);
5905 }
5906
5907 case TYPE_ELABORATED: {
5908 unsigned Idx = 0;
5909 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5910 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5911 QualType NamedType = readType(*Loc.F, Record, Idx);
5912 return Context.getElaboratedType(Keyword, NNS, NamedType);
5913 }
5914
5915 case TYPE_OBJC_INTERFACE: {
5916 unsigned Idx = 0;
5917 ObjCInterfaceDecl *ItfD
5918 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5919 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5920 }
5921
Manman Rene6be26c2016-09-13 17:25:08 +00005922 case TYPE_OBJC_TYPE_PARAM: {
5923 unsigned Idx = 0;
5924 ObjCTypeParamDecl *Decl
5925 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5926 unsigned NumProtos = Record[Idx++];
5927 SmallVector<ObjCProtocolDecl*, 4> Protos;
5928 for (unsigned I = 0; I != NumProtos; ++I)
5929 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5930 return Context.getObjCTypeParamType(Decl, Protos);
5931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005932 case TYPE_OBJC_OBJECT: {
5933 unsigned Idx = 0;
5934 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005935 unsigned NumTypeArgs = Record[Idx++];
5936 SmallVector<QualType, 4> TypeArgs;
5937 for (unsigned I = 0; I != NumTypeArgs; ++I)
5938 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 unsigned NumProtos = Record[Idx++];
5940 SmallVector<ObjCProtocolDecl*, 4> Protos;
5941 for (unsigned I = 0; I != NumProtos; ++I)
5942 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005943 bool IsKindOf = Record[Idx++];
5944 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005945 }
5946
5947 case TYPE_OBJC_OBJECT_POINTER: {
5948 unsigned Idx = 0;
5949 QualType Pointee = readType(*Loc.F, Record, Idx);
5950 return Context.getObjCObjectPointerType(Pointee);
5951 }
5952
5953 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5954 unsigned Idx = 0;
5955 QualType Parm = readType(*Loc.F, Record, Idx);
5956 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005957 return Context.getSubstTemplateTypeParmType(
5958 cast<TemplateTypeParmType>(Parm),
5959 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 }
5961
5962 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5963 unsigned Idx = 0;
5964 QualType Parm = readType(*Loc.F, Record, Idx);
5965 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5966 return Context.getSubstTemplateTypeParmPackType(
5967 cast<TemplateTypeParmType>(Parm),
5968 ArgPack);
5969 }
5970
5971 case TYPE_INJECTED_CLASS_NAME: {
5972 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5973 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5974 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5975 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005976 const Type *T = nullptr;
5977 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5978 if (const Type *Existing = DI->getTypeForDecl()) {
5979 T = Existing;
5980 break;
5981 }
5982 }
5983 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005984 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005985 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5986 DI->setTypeForDecl(T);
5987 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005988 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005989 }
5990
5991 case TYPE_TEMPLATE_TYPE_PARM: {
5992 unsigned Idx = 0;
5993 unsigned Depth = Record[Idx++];
5994 unsigned Index = Record[Idx++];
5995 bool Pack = Record[Idx++];
5996 TemplateTypeParmDecl *D
5997 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5998 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5999 }
6000
6001 case TYPE_DEPENDENT_NAME: {
6002 unsigned Idx = 0;
6003 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6004 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006005 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 QualType Canon = readType(*Loc.F, Record, Idx);
6007 if (!Canon.isNull())
6008 Canon = Context.getCanonicalType(Canon);
6009 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6010 }
6011
6012 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6013 unsigned Idx = 0;
6014 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6015 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006016 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 unsigned NumArgs = Record[Idx++];
6018 SmallVector<TemplateArgument, 8> Args;
6019 Args.reserve(NumArgs);
6020 while (NumArgs--)
6021 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6022 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006023 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 }
6025
6026 case TYPE_DEPENDENT_SIZED_ARRAY: {
6027 unsigned Idx = 0;
6028
6029 // ArrayType
6030 QualType ElementType = readType(*Loc.F, Record, Idx);
6031 ArrayType::ArraySizeModifier ASM
6032 = (ArrayType::ArraySizeModifier)Record[Idx++];
6033 unsigned IndexTypeQuals = Record[Idx++];
6034
6035 // DependentSizedArrayType
6036 Expr *NumElts = ReadExpr(*Loc.F);
6037 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6038
6039 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6040 IndexTypeQuals, Brackets);
6041 }
6042
6043 case TYPE_TEMPLATE_SPECIALIZATION: {
6044 unsigned Idx = 0;
6045 bool IsDependent = Record[Idx++];
6046 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6047 SmallVector<TemplateArgument, 8> Args;
6048 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6049 QualType Underlying = readType(*Loc.F, Record, Idx);
6050 QualType T;
6051 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006052 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006053 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006054 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6056 return T;
6057 }
6058
6059 case TYPE_ATOMIC: {
6060 if (Record.size() != 1) {
6061 Error("Incorrect encoding of atomic type");
6062 return QualType();
6063 }
6064 QualType ValueType = readType(*Loc.F, Record, Idx);
6065 return Context.getAtomicType(ValueType);
6066 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006067
Joey Goulye3c85de2016-12-01 11:30:49 +00006068 case TYPE_PIPE: {
6069 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006070 Error("Incorrect encoding of pipe type");
6071 return QualType();
6072 }
6073
6074 // Reading the pipe element type.
6075 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006076 unsigned ReadOnly = Record[1];
6077 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006078 }
6079
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 }
6081 llvm_unreachable("Invalid TypeCode!");
6082}
6083
Richard Smith564417a2014-03-20 21:47:22 +00006084void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6085 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006086 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006087 const RecordData &Record, unsigned &Idx) {
6088 ExceptionSpecificationType EST =
6089 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006090 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006091 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006092 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006093 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006094 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006095 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006096 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006097 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006098 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6099 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006100 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006101 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006102 }
6103}
6104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006106 ModuleFile *F;
6107 ASTReader *Reader;
6108 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 unsigned &Idx;
6110
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006111 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006112 return Reader->ReadSourceLocation(*F, Record, Idx);
6113 }
6114
6115 TypeSourceInfo *GetTypeSourceInfo() {
6116 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6117 }
6118
6119 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6120 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 }
6122
Guy Benyei11169dd2012-12-18 14:30:41 +00006123public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006124 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006126 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006127
6128 // We want compile-time assurance that we've enumerated all of
6129 // these, so unfortunately we have to declare them first, then
6130 // define them out-of-line.
6131#define ABSTRACT_TYPELOC(CLASS, PARENT)
6132#define TYPELOC(CLASS, PARENT) \
6133 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6134#include "clang/AST/TypeLocNodes.def"
6135
6136 void VisitFunctionTypeLoc(FunctionTypeLoc);
6137 void VisitArrayTypeLoc(ArrayTypeLoc);
6138};
6139
6140void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6141 // nothing to do
6142}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006145 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006146 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006147 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6148 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6149 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6150 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 }
6152}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006153
Guy Benyei11169dd2012-12-18 14:30:41 +00006154void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006155 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006156}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006157
Guy Benyei11169dd2012-12-18 14:30:41 +00006158void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006159 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006160}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006161
Reid Kleckner8a365022013-06-24 17:51:48 +00006162void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6163 // nothing to do
6164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006165
Reid Kleckner0503a872013-12-05 01:23:43 +00006166void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6167 // nothing to do
6168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006169
Guy Benyei11169dd2012-12-18 14:30:41 +00006170void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006171 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006172}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006173
Guy Benyei11169dd2012-12-18 14:30:41 +00006174void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006175 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006176}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006177
Guy Benyei11169dd2012-12-18 14:30:41 +00006178void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006179 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006180}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006181
Guy Benyei11169dd2012-12-18 14:30:41 +00006182void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006183 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006184 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006185}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006186
Guy Benyei11169dd2012-12-18 14:30:41 +00006187void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006188 TL.setLBracketLoc(ReadSourceLocation());
6189 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006190 if (Record[Idx++])
6191 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 else
Craig Toppera13603a2014-05-22 05:54:18 +00006193 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006194}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006195
Guy Benyei11169dd2012-12-18 14:30:41 +00006196void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6197 VisitArrayTypeLoc(TL);
6198}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006199
Guy Benyei11169dd2012-12-18 14:30:41 +00006200void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6201 VisitArrayTypeLoc(TL);
6202}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006203
Guy Benyei11169dd2012-12-18 14:30:41 +00006204void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6205 VisitArrayTypeLoc(TL);
6206}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006207
Guy Benyei11169dd2012-12-18 14:30:41 +00006208void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6209 DependentSizedArrayTypeLoc TL) {
6210 VisitArrayTypeLoc(TL);
6211}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006212
Guy Benyei11169dd2012-12-18 14:30:41 +00006213void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6214 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006215 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006216}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006217
Guy Benyei11169dd2012-12-18 14:30:41 +00006218void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006219 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006220}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006221
Guy Benyei11169dd2012-12-18 14:30:41 +00006222void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006223 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006224}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006227 TL.setLocalRangeBegin(ReadSourceLocation());
6228 TL.setLParenLoc(ReadSourceLocation());
6229 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006230 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6231 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006232 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006233 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006234 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 }
6236}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006237
Guy Benyei11169dd2012-12-18 14:30:41 +00006238void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6239 VisitFunctionTypeLoc(TL);
6240}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006241
Guy Benyei11169dd2012-12-18 14:30:41 +00006242void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6243 VisitFunctionTypeLoc(TL);
6244}
6245void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006246 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006247}
6248void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006249 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006250}
6251void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006252 TL.setTypeofLoc(ReadSourceLocation());
6253 TL.setLParenLoc(ReadSourceLocation());
6254 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006255}
6256void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006257 TL.setTypeofLoc(ReadSourceLocation());
6258 TL.setLParenLoc(ReadSourceLocation());
6259 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006260 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006261}
6262void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006263 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006264}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006265
Guy Benyei11169dd2012-12-18 14:30:41 +00006266void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006267 TL.setKWLoc(ReadSourceLocation());
6268 TL.setLParenLoc(ReadSourceLocation());
6269 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006270 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006271}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006272
Guy Benyei11169dd2012-12-18 14:30:41 +00006273void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006274 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006275}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006276
Richard Smith600b5262017-01-26 20:40:47 +00006277void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6278 DeducedTemplateSpecializationTypeLoc TL) {
6279 TL.setTemplateNameLoc(ReadSourceLocation());
6280}
6281
Guy Benyei11169dd2012-12-18 14:30:41 +00006282void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006283 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006284}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006285
Guy Benyei11169dd2012-12-18 14:30:41 +00006286void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006287 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006288}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006289
Guy Benyei11169dd2012-12-18 14:30:41 +00006290void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006291 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006292 if (TL.hasAttrOperand()) {
6293 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006294 range.setBegin(ReadSourceLocation());
6295 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 TL.setAttrOperandParensRange(range);
6297 }
6298 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006299 if (Record[Idx++])
6300 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 else
Craig Toppera13603a2014-05-22 05:54:18 +00006302 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006304 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006305}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006306
Guy Benyei11169dd2012-12-18 14:30:41 +00006307void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006308 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006309}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006310
Guy Benyei11169dd2012-12-18 14:30:41 +00006311void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6312 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006313 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006314}
6315void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6316 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006317 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006318}
6319void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6320 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006321 TL.setTemplateKeywordLoc(ReadSourceLocation());
6322 TL.setTemplateNameLoc(ReadSourceLocation());
6323 TL.setLAngleLoc(ReadSourceLocation());
6324 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006326 TL.setArgLocInfo(
6327 i,
6328 Reader->GetTemplateArgumentLocInfo(
6329 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006330}
6331void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006332 TL.setLParenLoc(ReadSourceLocation());
6333 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006334}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006335
Guy Benyei11169dd2012-12-18 14:30:41 +00006336void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006337 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006338 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006339}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006340
Guy Benyei11169dd2012-12-18 14:30:41 +00006341void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006342 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006343}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006344
Guy Benyei11169dd2012-12-18 14:30:41 +00006345void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006346 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006347 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006348 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006349}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006350
Guy Benyei11169dd2012-12-18 14:30:41 +00006351void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6352 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006353 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006354 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006355 TL.setTemplateKeywordLoc(ReadSourceLocation());
6356 TL.setTemplateNameLoc(ReadSourceLocation());
6357 TL.setLAngleLoc(ReadSourceLocation());
6358 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006360 TL.setArgLocInfo(
6361 I,
6362 Reader->GetTemplateArgumentLocInfo(
6363 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006364}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006365
Guy Benyei11169dd2012-12-18 14:30:41 +00006366void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006367 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006368}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006369
Guy Benyei11169dd2012-12-18 14:30:41 +00006370void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006371 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006372}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006373
Manman Rene6be26c2016-09-13 17:25:08 +00006374void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6375 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006376 TL.setProtocolLAngleLoc(ReadSourceLocation());
6377 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006378 }
6379 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006380 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006381}
6382
Guy Benyei11169dd2012-12-18 14:30:41 +00006383void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006384 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006385 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6386 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006387 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006388 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006389 TL.setProtocolLAngleLoc(ReadSourceLocation());
6390 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006392 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006393}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006394
Guy Benyei11169dd2012-12-18 14:30:41 +00006395void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006396 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006397}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006398
Guy Benyei11169dd2012-12-18 14:30:41 +00006399void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006400 TL.setKWLoc(ReadSourceLocation());
6401 TL.setLParenLoc(ReadSourceLocation());
6402 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006403}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006404
Xiuli Pan9c14e282016-01-09 12:53:17 +00006405void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006406 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006407}
Guy Benyei11169dd2012-12-18 14:30:41 +00006408
David L. Jonesbe1557a2016-12-21 00:17:49 +00006409TypeSourceInfo *
6410ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6411 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 QualType InfoTy = readType(F, Record, Idx);
6413 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006414 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006415
6416 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006417 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6419 TLR.Visit(TL);
6420 return TInfo;
6421}
6422
6423QualType ASTReader::GetType(TypeID ID) {
6424 unsigned FastQuals = ID & Qualifiers::FastMask;
6425 unsigned Index = ID >> Qualifiers::FastWidth;
6426
6427 if (Index < NUM_PREDEF_TYPE_IDS) {
6428 QualType T;
6429 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006430 case PREDEF_TYPE_NULL_ID:
6431 return QualType();
6432 case PREDEF_TYPE_VOID_ID:
6433 T = Context.VoidTy;
6434 break;
6435 case PREDEF_TYPE_BOOL_ID:
6436 T = Context.BoolTy;
6437 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006438
6439 case PREDEF_TYPE_CHAR_U_ID:
6440 case PREDEF_TYPE_CHAR_S_ID:
6441 // FIXME: Check that the signedness of CharTy is correct!
6442 T = Context.CharTy;
6443 break;
6444
Alexey Baderbdf7c842015-09-15 12:18:29 +00006445 case PREDEF_TYPE_UCHAR_ID:
6446 T = Context.UnsignedCharTy;
6447 break;
6448 case PREDEF_TYPE_USHORT_ID:
6449 T = Context.UnsignedShortTy;
6450 break;
6451 case PREDEF_TYPE_UINT_ID:
6452 T = Context.UnsignedIntTy;
6453 break;
6454 case PREDEF_TYPE_ULONG_ID:
6455 T = Context.UnsignedLongTy;
6456 break;
6457 case PREDEF_TYPE_ULONGLONG_ID:
6458 T = Context.UnsignedLongLongTy;
6459 break;
6460 case PREDEF_TYPE_UINT128_ID:
6461 T = Context.UnsignedInt128Ty;
6462 break;
6463 case PREDEF_TYPE_SCHAR_ID:
6464 T = Context.SignedCharTy;
6465 break;
6466 case PREDEF_TYPE_WCHAR_ID:
6467 T = Context.WCharTy;
6468 break;
6469 case PREDEF_TYPE_SHORT_ID:
6470 T = Context.ShortTy;
6471 break;
6472 case PREDEF_TYPE_INT_ID:
6473 T = Context.IntTy;
6474 break;
6475 case PREDEF_TYPE_LONG_ID:
6476 T = Context.LongTy;
6477 break;
6478 case PREDEF_TYPE_LONGLONG_ID:
6479 T = Context.LongLongTy;
6480 break;
6481 case PREDEF_TYPE_INT128_ID:
6482 T = Context.Int128Ty;
6483 break;
6484 case PREDEF_TYPE_HALF_ID:
6485 T = Context.HalfTy;
6486 break;
6487 case PREDEF_TYPE_FLOAT_ID:
6488 T = Context.FloatTy;
6489 break;
6490 case PREDEF_TYPE_DOUBLE_ID:
6491 T = Context.DoubleTy;
6492 break;
6493 case PREDEF_TYPE_LONGDOUBLE_ID:
6494 T = Context.LongDoubleTy;
6495 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006496 case PREDEF_TYPE_FLOAT128_ID:
6497 T = Context.Float128Ty;
6498 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006499 case PREDEF_TYPE_OVERLOAD_ID:
6500 T = Context.OverloadTy;
6501 break;
6502 case PREDEF_TYPE_BOUND_MEMBER:
6503 T = Context.BoundMemberTy;
6504 break;
6505 case PREDEF_TYPE_PSEUDO_OBJECT:
6506 T = Context.PseudoObjectTy;
6507 break;
6508 case PREDEF_TYPE_DEPENDENT_ID:
6509 T = Context.DependentTy;
6510 break;
6511 case PREDEF_TYPE_UNKNOWN_ANY:
6512 T = Context.UnknownAnyTy;
6513 break;
6514 case PREDEF_TYPE_NULLPTR_ID:
6515 T = Context.NullPtrTy;
6516 break;
6517 case PREDEF_TYPE_CHAR16_ID:
6518 T = Context.Char16Ty;
6519 break;
6520 case PREDEF_TYPE_CHAR32_ID:
6521 T = Context.Char32Ty;
6522 break;
6523 case PREDEF_TYPE_OBJC_ID:
6524 T = Context.ObjCBuiltinIdTy;
6525 break;
6526 case PREDEF_TYPE_OBJC_CLASS:
6527 T = Context.ObjCBuiltinClassTy;
6528 break;
6529 case PREDEF_TYPE_OBJC_SEL:
6530 T = Context.ObjCBuiltinSelTy;
6531 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006532#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6533 case PREDEF_TYPE_##Id##_ID: \
6534 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006535 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006536#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006537 case PREDEF_TYPE_SAMPLER_ID:
6538 T = Context.OCLSamplerTy;
6539 break;
6540 case PREDEF_TYPE_EVENT_ID:
6541 T = Context.OCLEventTy;
6542 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006543 case PREDEF_TYPE_CLK_EVENT_ID:
6544 T = Context.OCLClkEventTy;
6545 break;
6546 case PREDEF_TYPE_QUEUE_ID:
6547 T = Context.OCLQueueTy;
6548 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006549 case PREDEF_TYPE_RESERVE_ID_ID:
6550 T = Context.OCLReserveIDTy;
6551 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006552 case PREDEF_TYPE_AUTO_DEDUCT:
6553 T = Context.getAutoDeductType();
6554 break;
6555
6556 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6557 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 break;
6559
6560 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6561 T = Context.ARCUnbridgedCastTy;
6562 break;
6563
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 case PREDEF_TYPE_BUILTIN_FN:
6565 T = Context.BuiltinFnTy;
6566 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006567
6568 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6569 T = Context.OMPArraySectionTy;
6570 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 }
6572
6573 assert(!T.isNull() && "Unknown predefined type");
6574 return T.withFastQualifiers(FastQuals);
6575 }
6576
6577 Index -= NUM_PREDEF_TYPE_IDS;
6578 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6579 if (TypesLoaded[Index].isNull()) {
6580 TypesLoaded[Index] = readTypeRecord(Index);
6581 if (TypesLoaded[Index].isNull())
6582 return QualType();
6583
6584 TypesLoaded[Index]->setFromAST();
6585 if (DeserializationListener)
6586 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6587 TypesLoaded[Index]);
6588 }
6589
6590 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6591}
6592
6593QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6594 return GetType(getGlobalTypeID(F, LocalID));
6595}
6596
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006597serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006598ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6599 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6600 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006601
Guy Benyei11169dd2012-12-18 14:30:41 +00006602 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6603 return LocalID;
6604
Richard Smith37a93df2017-02-18 00:32:02 +00006605 if (!F.ModuleOffsetMap.empty())
6606 ReadModuleOffsetMap(F);
6607
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6609 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6610 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006611
Guy Benyei11169dd2012-12-18 14:30:41 +00006612 unsigned GlobalIndex = LocalIndex + I->second;
6613 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6614}
6615
6616TemplateArgumentLocInfo
6617ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6618 TemplateArgument::ArgKind Kind,
6619 const RecordData &Record,
6620 unsigned &Index) {
6621 switch (Kind) {
6622 case TemplateArgument::Expression:
6623 return ReadExpr(F);
6624 case TemplateArgument::Type:
6625 return GetTypeSourceInfo(F, Record, Index);
6626 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006627 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 Index);
6629 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6630 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6631 SourceLocation());
6632 }
6633 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006634 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 Index);
6636 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6637 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006638 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006639 EllipsisLoc);
6640 }
6641 case TemplateArgument::Null:
6642 case TemplateArgument::Integral:
6643 case TemplateArgument::Declaration:
6644 case TemplateArgument::NullPtr:
6645 case TemplateArgument::Pack:
6646 // FIXME: Is this right?
6647 return TemplateArgumentLocInfo();
6648 }
6649 llvm_unreachable("unexpected template argument loc");
6650}
6651
6652TemplateArgumentLoc
6653ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6654 const RecordData &Record, unsigned &Index) {
6655 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6656
6657 if (Arg.getKind() == TemplateArgument::Expression) {
6658 if (Record[Index++]) // bool InfoHasSameExpr.
6659 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6660 }
6661 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6662 Record, Index));
6663}
6664
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006665const ASTTemplateArgumentListInfo*
6666ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6667 const RecordData &Record,
6668 unsigned &Index) {
6669 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6670 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6671 unsigned NumArgsAsWritten = Record[Index++];
6672 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6673 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6674 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6675 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6676}
6677
Guy Benyei11169dd2012-12-18 14:30:41 +00006678Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6679 return GetDecl(ID);
6680}
6681
Richard Smith053f6c62014-05-16 23:01:30 +00006682void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006683 if (NumCurrentElementsDeserializing) {
6684 // We arrange to not care about the complete redeclaration chain while we're
6685 // deserializing. Just remember that the AST has marked this one as complete
6686 // but that it's not actually complete yet, so we know we still need to
6687 // complete it later.
6688 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6689 return;
6690 }
6691
Richard Smith053f6c62014-05-16 23:01:30 +00006692 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6693
Richard Smith053f6c62014-05-16 23:01:30 +00006694 // If this is a named declaration, complete it by looking it up
6695 // within its context.
6696 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006697 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006698 // all mergeable entities within it.
6699 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6700 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6701 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006702 if (!getContext().getLangOpts().CPlusPlus &&
6703 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006704 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006705 // the identifier instead. (For C++ modules, we don't store decls
6706 // in the serialized identifier table, so we do the lookup in the TU.)
6707 auto *II = Name.getAsIdentifierInfo();
6708 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006709 if (II->isOutOfDate())
6710 updateOutOfDateIdentifier(*II);
6711 } else
6712 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006713 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006714 // Find all declarations of this kind from the relevant context.
6715 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6716 auto *DC = cast<DeclContext>(DCDecl);
6717 SmallVector<Decl*, 8> Decls;
6718 FindExternalLexicalDecls(
6719 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6720 }
Richard Smith053f6c62014-05-16 23:01:30 +00006721 }
6722 }
Richard Smith50895422015-01-31 03:04:55 +00006723
6724 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6725 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6726 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6727 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6728 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6729 if (auto *Template = FD->getPrimaryTemplate())
6730 Template->LoadLazySpecializations();
6731 }
Richard Smith053f6c62014-05-16 23:01:30 +00006732}
6733
Richard Smithc2bb8182015-03-24 06:36:48 +00006734CXXCtorInitializer **
6735ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6736 RecordLocation Loc = getLocalBitOffset(Offset);
6737 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6738 SavedStreamPosition SavedPosition(Cursor);
6739 Cursor.JumpToBit(Loc.Offset);
6740 ReadingKindTracker ReadingKind(Read_Decl, *this);
6741
6742 RecordData Record;
6743 unsigned Code = Cursor.ReadCode();
6744 unsigned RecCode = Cursor.readRecord(Code, Record);
6745 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6746 Error("malformed AST file: missing C++ ctor initializers");
6747 return nullptr;
6748 }
6749
6750 unsigned Idx = 0;
6751 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6752}
6753
Guy Benyei11169dd2012-12-18 14:30:41 +00006754CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6755 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006756 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006757 SavedStreamPosition SavedPosition(Cursor);
6758 Cursor.JumpToBit(Loc.Offset);
6759 ReadingKindTracker ReadingKind(Read_Decl, *this);
6760 RecordData Record;
6761 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006762 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006764 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006765 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 }
6767
6768 unsigned Idx = 0;
6769 unsigned NumBases = Record[Idx++];
6770 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6771 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6772 for (unsigned I = 0; I != NumBases; ++I)
6773 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6774 return Bases;
6775}
6776
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006777serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006778ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6779 if (LocalID < NUM_PREDEF_DECL_IDS)
6780 return LocalID;
6781
Richard Smith37a93df2017-02-18 00:32:02 +00006782 if (!F.ModuleOffsetMap.empty())
6783 ReadModuleOffsetMap(F);
6784
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6786 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6787 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006788
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 return LocalID + I->second;
6790}
6791
6792bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6793 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006794 // Predefined decls aren't from any module.
6795 if (ID < NUM_PREDEF_DECL_IDS)
6796 return false;
6797
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006798 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006799 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006800}
6801
Douglas Gregor9f782892013-01-21 15:25:38 +00006802ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006803 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006804 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6806 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6807 return I->second;
6808}
6809
6810SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6811 if (ID < NUM_PREDEF_DECL_IDS)
6812 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006813
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6815
6816 if (Index > DeclsLoaded.size()) {
6817 Error("declaration ID out-of-range for AST file");
6818 return SourceLocation();
6819 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006820
Guy Benyei11169dd2012-12-18 14:30:41 +00006821 if (Decl *D = DeclsLoaded[Index])
6822 return D->getLocation();
6823
Richard Smithcb34bd32016-03-27 07:28:06 +00006824 SourceLocation Loc;
6825 DeclCursorForID(ID, Loc);
6826 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006827}
6828
Richard Smithfe620d22015-03-05 23:24:12 +00006829static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6830 switch (ID) {
6831 case PREDEF_DECL_NULL_ID:
6832 return nullptr;
6833
6834 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6835 return Context.getTranslationUnitDecl();
6836
6837 case PREDEF_DECL_OBJC_ID_ID:
6838 return Context.getObjCIdDecl();
6839
6840 case PREDEF_DECL_OBJC_SEL_ID:
6841 return Context.getObjCSelDecl();
6842
6843 case PREDEF_DECL_OBJC_CLASS_ID:
6844 return Context.getObjCClassDecl();
6845
6846 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6847 return Context.getObjCProtocolDecl();
6848
6849 case PREDEF_DECL_INT_128_ID:
6850 return Context.getInt128Decl();
6851
6852 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6853 return Context.getUInt128Decl();
6854
6855 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6856 return Context.getObjCInstanceTypeDecl();
6857
6858 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6859 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006860
Richard Smith9b88a4c2015-07-27 05:40:23 +00006861 case PREDEF_DECL_VA_LIST_TAG:
6862 return Context.getVaListTagDecl();
6863
Charles Davisc7d5c942015-09-17 20:55:33 +00006864 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6865 return Context.getBuiltinMSVaListDecl();
6866
Richard Smithf19e1272015-03-07 00:04:49 +00006867 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6868 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006869
6870 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6871 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006872
6873 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6874 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006875
6876 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6877 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006878
6879 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6880 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006881 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006882 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006883}
6884
Richard Smithcd45dbc2014-04-19 03:48:30 +00006885Decl *ASTReader::GetExistingDecl(DeclID ID) {
6886 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006887 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6888 if (D) {
6889 // Track that we have merged the declaration with ID \p ID into the
6890 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006891 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006892 if (Merged.empty())
6893 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 }
Richard Smithfe620d22015-03-05 23:24:12 +00006895 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006896 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006897
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6899
6900 if (Index >= DeclsLoaded.size()) {
6901 assert(0 && "declaration ID out-of-range for AST file");
6902 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006903 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006905
6906 return DeclsLoaded[Index];
6907}
6908
6909Decl *ASTReader::GetDecl(DeclID ID) {
6910 if (ID < NUM_PREDEF_DECL_IDS)
6911 return GetExistingDecl(ID);
6912
6913 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6914
6915 if (Index >= DeclsLoaded.size()) {
6916 assert(0 && "declaration ID out-of-range for AST file");
6917 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006918 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006919 }
6920
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 if (!DeclsLoaded[Index]) {
6922 ReadDeclRecord(ID);
6923 if (DeserializationListener)
6924 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6925 }
6926
6927 return DeclsLoaded[Index];
6928}
6929
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006930DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 DeclID GlobalID) {
6932 if (GlobalID < NUM_PREDEF_DECL_IDS)
6933 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006934
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6936 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6937 ModuleFile *Owner = I->second;
6938
6939 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6940 = M.GlobalToLocalDeclIDs.find(Owner);
6941 if (Pos == M.GlobalToLocalDeclIDs.end())
6942 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006943
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 return GlobalID - Owner->BaseDeclID + Pos->second;
6945}
6946
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006947serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 const RecordData &Record,
6949 unsigned &Idx) {
6950 if (Idx >= Record.size()) {
6951 Error("Corrupted AST file");
6952 return 0;
6953 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006954
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 return getGlobalDeclID(F, Record[Idx++]);
6956}
6957
6958/// \brief Resolve the offset of a statement into a statement.
6959///
6960/// This operation will read a new statement from the external
6961/// source each time it is called, and is meant to be used via a
6962/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6963Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6964 // Switch case IDs are per Decl.
6965 ClearSwitchCaseIDs();
6966
6967 // Offset here is a global offset across the entire chain.
6968 RecordLocation Loc = getLocalBitOffset(Offset);
6969 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00006970 assert(NumCurrentElementsDeserializing == 0 &&
6971 "should not be called while already deserializing");
6972 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 return ReadStmtFromStream(*Loc.F);
6974}
6975
Richard Smith3cb15722015-08-05 22:41:45 +00006976void ASTReader::FindExternalLexicalDecls(
6977 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6978 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006979 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6980
Richard Smith9ccdd932015-08-06 22:14:12 +00006981 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006982 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6983 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6984 auto K = (Decl::Kind)+LexicalDecls[I];
6985 if (!IsKindWeWant(K))
6986 continue;
6987
6988 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6989
6990 // Don't add predefined declarations to the lexical context more
6991 // than once.
6992 if (ID < NUM_PREDEF_DECL_IDS) {
6993 if (PredefsVisited[ID])
6994 continue;
6995
6996 PredefsVisited[ID] = true;
6997 }
6998
6999 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007000 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007001 if (!DC->isDeclInLexicalTraversal(D))
7002 Decls.push_back(D);
7003 }
7004 }
7005 };
7006
7007 if (isa<TranslationUnitDecl>(DC)) {
7008 for (auto Lexical : TULexicalDecls)
7009 Visit(Lexical.first, Lexical.second);
7010 } else {
7011 auto I = LexicalDecls.find(DC);
7012 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007013 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007014 }
7015
Guy Benyei11169dd2012-12-18 14:30:41 +00007016 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007017}
7018
7019namespace {
7020
7021class DeclIDComp {
7022 ASTReader &Reader;
7023 ModuleFile &Mod;
7024
7025public:
7026 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7027
7028 bool operator()(LocalDeclID L, LocalDeclID R) const {
7029 SourceLocation LHS = getLocation(L);
7030 SourceLocation RHS = getLocation(R);
7031 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7032 }
7033
7034 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7035 SourceLocation RHS = getLocation(R);
7036 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7037 }
7038
7039 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7040 SourceLocation LHS = getLocation(L);
7041 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7042 }
7043
7044 SourceLocation getLocation(LocalDeclID ID) const {
7045 return Reader.getSourceManager().getFileLoc(
7046 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7047 }
7048};
7049
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007050} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007051
7052void ASTReader::FindFileRegionDecls(FileID File,
7053 unsigned Offset, unsigned Length,
7054 SmallVectorImpl<Decl *> &Decls) {
7055 SourceManager &SM = getSourceManager();
7056
7057 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7058 if (I == FileDeclIDs.end())
7059 return;
7060
7061 FileDeclsInfo &DInfo = I->second;
7062 if (DInfo.Decls.empty())
7063 return;
7064
7065 SourceLocation
7066 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7067 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7068
7069 DeclIDComp DIDComp(*this, *DInfo.Mod);
7070 ArrayRef<serialization::LocalDeclID>::iterator
7071 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7072 BeginLoc, DIDComp);
7073 if (BeginIt != DInfo.Decls.begin())
7074 --BeginIt;
7075
7076 // If we are pointing at a top-level decl inside an objc container, we need
7077 // to backtrack until we find it otherwise we will fail to report that the
7078 // region overlaps with an objc container.
7079 while (BeginIt != DInfo.Decls.begin() &&
7080 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7081 ->isTopLevelDeclInObjCContainer())
7082 --BeginIt;
7083
7084 ArrayRef<serialization::LocalDeclID>::iterator
7085 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7086 EndLoc, DIDComp);
7087 if (EndIt != DInfo.Decls.end())
7088 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007089
Guy Benyei11169dd2012-12-18 14:30:41 +00007090 for (ArrayRef<serialization::LocalDeclID>::iterator
7091 DIt = BeginIt; DIt != EndIt; ++DIt)
7092 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7093}
7094
Richard Smith9ce12e32013-02-07 03:30:24 +00007095bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007096ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7097 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007098 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 "DeclContext has no visible decls in storage");
7100 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007101 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007102
Richard Smithd88a7f12015-09-01 20:35:42 +00007103 auto It = Lookups.find(DC);
7104 if (It == Lookups.end())
7105 return false;
7106
Richard Smith8c913ec2014-08-14 02:21:01 +00007107 Deserializing LookupResults(this);
7108
Richard Smithd88a7f12015-09-01 20:35:42 +00007109 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007110 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007111 for (DeclID ID : It->second.Table.find(Name)) {
7112 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7113 if (ND->getDeclName() == Name)
7114 Decls.push_back(ND);
7115 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007116
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 ++NumVisibleDeclContextsRead;
7118 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007119 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007120}
7121
Guy Benyei11169dd2012-12-18 14:30:41 +00007122void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7123 if (!DC->hasExternalVisibleStorage())
7124 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007125
7126 auto It = Lookups.find(DC);
7127 assert(It != Lookups.end() &&
7128 "have external visible storage but no lookup tables");
7129
Craig Topper79be4cd2013-07-05 04:33:53 +00007130 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007131
Richard Smithd88a7f12015-09-01 20:35:42 +00007132 for (DeclID ID : It->second.Table.findAll()) {
7133 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7134 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007135 }
7136
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 ++NumVisibleDeclContextsRead;
7138
Craig Topper79be4cd2013-07-05 04:33:53 +00007139 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7141 }
7142 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7143}
7144
Richard Smithd88a7f12015-09-01 20:35:42 +00007145const serialization::reader::DeclContextLookupTable *
7146ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7147 auto I = Lookups.find(Primary);
7148 return I == Lookups.end() ? nullptr : &I->second;
7149}
7150
Guy Benyei11169dd2012-12-18 14:30:41 +00007151/// \brief Under non-PCH compilation the consumer receives the objc methods
7152/// before receiving the implementation, and codegen depends on this.
7153/// We simulate this by deserializing and passing to consumer the methods of the
7154/// implementation before passing the deserialized implementation decl.
7155static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7156 ASTConsumer *Consumer) {
7157 assert(ImplD && Consumer);
7158
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007159 for (auto *I : ImplD->methods())
7160 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007161
7162 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7163}
7164
7165void ASTReader::PassInterestingDeclsToConsumer() {
7166 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00007167
7168 if (PassingDeclsToConsumer)
7169 return;
7170
7171 // Guard variable to avoid recursively redoing the process of passing
7172 // decls to consumer.
7173 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7174 true);
7175
Richard Smith9e2341d2015-03-23 03:25:59 +00007176 // Ensure that we've loaded all potentially-interesting declarations
7177 // that need to be eagerly loaded.
7178 for (auto ID : EagerlyDeserializedDecls)
7179 GetDecl(ID);
7180 EagerlyDeserializedDecls.clear();
7181
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 while (!InterestingDecls.empty()) {
7183 Decl *D = InterestingDecls.front();
7184 InterestingDecls.pop_front();
7185
7186 PassInterestingDeclToConsumer(D);
7187 }
7188}
7189
7190void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7191 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7192 PassObjCImplDeclToConsumer(ImplD, Consumer);
7193 else
7194 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7195}
7196
7197void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7198 this->Consumer = Consumer;
7199
Richard Smith9e2341d2015-03-23 03:25:59 +00007200 if (Consumer)
7201 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007202
7203 if (DeserializationListener)
7204 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007205}
7206
7207void ASTReader::PrintStats() {
7208 std::fprintf(stderr, "*** AST File Statistics:\n");
7209
7210 unsigned NumTypesLoaded
7211 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7212 QualType());
7213 unsigned NumDeclsLoaded
7214 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007215 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 unsigned NumIdentifiersLoaded
7217 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7218 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007219 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 unsigned NumMacrosLoaded
7221 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7222 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007223 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 unsigned NumSelectorsLoaded
7225 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7226 SelectorsLoaded.end(),
7227 Selector());
7228
7229 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7230 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7231 NumSLocEntriesRead, TotalNumSLocEntries,
7232 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7233 if (!TypesLoaded.empty())
7234 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7235 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7236 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7237 if (!DeclsLoaded.empty())
7238 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7239 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7240 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7241 if (!IdentifiersLoaded.empty())
7242 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7243 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7244 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7245 if (!MacrosLoaded.empty())
7246 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7247 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7248 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7249 if (!SelectorsLoaded.empty())
7250 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7251 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7252 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7253 if (TotalNumStatements)
7254 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7255 NumStatementsRead, TotalNumStatements,
7256 ((float)NumStatementsRead/TotalNumStatements * 100));
7257 if (TotalNumMacros)
7258 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7259 NumMacrosRead, TotalNumMacros,
7260 ((float)NumMacrosRead/TotalNumMacros * 100));
7261 if (TotalLexicalDeclContexts)
7262 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7263 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7264 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7265 * 100));
7266 if (TotalVisibleDeclContexts)
7267 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7268 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7269 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7270 * 100));
7271 if (TotalNumMethodPoolEntries) {
7272 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7273 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7274 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7275 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007277 if (NumMethodPoolLookups) {
7278 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7279 NumMethodPoolHits, NumMethodPoolLookups,
7280 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7281 }
7282 if (NumMethodPoolTableLookups) {
7283 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7284 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7285 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7286 * 100.0));
7287 }
7288
Douglas Gregor00a50f72013-01-25 00:38:33 +00007289 if (NumIdentifierLookupHits) {
7290 std::fprintf(stderr,
7291 " %u / %u identifier table lookups succeeded (%f%%)\n",
7292 NumIdentifierLookupHits, NumIdentifierLookups,
7293 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7294 }
7295
Douglas Gregore060e572013-01-25 01:03:03 +00007296 if (GlobalIndex) {
7297 std::fprintf(stderr, "\n");
7298 GlobalIndex->printStats();
7299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007300
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 std::fprintf(stderr, "\n");
7302 dump();
7303 std::fprintf(stderr, "\n");
7304}
7305
7306template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007307LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007308dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007309 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 InitialCapacity> &Map) {
7311 if (Map.begin() == Map.end())
7312 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007313
Guy Benyei11169dd2012-12-18 14:30:41 +00007314 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7315 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007316 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007317 I != IEnd; ++I) {
7318 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7319 << "\n";
7320 }
7321}
7322
Yaron Kerencdae9412016-01-29 19:38:18 +00007323LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007324 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7325 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7326 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7327 dumpModuleIDMap("Global type map", GlobalTypeMap);
7328 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7329 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7330 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7331 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7332 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007333 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007335
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007337 for (ModuleFile &M : ModuleMgr)
7338 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007339}
7340
7341/// Return the amount of memory used by memory buffers, breaking down
7342/// by heap-backed versus mmap'ed memory.
7343void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007344 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007345 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007346 size_t bytes = buf->getBufferSize();
7347 switch (buf->getBufferKind()) {
7348 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7349 sizes.malloc_bytes += bytes;
7350 break;
7351 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7352 sizes.mmap_bytes += bytes;
7353 break;
7354 }
7355 }
7356 }
7357}
7358
7359void ASTReader::InitializeSema(Sema &S) {
7360 SemaObj = &S;
7361 S.addExternalSource(this);
7362
7363 // Makes sure any declarations that were deserialized "too early"
7364 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007365 for (uint64_t ID : PreloadedDeclIDs) {
7366 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7367 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007369 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007370
Richard Smith3d8e97e2013-10-18 06:54:39 +00007371 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007372 if (!FPPragmaOptions.empty()) {
7373 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7374 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7375 }
7376
Yaxun Liu5b746652016-12-18 05:18:55 +00007377 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7378 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7379 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007380
7381 UpdateSema();
7382}
7383
7384void ASTReader::UpdateSema() {
7385 assert(SemaObj && "no Sema to update");
7386
7387 // Load the offsets of the declarations that Sema references.
7388 // They will be lazily deserialized when needed.
7389 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007390 assert(SemaDeclRefs.size() % 3 == 0);
7391 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007392 if (!SemaObj->StdNamespace)
7393 SemaObj->StdNamespace = SemaDeclRefs[I];
7394 if (!SemaObj->StdBadAlloc)
7395 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007396 if (!SemaObj->StdAlignValT)
7397 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007398 }
7399 SemaDeclRefs.clear();
7400 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007401
Nico Weber779355f2016-03-02 23:22:00 +00007402 // Update the state of pragmas. Use the same API as if we had encountered the
7403 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007404 if(OptimizeOffPragmaLocation.isValid())
7405 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007406 if (PragmaMSStructState != -1)
7407 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007408 if (PointersToMembersPragmaLocation.isValid()) {
7409 SemaObj->ActOnPragmaMSPointersToMembers(
7410 (LangOptions::PragmaMSPointersToMembersKind)
7411 PragmaMSPointersToMembersState,
7412 PointersToMembersPragmaLocation);
7413 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007414 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007415}
7416
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007417IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 // Note that we are loading an identifier.
7419 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007420
Douglas Gregor7211ac12013-01-25 23:32:03 +00007421 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007422 NumIdentifierLookups,
7423 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007424
7425 // We don't need to do identifier table lookups in C++ modules (we preload
7426 // all interesting declarations, and don't need to use the scope for name
7427 // lookups). Perform the lookup in PCH files, though, since we don't build
7428 // a complete initial identifier table if we're carrying on from a PCH.
7429 if (Context.getLangOpts().CPlusPlus) {
7430 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007431 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007432 break;
7433 } else {
7434 // If there is a global index, look there first to determine which modules
7435 // provably do not have any results for this identifier.
7436 GlobalModuleIndex::HitSet Hits;
7437 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7438 if (!loadGlobalIndex()) {
7439 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7440 HitsPtr = &Hits;
7441 }
7442 }
7443
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007444 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007445 }
7446
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 IdentifierInfo *II = Visitor.getIdentifierInfo();
7448 markIdentifierUpToDate(II);
7449 return II;
7450}
7451
7452namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007453
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 /// \brief An identifier-lookup iterator that enumerates all of the
7455 /// identifiers stored within a set of AST files.
7456 class ASTIdentifierIterator : public IdentifierIterator {
7457 /// \brief The AST reader whose identifiers are being enumerated.
7458 const ASTReader &Reader;
7459
7460 /// \brief The current index into the chain of AST files stored in
7461 /// the AST reader.
7462 unsigned Index;
7463
7464 /// \brief The current position within the identifier lookup table
7465 /// of the current AST file.
7466 ASTIdentifierLookupTable::key_iterator Current;
7467
7468 /// \brief The end position within the identifier lookup table of
7469 /// the current AST file.
7470 ASTIdentifierLookupTable::key_iterator End;
7471
Ben Langmuir537c5b52016-05-04 00:53:13 +00007472 /// \brief Whether to skip any modules in the ASTReader.
7473 bool SkipModules;
7474
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007476 explicit ASTIdentifierIterator(const ASTReader &Reader,
7477 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007478
Craig Topper3e89dfe2014-03-13 02:13:41 +00007479 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007481
7482} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
Ben Langmuir537c5b52016-05-04 00:53:13 +00007484ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7485 bool SkipModules)
7486 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007487}
7488
7489StringRef ASTIdentifierIterator::Next() {
7490 while (Current == End) {
7491 // If we have exhausted all of our AST files, we're done.
7492 if (Index == 0)
7493 return StringRef();
7494
7495 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007496 ModuleFile &F = Reader.ModuleMgr[Index];
7497 if (SkipModules && F.isModule())
7498 continue;
7499
7500 ASTIdentifierLookupTable *IdTable =
7501 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007502 Current = IdTable->key_begin();
7503 End = IdTable->key_end();
7504 }
7505
7506 // We have any identifiers remaining in the current AST file; return
7507 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007508 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007510 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007511}
7512
Ben Langmuir537c5b52016-05-04 00:53:13 +00007513namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007514
Ben Langmuir537c5b52016-05-04 00:53:13 +00007515/// A utility for appending two IdentifierIterators.
7516class ChainedIdentifierIterator : public IdentifierIterator {
7517 std::unique_ptr<IdentifierIterator> Current;
7518 std::unique_ptr<IdentifierIterator> Queued;
7519
7520public:
7521 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7522 std::unique_ptr<IdentifierIterator> Second)
7523 : Current(std::move(First)), Queued(std::move(Second)) {}
7524
7525 StringRef Next() override {
7526 if (!Current)
7527 return StringRef();
7528
7529 StringRef result = Current->Next();
7530 if (!result.empty())
7531 return result;
7532
7533 // Try the queued iterator, which may itself be empty.
7534 Current.reset();
7535 std::swap(Current, Queued);
7536 return Next();
7537 }
7538};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007539
Ben Langmuir537c5b52016-05-04 00:53:13 +00007540} // end anonymous namespace.
7541
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007542IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007543 if (!loadGlobalIndex()) {
7544 std::unique_ptr<IdentifierIterator> ReaderIter(
7545 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7546 std::unique_ptr<IdentifierIterator> ModulesIter(
7547 GlobalIndex->createIdentifierIterator());
7548 return new ChainedIdentifierIterator(std::move(ReaderIter),
7549 std::move(ModulesIter));
7550 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007551
Guy Benyei11169dd2012-12-18 14:30:41 +00007552 return new ASTIdentifierIterator(*this);
7553}
7554
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007555namespace clang {
7556namespace serialization {
7557
Guy Benyei11169dd2012-12-18 14:30:41 +00007558 class ReadMethodPoolVisitor {
7559 ASTReader &Reader;
7560 Selector Sel;
7561 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007562 unsigned InstanceBits;
7563 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007564 bool InstanceHasMoreThanOneDecl;
7565 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007566 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7567 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007568
7569 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007570 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007572 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007573 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7574 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007575
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007576 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007577 if (!M.SelectorLookupTable)
7578 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007579
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007581 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007582 return true;
7583
Richard Smithbdf2d932015-07-30 03:37:16 +00007584 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 ASTSelectorLookupTable *PoolTable
7586 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007587 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007588 if (Pos == PoolTable->end())
7589 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007590
Richard Smithbdf2d932015-07-30 03:37:16 +00007591 ++Reader.NumMethodPoolTableHits;
7592 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 // FIXME: Not quite happy with the statistics here. We probably should
7594 // disable this tracking when called via LoadSelector.
7595 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007596 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007598 if (Reader.DeserializationListener)
7599 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007600
Richard Smithbdf2d932015-07-30 03:37:16 +00007601 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7602 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7603 InstanceBits = Data.InstanceBits;
7604 FactoryBits = Data.FactoryBits;
7605 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7606 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 return true;
7608 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007611 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7612 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 }
7614
7615 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007616 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 return FactoryMethods;
7618 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007619
7620 unsigned getInstanceBits() const { return InstanceBits; }
7621 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007622 bool instanceHasMoreThanOneDecl() const {
7623 return InstanceHasMoreThanOneDecl;
7624 }
7625 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007626 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007627
7628} // end namespace serialization
7629} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007630
7631/// \brief Add the given set of methods to the method list.
7632static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7633 ObjCMethodList &List) {
7634 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7635 S.addMethodToGlobalList(&List, Methods[I]);
7636 }
7637}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007638
Guy Benyei11169dd2012-12-18 14:30:41 +00007639void ASTReader::ReadMethodPool(Selector Sel) {
7640 // Get the selector generation and update it to the current generation.
7641 unsigned &Generation = SelectorGeneration[Sel];
7642 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007643 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007644 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007645
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007647 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007649 ModuleMgr.visit(Visitor);
7650
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007652 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007653 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007654
7655 ++NumMethodPoolHits;
7656
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 if (!getSema())
7658 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007659
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 Sema &S = *getSema();
7661 Sema::GlobalMethodPool::iterator Pos
7662 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007663
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007664 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007665 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007666 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007667 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007668
7669 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7670 // when building a module we keep every method individually and may need to
7671 // update hasMoreThanOneDecl as we add the methods.
7672 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7673 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007674}
7675
Manman Rena0f31a02016-04-29 19:04:05 +00007676void ASTReader::updateOutOfDateSelector(Selector Sel) {
7677 if (SelectorOutOfDate[Sel])
7678 ReadMethodPool(Sel);
7679}
7680
Guy Benyei11169dd2012-12-18 14:30:41 +00007681void ASTReader::ReadKnownNamespaces(
7682 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7683 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007684
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007686 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7688 Namespaces.push_back(Namespace);
7689 }
7690}
7691
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007692void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007693 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007694 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7695 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007696 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007697 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007698 Undefined.insert(std::make_pair(D, Loc));
7699 }
7700}
Nick Lewycky8334af82013-01-26 00:35:08 +00007701
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007702void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7703 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7704 Exprs) {
7705 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7706 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7707 uint64_t Count = DelayedDeleteExprs[Idx++];
7708 for (uint64_t C = 0; C < Count; ++C) {
7709 SourceLocation DeleteLoc =
7710 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7711 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7712 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7713 }
7714 }
7715}
7716
Guy Benyei11169dd2012-12-18 14:30:41 +00007717void ASTReader::ReadTentativeDefinitions(
7718 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7719 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7720 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7721 if (Var)
7722 TentativeDefs.push_back(Var);
7723 }
7724 TentativeDefinitions.clear();
7725}
7726
7727void ASTReader::ReadUnusedFileScopedDecls(
7728 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7729 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7730 DeclaratorDecl *D
7731 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7732 if (D)
7733 Decls.push_back(D);
7734 }
7735 UnusedFileScopedDecls.clear();
7736}
7737
7738void ASTReader::ReadDelegatingConstructors(
7739 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7740 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7741 CXXConstructorDecl *D
7742 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7743 if (D)
7744 Decls.push_back(D);
7745 }
7746 DelegatingCtorDecls.clear();
7747}
7748
7749void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7750 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7751 TypedefNameDecl *D
7752 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7753 if (D)
7754 Decls.push_back(D);
7755 }
7756 ExtVectorDecls.clear();
7757}
7758
Nico Weber72889432014-09-06 01:25:55 +00007759void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7760 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7761 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7762 ++I) {
7763 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7764 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7765 if (D)
7766 Decls.insert(D);
7767 }
7768 UnusedLocalTypedefNameCandidates.clear();
7769}
7770
Guy Benyei11169dd2012-12-18 14:30:41 +00007771void ASTReader::ReadReferencedSelectors(
7772 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7773 if (ReferencedSelectorsData.empty())
7774 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007775
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 // If there are @selector references added them to its pool. This is for
7777 // implementation of -Wselector.
7778 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7779 unsigned I = 0;
7780 while (I < DataSize) {
7781 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7782 SourceLocation SelLoc
7783 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7784 Sels.push_back(std::make_pair(Sel, SelLoc));
7785 }
7786 ReferencedSelectorsData.clear();
7787}
7788
7789void ASTReader::ReadWeakUndeclaredIdentifiers(
7790 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7791 if (WeakUndeclaredIdentifiers.empty())
7792 return;
7793
7794 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007795 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007797 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7799 SourceLocation Loc
7800 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7801 bool Used = WeakUndeclaredIdentifiers[I++];
7802 WeakInfo WI(AliasId, Loc);
7803 WI.setUsed(Used);
7804 WeakIDs.push_back(std::make_pair(WeakId, WI));
7805 }
7806 WeakUndeclaredIdentifiers.clear();
7807}
7808
7809void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7810 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7811 ExternalVTableUse VT;
7812 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7813 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7814 VT.DefinitionRequired = VTableUses[Idx++];
7815 VTables.push_back(VT);
7816 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007817
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 VTableUses.clear();
7819}
7820
7821void ASTReader::ReadPendingInstantiations(
7822 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7823 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7824 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7825 SourceLocation Loc
7826 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7827
7828 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007829 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007830 PendingInstantiations.clear();
7831}
7832
Richard Smithe40f2ba2013-08-07 21:41:30 +00007833void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007834 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7835 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007836 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7837 /* In loop */) {
7838 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7839
Justin Lebar28f09c52016-10-10 16:26:08 +00007840 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007841 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7842
7843 ModuleFile *F = getOwningModuleFile(LT->D);
7844 assert(F && "No module");
7845
7846 unsigned TokN = LateParsedTemplates[Idx++];
7847 LT->Toks.reserve(TokN);
7848 for (unsigned T = 0; T < TokN; ++T)
7849 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7850
Justin Lebar28f09c52016-10-10 16:26:08 +00007851 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007852 }
7853
7854 LateParsedTemplates.clear();
7855}
7856
Guy Benyei11169dd2012-12-18 14:30:41 +00007857void ASTReader::LoadSelector(Selector Sel) {
7858 // It would be complicated to avoid reading the methods anyway. So don't.
7859 ReadMethodPool(Sel);
7860}
7861
7862void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7863 assert(ID && "Non-zero identifier ID required");
7864 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7865 IdentifiersLoaded[ID - 1] = II;
7866 if (DeserializationListener)
7867 DeserializationListener->IdentifierRead(ID, II);
7868}
7869
7870/// \brief Set the globally-visible declarations associated with the given
7871/// identifier.
7872///
7873/// If the AST reader is currently in a state where the given declaration IDs
7874/// cannot safely be resolved, they are queued until it is safe to resolve
7875/// them.
7876///
7877/// \param II an IdentifierInfo that refers to one or more globally-visible
7878/// declarations.
7879///
7880/// \param DeclIDs the set of declaration IDs with the name @p II that are
7881/// visible at global scope.
7882///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007883/// \param Decls if non-null, this vector will be populated with the set of
7884/// deserialized declarations. These declarations will not be pushed into
7885/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007886void
7887ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7888 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007889 SmallVectorImpl<Decl *> *Decls) {
7890 if (NumCurrentElementsDeserializing && !Decls) {
7891 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007892 return;
7893 }
7894
7895 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007896 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007897 // Queue this declaration so that it will be added to the
7898 // translation unit scope and identifier's declaration chain
7899 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007900 PreloadedDeclIDs.push_back(DeclIDs[I]);
7901 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007903
7904 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7905
7906 // If we're simply supposed to record the declarations, do so now.
7907 if (Decls) {
7908 Decls->push_back(D);
7909 continue;
7910 }
7911
7912 // Introduce this declaration into the translation-unit scope
7913 // and add it to the declaration chain for this identifier, so
7914 // that (unqualified) name lookup will find it.
7915 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007916 }
7917}
7918
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007919IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007920 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007921 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007922
7923 if (IdentifiersLoaded.empty()) {
7924 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007925 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007926 }
7927
7928 ID -= 1;
7929 if (!IdentifiersLoaded[ID]) {
7930 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7931 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7932 ModuleFile *M = I->second;
7933 unsigned Index = ID - M->BaseIdentifierID;
7934 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7935
7936 // All of the strings in the AST file are preceded by a 16-bit length.
7937 // Extract that 16-bit length to avoid having to execute strlen().
7938 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7939 // unsigned integers. This is important to avoid integer overflow when
7940 // we cast them to 'unsigned'.
7941 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7942 unsigned StrLen = (((unsigned) StrLenPtr[0])
7943 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007944 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7945 IdentifiersLoaded[ID] = &II;
7946 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007948 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007949 }
7950
7951 return IdentifiersLoaded[ID];
7952}
7953
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007954IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7955 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007956}
7957
7958IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7959 if (LocalID < NUM_PREDEF_IDENT_IDS)
7960 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007961
Richard Smith37a93df2017-02-18 00:32:02 +00007962 if (!M.ModuleOffsetMap.empty())
7963 ReadModuleOffsetMap(M);
7964
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7966 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007967 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007969
Guy Benyei11169dd2012-12-18 14:30:41 +00007970 return LocalID + I->second;
7971}
7972
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007973MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007975 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007976
7977 if (MacrosLoaded.empty()) {
7978 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007979 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 }
7981
7982 ID -= NUM_PREDEF_MACRO_IDS;
7983 if (!MacrosLoaded[ID]) {
7984 GlobalMacroMapType::iterator I
7985 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7986 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7987 ModuleFile *M = I->second;
7988 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007989 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007990
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007991 if (DeserializationListener)
7992 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7993 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 }
7995
7996 return MacrosLoaded[ID];
7997}
7998
7999MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8000 if (LocalID < NUM_PREDEF_MACRO_IDS)
8001 return LocalID;
8002
Richard Smith37a93df2017-02-18 00:32:02 +00008003 if (!M.ModuleOffsetMap.empty())
8004 ReadModuleOffsetMap(M);
8005
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8007 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8008 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8009
8010 return LocalID + I->second;
8011}
8012
8013serialization::SubmoduleID
8014ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8015 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8016 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008017
Richard Smith37a93df2017-02-18 00:32:02 +00008018 if (!M.ModuleOffsetMap.empty())
8019 ReadModuleOffsetMap(M);
8020
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8022 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008023 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008025
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 return LocalID + I->second;
8027}
8028
8029Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8030 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8031 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008032 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008034
Guy Benyei11169dd2012-12-18 14:30:41 +00008035 if (GlobalID > SubmodulesLoaded.size()) {
8036 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008037 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008039
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8041}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008042
8043Module *ASTReader::getModule(unsigned ID) {
8044 return getSubmodule(ID);
8045}
8046
Richard Smithd88a7f12015-09-01 20:35:42 +00008047ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8048 if (ID & 1) {
8049 // It's a module, look it up by submodule ID.
8050 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8051 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8052 } else {
8053 // It's a prefix (preamble, PCH, ...). Look it up by index.
8054 unsigned IndexFromEnd = ID >> 1;
8055 assert(IndexFromEnd && "got reference to unknown module file");
8056 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8057 }
8058}
8059
8060unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8061 if (!F)
8062 return 1;
8063
8064 // For a file representing a module, use the submodule ID of the top-level
8065 // module as the file ID. For any other kind of file, the number of such
8066 // files loaded beforehand will be the same on reload.
8067 // FIXME: Is this true even if we have an explicit module file and a PCH?
8068 if (F->isModule())
8069 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8070
8071 auto PCHModules = getModuleManager().pch_modules();
8072 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8073 assert(I != PCHModules.end() && "emitting reference to unknown file");
8074 return (I - PCHModules.end()) << 1;
8075}
8076
Adrian Prantl15bcf702015-06-30 17:39:43 +00008077llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8078ASTReader::getSourceDescriptor(unsigned ID) {
8079 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008080 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008081
8082 // If there is only a single PCH, return it instead.
8083 // Chained PCH are not suported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008084 const auto &PCHChain = ModuleMgr.pch_modules();
8085 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008086 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008087 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008088 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8089 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8090 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008091 }
8092 return None;
8093}
8094
David Blaikie9ffe5a32017-01-30 05:00:26 +00008095ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
8096 const Module *M = getSubmodule(ID);
8097 if (!M || !M->WithCodegen)
8098 return EK_ReplyHazy;
8099
8100 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
8101 assert(MF); // ?
8102 if (MF->Kind == ModuleKind::MK_MainFile)
8103 return EK_Never;
8104 return EK_Always;
8105}
8106
Guy Benyei11169dd2012-12-18 14:30:41 +00008107Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8108 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8109}
8110
8111Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8112 if (ID == 0)
8113 return Selector();
8114
8115 if (ID > SelectorsLoaded.size()) {
8116 Error("selector ID out of range in AST file");
8117 return Selector();
8118 }
8119
Craig Toppera13603a2014-05-22 05:54:18 +00008120 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 // Load this selector from the selector table.
8122 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8123 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8124 ModuleFile &M = *I->second;
8125 ASTSelectorLookupTrait Trait(*this, M);
8126 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8127 SelectorsLoaded[ID - 1] =
8128 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8129 if (DeserializationListener)
8130 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8131 }
8132
8133 return SelectorsLoaded[ID - 1];
8134}
8135
8136Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8137 return DecodeSelector(ID);
8138}
8139
8140uint32_t ASTReader::GetNumExternalSelectors() {
8141 // ID 0 (the null selector) is considered an external selector.
8142 return getTotalNumSelectors() + 1;
8143}
8144
8145serialization::SelectorID
8146ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8147 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8148 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008149
Richard Smith37a93df2017-02-18 00:32:02 +00008150 if (!M.ModuleOffsetMap.empty())
8151 ReadModuleOffsetMap(M);
8152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8154 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008155 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008157
Guy Benyei11169dd2012-12-18 14:30:41 +00008158 return LocalID + I->second;
8159}
8160
8161DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008162ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 const RecordData &Record, unsigned &Idx) {
8164 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8165 switch (Kind) {
8166 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008167 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008168
8169 case DeclarationName::ObjCZeroArgSelector:
8170 case DeclarationName::ObjCOneArgSelector:
8171 case DeclarationName::ObjCMultiArgSelector:
8172 return DeclarationName(ReadSelector(F, Record, Idx));
8173
8174 case DeclarationName::CXXConstructorName:
8175 return Context.DeclarationNames.getCXXConstructorName(
8176 Context.getCanonicalType(readType(F, Record, Idx)));
8177
8178 case DeclarationName::CXXDestructorName:
8179 return Context.DeclarationNames.getCXXDestructorName(
8180 Context.getCanonicalType(readType(F, Record, Idx)));
8181
Richard Smith35845152017-02-07 01:37:30 +00008182 case DeclarationName::CXXDeductionGuideName:
8183 return Context.DeclarationNames.getCXXDeductionGuideName(
8184 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8185
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 case DeclarationName::CXXConversionFunctionName:
8187 return Context.DeclarationNames.getCXXConversionFunctionName(
8188 Context.getCanonicalType(readType(F, Record, Idx)));
8189
8190 case DeclarationName::CXXOperatorName:
8191 return Context.DeclarationNames.getCXXOperatorName(
8192 (OverloadedOperatorKind)Record[Idx++]);
8193
8194 case DeclarationName::CXXLiteralOperatorName:
8195 return Context.DeclarationNames.getCXXLiteralOperatorName(
8196 GetIdentifierInfo(F, Record, Idx));
8197
8198 case DeclarationName::CXXUsingDirective:
8199 return DeclarationName::getUsingDirectiveName();
8200 }
8201
8202 llvm_unreachable("Invalid NameKind!");
8203}
8204
8205void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8206 DeclarationNameLoc &DNLoc,
8207 DeclarationName Name,
8208 const RecordData &Record, unsigned &Idx) {
8209 switch (Name.getNameKind()) {
8210 case DeclarationName::CXXConstructorName:
8211 case DeclarationName::CXXDestructorName:
8212 case DeclarationName::CXXConversionFunctionName:
8213 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8214 break;
8215
8216 case DeclarationName::CXXOperatorName:
8217 DNLoc.CXXOperatorName.BeginOpNameLoc
8218 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8219 DNLoc.CXXOperatorName.EndOpNameLoc
8220 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8221 break;
8222
8223 case DeclarationName::CXXLiteralOperatorName:
8224 DNLoc.CXXLiteralOperatorName.OpNameLoc
8225 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8226 break;
8227
8228 case DeclarationName::Identifier:
8229 case DeclarationName::ObjCZeroArgSelector:
8230 case DeclarationName::ObjCOneArgSelector:
8231 case DeclarationName::ObjCMultiArgSelector:
8232 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008233 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 break;
8235 }
8236}
8237
8238void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8239 DeclarationNameInfo &NameInfo,
8240 const RecordData &Record, unsigned &Idx) {
8241 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8242 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8243 DeclarationNameLoc DNLoc;
8244 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8245 NameInfo.setInfo(DNLoc);
8246}
8247
8248void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8249 const RecordData &Record, unsigned &Idx) {
8250 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8251 unsigned NumTPLists = Record[Idx++];
8252 Info.NumTemplParamLists = NumTPLists;
8253 if (NumTPLists) {
8254 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008255 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8257 }
8258}
8259
8260TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008261ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008262 unsigned &Idx) {
8263 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8264 switch (Kind) {
8265 case TemplateName::Template:
8266 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8267
8268 case TemplateName::OverloadedTemplate: {
8269 unsigned size = Record[Idx++];
8270 UnresolvedSet<8> Decls;
8271 while (size--)
8272 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8273
8274 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8275 }
8276
8277 case TemplateName::QualifiedTemplate: {
8278 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8279 bool hasTemplKeyword = Record[Idx++];
8280 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8281 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8282 }
8283
8284 case TemplateName::DependentTemplate: {
8285 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8286 if (Record[Idx++]) // isIdentifier
8287 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008288 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 Idx));
8290 return Context.getDependentTemplateName(NNS,
8291 (OverloadedOperatorKind)Record[Idx++]);
8292 }
8293
8294 case TemplateName::SubstTemplateTemplateParm: {
8295 TemplateTemplateParmDecl *param
8296 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8297 if (!param) return TemplateName();
8298 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8299 return Context.getSubstTemplateTemplateParm(param, replacement);
8300 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008303 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8305 if (!Param)
8306 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008307
Guy Benyei11169dd2012-12-18 14:30:41 +00008308 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8309 if (ArgPack.getKind() != TemplateArgument::Pack)
8310 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008311
Guy Benyei11169dd2012-12-18 14:30:41 +00008312 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8313 }
8314 }
8315
8316 llvm_unreachable("Unhandled template name kind!");
8317}
8318
Richard Smith2bb3c342015-08-09 01:05:31 +00008319TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8320 const RecordData &Record,
8321 unsigned &Idx,
8322 bool Canonicalize) {
8323 if (Canonicalize) {
8324 // The caller wants a canonical template argument. Sometimes the AST only
8325 // wants template arguments in canonical form (particularly as the template
8326 // argument lists of template specializations) so ensure we preserve that
8327 // canonical form across serialization.
8328 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8329 return Context.getCanonicalTemplateArgument(Arg);
8330 }
8331
Guy Benyei11169dd2012-12-18 14:30:41 +00008332 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8333 switch (Kind) {
8334 case TemplateArgument::Null:
8335 return TemplateArgument();
8336 case TemplateArgument::Type:
8337 return TemplateArgument(readType(F, Record, Idx));
8338 case TemplateArgument::Declaration: {
8339 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008340 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 }
8342 case TemplateArgument::NullPtr:
8343 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8344 case TemplateArgument::Integral: {
8345 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8346 QualType T = readType(F, Record, Idx);
8347 return TemplateArgument(Context, Value, T);
8348 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008349 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8351 case TemplateArgument::TemplateExpansion: {
8352 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008353 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 if (unsigned NumExpansions = Record[Idx++])
8355 NumTemplateExpansions = NumExpansions - 1;
8356 return TemplateArgument(Name, NumTemplateExpansions);
8357 }
8358 case TemplateArgument::Expression:
8359 return TemplateArgument(ReadExpr(F));
8360 case TemplateArgument::Pack: {
8361 unsigned NumArgs = Record[Idx++];
8362 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8363 for (unsigned I = 0; I != NumArgs; ++I)
8364 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008365 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008366 }
8367 }
8368
8369 llvm_unreachable("Unhandled template argument kind!");
8370}
8371
8372TemplateParameterList *
8373ASTReader::ReadTemplateParameterList(ModuleFile &F,
8374 const RecordData &Record, unsigned &Idx) {
8375 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8376 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8377 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8378
8379 unsigned NumParams = Record[Idx++];
8380 SmallVector<NamedDecl *, 16> Params;
8381 Params.reserve(NumParams);
8382 while (NumParams--)
8383 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8384
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008385 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008386 TemplateParameterList* TemplateParams =
8387 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008388 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008389 return TemplateParams;
8390}
8391
8392void
8393ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008394ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008395 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008396 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 unsigned NumTemplateArgs = Record[Idx++];
8398 TemplArgs.reserve(NumTemplateArgs);
8399 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008400 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008401}
8402
8403/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008404void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008405 const RecordData &Record, unsigned &Idx) {
8406 unsigned NumDecls = Record[Idx++];
8407 Set.reserve(Context, NumDecls);
8408 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008409 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008410 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008411 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 }
8413}
8414
8415CXXBaseSpecifier
8416ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8417 const RecordData &Record, unsigned &Idx) {
8418 bool isVirtual = static_cast<bool>(Record[Idx++]);
8419 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8420 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8421 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8422 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8423 SourceRange Range = ReadSourceRange(F, Record, Idx);
8424 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008425 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008426 EllipsisLoc);
8427 Result.setInheritConstructors(inheritConstructors);
8428 return Result;
8429}
8430
Richard Smithc2bb8182015-03-24 06:36:48 +00008431CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008432ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8433 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008434 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008435 assert(NumInitializers && "wrote ctor initializers but have no inits");
8436 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8437 for (unsigned i = 0; i != NumInitializers; ++i) {
8438 TypeSourceInfo *TInfo = nullptr;
8439 bool IsBaseVirtual = false;
8440 FieldDecl *Member = nullptr;
8441 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008442
Richard Smithc2bb8182015-03-24 06:36:48 +00008443 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8444 switch (Type) {
8445 case CTOR_INITIALIZER_BASE:
8446 TInfo = GetTypeSourceInfo(F, Record, Idx);
8447 IsBaseVirtual = Record[Idx++];
8448 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008449
Richard Smithc2bb8182015-03-24 06:36:48 +00008450 case CTOR_INITIALIZER_DELEGATING:
8451 TInfo = GetTypeSourceInfo(F, Record, Idx);
8452 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008453
Richard Smithc2bb8182015-03-24 06:36:48 +00008454 case CTOR_INITIALIZER_MEMBER:
8455 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8456 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008457
Richard Smithc2bb8182015-03-24 06:36:48 +00008458 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8459 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8460 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008461 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008462
8463 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8464 Expr *Init = ReadExpr(F);
8465 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8466 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008467
8468 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008469 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008470 BOMInit = new (Context)
8471 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8472 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008473 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008474 BOMInit = new (Context)
8475 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008476 else if (Member)
8477 BOMInit = new (Context)
8478 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8479 Init, RParenLoc);
8480 else
8481 BOMInit = new (Context)
8482 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8483 LParenLoc, Init, RParenLoc);
8484
Richard Smith418ed822016-12-14 19:45:03 +00008485 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008486 unsigned SourceOrder = Record[Idx++];
8487 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008488 }
8489
Richard Smithc2bb8182015-03-24 06:36:48 +00008490 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008491 }
8492
Richard Smithc2bb8182015-03-24 06:36:48 +00008493 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008494}
8495
8496NestedNameSpecifier *
8497ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8498 const RecordData &Record, unsigned &Idx) {
8499 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008500 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008501 for (unsigned I = 0; I != N; ++I) {
8502 NestedNameSpecifier::SpecifierKind Kind
8503 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8504 switch (Kind) {
8505 case NestedNameSpecifier::Identifier: {
8506 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8507 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8508 break;
8509 }
8510
8511 case NestedNameSpecifier::Namespace: {
8512 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8513 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8514 break;
8515 }
8516
8517 case NestedNameSpecifier::NamespaceAlias: {
8518 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8519 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8520 break;
8521 }
8522
8523 case NestedNameSpecifier::TypeSpec:
8524 case NestedNameSpecifier::TypeSpecWithTemplate: {
8525 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8526 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008527 return nullptr;
8528
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 bool Template = Record[Idx++];
8530 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8531 break;
8532 }
8533
8534 case NestedNameSpecifier::Global: {
8535 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8536 // No associated value, and there can't be a prefix.
8537 break;
8538 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008539
8540 case NestedNameSpecifier::Super: {
8541 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8542 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8543 break;
8544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008545 }
8546 Prev = NNS;
8547 }
8548 return NNS;
8549}
8550
8551NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008552ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008553 unsigned &Idx) {
8554 unsigned N = Record[Idx++];
8555 NestedNameSpecifierLocBuilder Builder;
8556 for (unsigned I = 0; I != N; ++I) {
8557 NestedNameSpecifier::SpecifierKind Kind
8558 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8559 switch (Kind) {
8560 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008561 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 SourceRange Range = ReadSourceRange(F, Record, Idx);
8563 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8564 break;
8565 }
8566
8567 case NestedNameSpecifier::Namespace: {
8568 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8569 SourceRange Range = ReadSourceRange(F, Record, Idx);
8570 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8571 break;
8572 }
8573
8574 case NestedNameSpecifier::NamespaceAlias: {
8575 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8576 SourceRange Range = ReadSourceRange(F, Record, Idx);
8577 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8578 break;
8579 }
8580
8581 case NestedNameSpecifier::TypeSpec:
8582 case NestedNameSpecifier::TypeSpecWithTemplate: {
8583 bool Template = Record[Idx++];
8584 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8585 if (!T)
8586 return NestedNameSpecifierLoc();
8587 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8588
8589 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008590 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8592 T->getTypeLoc(), ColonColonLoc);
8593 break;
8594 }
8595
8596 case NestedNameSpecifier::Global: {
8597 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8598 Builder.MakeGlobal(Context, ColonColonLoc);
8599 break;
8600 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008601
8602 case NestedNameSpecifier::Super: {
8603 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8604 SourceRange Range = ReadSourceRange(F, Record, Idx);
8605 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8606 break;
8607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008608 }
8609 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008610
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 return Builder.getWithLocInContext(Context);
8612}
8613
8614SourceRange
8615ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8616 unsigned &Idx) {
8617 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8618 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8619 return SourceRange(beg, end);
8620}
8621
8622/// \brief Read an integral value
8623llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8624 unsigned BitWidth = Record[Idx++];
8625 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8626 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8627 Idx += NumWords;
8628 return Result;
8629}
8630
8631/// \brief Read a signed integral value
8632llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8633 bool isUnsigned = Record[Idx++];
8634 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8635}
8636
8637/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008638llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8639 const llvm::fltSemantics &Sem,
8640 unsigned &Idx) {
8641 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008642}
8643
8644// \brief Read a string
8645std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8646 unsigned Len = Record[Idx++];
8647 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8648 Idx += Len;
8649 return Result;
8650}
8651
Richard Smith7ed1bc92014-12-05 22:42:13 +00008652std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8653 unsigned &Idx) {
8654 std::string Filename = ReadString(Record, Idx);
8655 ResolveImportedPath(F, Filename);
8656 return Filename;
8657}
8658
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008659VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008660 unsigned &Idx) {
8661 unsigned Major = Record[Idx++];
8662 unsigned Minor = Record[Idx++];
8663 unsigned Subminor = Record[Idx++];
8664 if (Minor == 0)
8665 return VersionTuple(Major);
8666 if (Subminor == 0)
8667 return VersionTuple(Major, Minor - 1);
8668 return VersionTuple(Major, Minor - 1, Subminor - 1);
8669}
8670
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008671CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008672 const RecordData &Record,
8673 unsigned &Idx) {
8674 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8675 return CXXTemporary::Create(Context, Decl);
8676}
8677
Richard Smith37a93df2017-02-18 00:32:02 +00008678DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008679 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008680}
8681
Richard Smith37a93df2017-02-18 00:32:02 +00008682DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008683 return Diags.Report(Loc, DiagID);
8684}
8685
8686/// \brief Retrieve the identifier table associated with the
8687/// preprocessor.
8688IdentifierTable &ASTReader::getIdentifierTable() {
8689 return PP.getIdentifierTable();
8690}
8691
8692/// \brief Record that the given ID maps to the given switch-case
8693/// statement.
8694void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008695 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 "Already have a SwitchCase with this ID");
8697 (*CurrSwitchCaseStmts)[ID] = SC;
8698}
8699
8700/// \brief Retrieve the switch-case statement with the given ID.
8701SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008702 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 return (*CurrSwitchCaseStmts)[ID];
8704}
8705
8706void ASTReader::ClearSwitchCaseIDs() {
8707 CurrSwitchCaseStmts->clear();
8708}
8709
8710void ASTReader::ReadComments() {
8711 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008712 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 serialization::ModuleFile *> >::iterator
8714 I = CommentsCursors.begin(),
8715 E = CommentsCursors.end();
8716 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008717 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008718 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008719 serialization::ModuleFile &F = *I->second;
8720 SavedStreamPosition SavedPosition(Cursor);
8721
8722 RecordData Record;
8723 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008724 llvm::BitstreamEntry Entry =
8725 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008726
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008727 switch (Entry.Kind) {
8728 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8729 case llvm::BitstreamEntry::Error:
8730 Error("malformed block record in AST file");
8731 return;
8732 case llvm::BitstreamEntry::EndBlock:
8733 goto NextCursor;
8734 case llvm::BitstreamEntry::Record:
8735 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008736 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 }
8738
8739 // Read a record.
8740 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008741 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008742 case COMMENTS_RAW_COMMENT: {
8743 unsigned Idx = 0;
8744 SourceRange SR = ReadSourceRange(F, Record, Idx);
8745 RawComment::CommentKind Kind =
8746 (RawComment::CommentKind) Record[Idx++];
8747 bool IsTrailingComment = Record[Idx++];
8748 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008749 Comments.push_back(new (Context) RawComment(
8750 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8751 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008752 break;
8753 }
8754 }
8755 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008756 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008757 // De-serialized SourceLocations get negative FileIDs for other modules,
8758 // potentially invalidating the original order. Sort it again.
8759 std::sort(Comments.begin(), Comments.end(),
8760 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008761 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008762 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008763}
8764
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008765void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8766 bool IncludeSystem, bool Complain,
8767 llvm::function_ref<void(const serialization::InputFile &IF,
8768 bool isSystem)> Visitor) {
8769 unsigned NumUserInputs = MF.NumUserInputFiles;
8770 unsigned NumInputs = MF.InputFilesLoaded.size();
8771 assert(NumUserInputs <= NumInputs);
8772 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8773 for (unsigned I = 0; I < N; ++I) {
8774 bool IsSystem = I >= NumUserInputs;
8775 InputFile IF = getInputFile(MF, I+1, Complain);
8776 Visitor(IF, IsSystem);
8777 }
8778}
8779
Richard Smithcd45dbc2014-04-19 03:48:30 +00008780std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8781 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008782 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008783 return M->getFullModuleName();
8784
8785 // Otherwise, use the name of the top-level module the decl is within.
8786 if (ModuleFile *M = getOwningModuleFile(D))
8787 return M->ModuleName;
8788
8789 // Not from a module.
8790 return "";
8791}
8792
Guy Benyei11169dd2012-12-18 14:30:41 +00008793void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008794 while (!PendingIdentifierInfos.empty() ||
8795 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008796 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008797 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008798 // If any identifiers with corresponding top-level declarations have
8799 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008800 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8801 TopLevelDeclsMap;
8802 TopLevelDeclsMap TopLevelDecls;
8803
Guy Benyei11169dd2012-12-18 14:30:41 +00008804 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008805 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008806 SmallVector<uint32_t, 4> DeclIDs =
8807 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008808 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008809
8810 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008812
Richard Smith851072e2014-05-19 20:59:20 +00008813 // For each decl chain that we wanted to complete while deserializing, mark
8814 // it as "still needs to be completed".
8815 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8816 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8817 }
8818 PendingIncompleteDeclChains.clear();
8819
Guy Benyei11169dd2012-12-18 14:30:41 +00008820 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008821 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008822 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008823 PendingDeclChains.clear();
8824
Douglas Gregor6168bd22013-02-18 15:53:43 +00008825 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008826 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8827 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008828 IdentifierInfo *II = TLD->first;
8829 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008830 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008831 }
8832 }
8833
Guy Benyei11169dd2012-12-18 14:30:41 +00008834 // Load any pending macro definitions.
8835 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008836 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8837 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8838 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8839 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008840 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008841 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008842 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008843 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008844 resolvePendingMacro(II, Info);
8845 }
8846 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008847 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008848 ++IDIdx) {
8849 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008850 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008851 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008852 }
8853 }
8854 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008855
8856 // Wire up the DeclContexts for Decls that we delayed setting until
8857 // recursive loading is completed.
8858 while (!PendingDeclContextInfos.empty()) {
8859 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8860 PendingDeclContextInfos.pop_front();
8861 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8862 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8863 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8864 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008865
Richard Smithd1c46742014-04-30 02:24:17 +00008866 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008867 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008868 auto Update = PendingUpdateRecords.pop_back_val();
8869 ReadingKindTracker ReadingKind(Read_Decl, *this);
8870 loadDeclUpdateRecords(Update.first, Update.second);
8871 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008872 }
Richard Smith8a639892015-01-24 01:07:20 +00008873
8874 // At this point, all update records for loaded decls are in place, so any
8875 // fake class definitions should have become real.
8876 assert(PendingFakeDefinitionData.empty() &&
8877 "faked up a class definition but never saw the real one");
8878
Guy Benyei11169dd2012-12-18 14:30:41 +00008879 // If we deserialized any C++ or Objective-C class definitions, any
8880 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008881 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008882 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008883 for (Decl *D : PendingDefinitions) {
8884 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008885 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008886 // Make sure that the TagType points at the definition.
8887 const_cast<TagType*>(TagT)->decl = TD;
8888 }
Richard Smith8ce51082015-03-11 01:44:51 +00008889
Craig Topperc6914d02014-08-25 04:15:02 +00008890 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008891 for (auto *R = getMostRecentExistingDecl(RD); R;
8892 R = R->getPreviousDecl()) {
8893 assert((R == D) ==
8894 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008895 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008896 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008898 }
8899
8900 continue;
8901 }
Richard Smith8ce51082015-03-11 01:44:51 +00008902
Craig Topperc6914d02014-08-25 04:15:02 +00008903 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008904 // Make sure that the ObjCInterfaceType points at the definition.
8905 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8906 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008907
8908 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8909 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8910
Guy Benyei11169dd2012-12-18 14:30:41 +00008911 continue;
8912 }
Richard Smith8ce51082015-03-11 01:44:51 +00008913
Craig Topperc6914d02014-08-25 04:15:02 +00008914 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008915 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8916 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8917
Guy Benyei11169dd2012-12-18 14:30:41 +00008918 continue;
8919 }
Richard Smith8ce51082015-03-11 01:44:51 +00008920
Craig Topperc6914d02014-08-25 04:15:02 +00008921 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008922 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8923 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 }
8925 PendingDefinitions.clear();
8926
8927 // Load the bodies of any functions or methods we've encountered. We do
8928 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008929 // have been fully wired up (hasBody relies on this).
8930 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008931 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8932 PBEnd = PendingBodies.end();
8933 PB != PBEnd; ++PB) {
8934 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8935 // FIXME: Check for =delete/=default?
8936 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008937 const FunctionDecl *Defn = nullptr;
8938 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008939 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008940 else
Richard Smith6561f922016-09-12 21:06:40 +00008941 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008942 continue;
8943 }
8944
8945 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8946 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8947 MD->setLazyBody(PB->second);
8948 }
8949 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008950
8951 // Do some cleanup.
8952 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8953 getContext().deduplicateMergedDefinitonsFor(ND);
8954 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008955}
8956
8957void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008958 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8959 return;
8960
Richard Smitha0ce9c42014-07-29 23:23:27 +00008961 // Trigger the import of the full definition of each class that had any
8962 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008963 // These updates may in turn find and diagnose some ODR failures, so take
8964 // ownership of the set first.
8965 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8966 PendingOdrMergeFailures.clear();
8967 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008968 Merge.first->buildLookup();
8969 Merge.first->decls_begin();
8970 Merge.first->bases_begin();
8971 Merge.first->vbases_begin();
8972 for (auto *RD : Merge.second) {
8973 RD->decls_begin();
8974 RD->bases_begin();
8975 RD->vbases_begin();
8976 }
8977 }
8978
8979 // For each declaration from a merged context, check that the canonical
8980 // definition of that context also contains a declaration of the same
8981 // entity.
8982 //
8983 // Caution: this loop does things that might invalidate iterators into
8984 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8985 while (!PendingOdrMergeChecks.empty()) {
8986 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8987
8988 // FIXME: Skip over implicit declarations for now. This matters for things
8989 // like implicitly-declared special member functions. This isn't entirely
8990 // correct; we can end up with multiple unmerged declarations of the same
8991 // implicit entity.
8992 if (D->isImplicit())
8993 continue;
8994
8995 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008996
8997 bool Found = false;
8998 const Decl *DCanon = D->getCanonicalDecl();
8999
Richard Smith01bdb7a2014-08-28 05:44:07 +00009000 for (auto RI : D->redecls()) {
9001 if (RI->getLexicalDeclContext() == CanonDef) {
9002 Found = true;
9003 break;
9004 }
9005 }
9006 if (Found)
9007 continue;
9008
Richard Smith0f4e2c42015-08-06 04:23:48 +00009009 // Quick check failed, time to do the slow thing. Note, we can't just
9010 // look up the name of D in CanonDef here, because the member that is
9011 // in CanonDef might not be found by name lookup (it might have been
9012 // replaced by a more recent declaration in the lookup table), and we
9013 // can't necessarily find it in the redeclaration chain because it might
9014 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009015 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009016 for (auto *CanonMember : CanonDef->decls()) {
9017 if (CanonMember->getCanonicalDecl() == DCanon) {
9018 // This can happen if the declaration is merely mergeable and not
9019 // actually redeclarable (we looked for redeclarations earlier).
9020 //
9021 // FIXME: We should be able to detect this more efficiently, without
9022 // pulling in all of the members of CanonDef.
9023 Found = true;
9024 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009025 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009026 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9027 if (ND->getDeclName() == D->getDeclName())
9028 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009029 }
9030
9031 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009032 // The AST doesn't like TagDecls becoming invalid after they've been
9033 // completed. We only really need to mark FieldDecls as invalid here.
9034 if (!isa<TagDecl>(D))
9035 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009036
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009037 // Ensure we don't accidentally recursively enter deserialization while
9038 // we're producing our diagnostic.
9039 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009040
9041 std::string CanonDefModule =
9042 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9043 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9044 << D << getOwningModuleNameForDiagnostic(D)
9045 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9046
9047 if (Candidates.empty())
9048 Diag(cast<Decl>(CanonDef)->getLocation(),
9049 diag::note_module_odr_violation_no_possible_decls) << D;
9050 else {
9051 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9052 Diag(Candidates[I]->getLocation(),
9053 diag::note_module_odr_violation_possible_decl)
9054 << Candidates[I];
9055 }
9056
9057 DiagnosedOdrMergeFailures.insert(CanonDef);
9058 }
9059 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009060
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009061 if (OdrMergeFailures.empty())
9062 return;
9063
9064 // Ensure we don't accidentally recursively enter deserialization while
9065 // we're producing our diagnostics.
9066 Deserializing RecursionGuard(this);
9067
Richard Smithcd45dbc2014-04-19 03:48:30 +00009068 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009069 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009070 // If we've already pointed out a specific problem with this class, don't
9071 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009072 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009073 continue;
9074
9075 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009076 CXXRecordDecl *FirstRecord = Merge.first;
9077 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9078 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00009079 // Multiple different declarations got merged together; tell the user
9080 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009081 if (FirstRecord == SecondRecord)
9082 continue;
9083
9084 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9085 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9086 DeclHashes FirstHashes;
9087 DeclHashes SecondHashes;
9088 ODRHash Hash;
9089
9090 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9091 CXXRecordDecl *Record) {
9092 for (auto *D : Record->decls()) {
9093 // Due to decl merging, the first CXXRecordDecl is the parent of
9094 // Decls in both records.
9095 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9096 continue;
9097 Hash.clear();
9098 Hash.AddSubDecl(D);
9099 Hashes.emplace_back(D, Hash.CalculateHash());
9100 }
9101 };
9102 PopulateHashes(FirstHashes, FirstRecord);
9103 PopulateHashes(SecondHashes, SecondRecord);
9104
9105 // Used with err_module_odr_violation_mismatch_decl and
9106 // note_module_odr_violation_mismatch_decl
9107 enum {
9108 EndOfClass,
9109 PublicSpecifer,
9110 PrivateSpecifer,
9111 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009112 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009113 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009114 CXXMethod,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009115 Other
9116 } FirstDiffType = Other,
9117 SecondDiffType = Other;
9118
9119 auto DifferenceSelector = [](Decl *D) {
9120 assert(D && "valid Decl required");
9121 switch (D->getKind()) {
9122 default:
9123 return Other;
9124 case Decl::AccessSpec:
9125 switch (D->getAccess()) {
9126 case AS_public:
9127 return PublicSpecifer;
9128 case AS_private:
9129 return PrivateSpecifer;
9130 case AS_protected:
9131 return ProtectedSpecifer;
9132 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009133 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009134 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009135 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009136 case Decl::StaticAssert:
9137 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009138 case Decl::Field:
9139 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009140 case Decl::CXXMethod:
9141 return CXXMethod;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009142 }
9143 };
9144
9145 Decl *FirstDecl = nullptr;
9146 Decl *SecondDecl = nullptr;
9147 auto FirstIt = FirstHashes.begin();
9148 auto SecondIt = SecondHashes.begin();
9149
9150 // If there is a diagnoseable difference, FirstDiffType and
9151 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9152 // filled in if not EndOfClass.
9153 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009154 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9155 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009156 ++FirstIt;
9157 ++SecondIt;
9158 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009159 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009160
Richard Trieue7f7ed22017-02-22 01:11:25 +00009161 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9162 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9163
9164 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9165 SecondDiffType =
9166 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9167
9168 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009169 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009170
9171 if (FirstDiffType == Other || SecondDiffType == Other) {
9172 // Reaching this point means an unexpected Decl was encountered
9173 // or no difference was detected. This causes a generic error
9174 // message to be emitted.
9175 Diag(FirstRecord->getLocation(),
9176 diag::err_module_odr_violation_different_definitions)
9177 << FirstRecord << FirstModule.empty() << FirstModule;
9178
9179 Diag(SecondRecord->getLocation(),
9180 diag::note_module_odr_violation_different_definitions)
9181 << SecondModule;
9182 Diagnosed = true;
9183 break;
9184 }
9185
9186 if (FirstDiffType != SecondDiffType) {
9187 SourceLocation FirstLoc;
9188 SourceRange FirstRange;
9189 if (FirstDiffType == EndOfClass) {
9190 FirstLoc = FirstRecord->getBraceRange().getEnd();
9191 } else {
9192 FirstLoc = FirstIt->first->getLocation();
9193 FirstRange = FirstIt->first->getSourceRange();
9194 }
9195 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9196 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9197 << FirstDiffType;
9198
9199 SourceLocation SecondLoc;
9200 SourceRange SecondRange;
9201 if (SecondDiffType == EndOfClass) {
9202 SecondLoc = SecondRecord->getBraceRange().getEnd();
9203 } else {
9204 SecondLoc = SecondDecl->getLocation();
9205 SecondRange = SecondDecl->getSourceRange();
9206 }
9207 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9208 << SecondModule << SecondRange << SecondDiffType;
9209 Diagnosed = true;
9210 break;
9211 }
9212
Richard Trieu639d7b62017-02-22 22:22:42 +00009213 assert(FirstDiffType == SecondDiffType);
9214
9215 // Used with err_module_odr_violation_mismatch_decl_diff and
9216 // note_module_odr_violation_mismatch_decl_diff
9217 enum ODRDeclDifference{
9218 StaticAssertCondition,
9219 StaticAssertMessage,
9220 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009221 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009222 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009223 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009224 FieldDifferentWidthBitField,
9225 FieldSingleMutable,
9226 FieldSingleInitializer,
9227 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009228 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009229 MethodDeleted,
9230 MethodVirtual,
9231 MethodStatic,
9232 MethodVolatile,
9233 MethodConst,
9234 MethodInline,
Richard Trieu639d7b62017-02-22 22:22:42 +00009235 };
9236
9237 // These lambdas have the common portions of the ODR diagnostics. This
9238 // has the same return as Diag(), so addition parameters can be passed
9239 // in with operator<<
9240 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9241 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9242 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9243 << FirstRecord << FirstModule.empty() << FirstModule << Range
9244 << DiffType;
9245 };
9246 auto ODRDiagNote = [&SecondModule, this](
9247 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9248 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9249 << SecondModule << Range << DiffType;
9250 };
9251
9252 auto ComputeODRHash = [&Hash](const Stmt* S) {
9253 assert(S);
9254 Hash.clear();
9255 Hash.AddStmt(S);
9256 return Hash.CalculateHash();
9257 };
9258
Richard Trieu8459ddf2017-02-24 02:59:12 +00009259 auto ComputeDeclNameODRHash = [&Hash](const DeclarationName Name) {
9260 Hash.clear();
9261 Hash.AddDeclarationName(Name);
9262 return Hash.CalculateHash();
9263 };
9264
Richard Trieu639d7b62017-02-22 22:22:42 +00009265 switch (FirstDiffType) {
9266 case Other:
9267 case EndOfClass:
9268 case PublicSpecifer:
9269 case PrivateSpecifer:
9270 case ProtectedSpecifer:
9271 llvm_unreachable("Invalid diff type");
9272
9273 case StaticAssert: {
9274 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9275 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9276
9277 Expr *FirstExpr = FirstSA->getAssertExpr();
9278 Expr *SecondExpr = SecondSA->getAssertExpr();
9279 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9280 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9281 if (FirstODRHash != SecondODRHash) {
9282 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9283 StaticAssertCondition);
9284 ODRDiagNote(SecondExpr->getLocStart(),
9285 SecondExpr->getSourceRange(), StaticAssertCondition);
9286 Diagnosed = true;
9287 break;
9288 }
9289
9290 StringLiteral *FirstStr = FirstSA->getMessage();
9291 StringLiteral *SecondStr = SecondSA->getMessage();
9292 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9293 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9294 SourceLocation FirstLoc, SecondLoc;
9295 SourceRange FirstRange, SecondRange;
9296 if (FirstStr) {
9297 FirstLoc = FirstStr->getLocStart();
9298 FirstRange = FirstStr->getSourceRange();
9299 } else {
9300 FirstLoc = FirstSA->getLocStart();
9301 FirstRange = FirstSA->getSourceRange();
9302 }
9303 if (SecondStr) {
9304 SecondLoc = SecondStr->getLocStart();
9305 SecondRange = SecondStr->getSourceRange();
9306 } else {
9307 SecondLoc = SecondSA->getLocStart();
9308 SecondRange = SecondSA->getSourceRange();
9309 }
9310 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9311 << (FirstStr == nullptr);
9312 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9313 << (SecondStr == nullptr);
9314 Diagnosed = true;
9315 break;
9316 }
9317
9318 if (FirstStr && SecondStr &&
9319 FirstStr->getString() != SecondStr->getString()) {
9320 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9321 StaticAssertMessage);
9322 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9323 StaticAssertMessage);
9324 Diagnosed = true;
9325 break;
9326 }
9327 break;
9328 }
Richard Trieud0786092017-02-23 00:23:01 +00009329 case Field: {
9330 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9331 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9332 IdentifierInfo *FirstII = FirstField->getIdentifier();
9333 IdentifierInfo *SecondII = SecondField->getIdentifier();
9334 if (FirstII->getName() != SecondII->getName()) {
9335 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9336 FieldName)
9337 << FirstII;
9338 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9339 FieldName)
9340 << SecondII;
9341
9342 Diagnosed = true;
9343 break;
9344 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009345
9346 assert(
9347 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9348
9349 QualType FirstType = FirstField->getType();
9350 QualType SecondType = SecondField->getType();
9351 const TypedefType *FirstTypedef = dyn_cast<TypedefType>(FirstType);
9352 const TypedefType *SecondTypedef = dyn_cast<TypedefType>(SecondType);
9353
9354 if ((FirstTypedef && !SecondTypedef) ||
9355 (!FirstTypedef && SecondTypedef)) {
9356 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9357 FieldTypeName)
9358 << FirstII << FirstType;
9359 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9360 FieldTypeName)
9361 << SecondII << SecondType;
9362
9363 Diagnosed = true;
9364 break;
9365 }
9366
9367 if (FirstTypedef && SecondTypedef) {
9368 unsigned FirstHash = ComputeDeclNameODRHash(
9369 FirstTypedef->getDecl()->getDeclName());
9370 unsigned SecondHash = ComputeDeclNameODRHash(
9371 SecondTypedef->getDecl()->getDeclName());
9372 if (FirstHash != SecondHash) {
9373 ODRDiagError(FirstField->getLocation(),
9374 FirstField->getSourceRange(), FieldTypeName)
9375 << FirstII << FirstType;
9376 ODRDiagNote(SecondField->getLocation(),
9377 SecondField->getSourceRange(), FieldTypeName)
9378 << SecondII << SecondType;
9379
9380 Diagnosed = true;
9381 break;
9382 }
9383 }
9384
Richard Trieu93772fc2017-02-24 20:59:28 +00009385 const bool IsFirstBitField = FirstField->isBitField();
9386 const bool IsSecondBitField = SecondField->isBitField();
9387 if (IsFirstBitField != IsSecondBitField) {
9388 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9389 FieldSingleBitField)
9390 << FirstII << IsFirstBitField;
9391 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9392 FieldSingleBitField)
9393 << SecondII << IsSecondBitField;
9394 Diagnosed = true;
9395 break;
9396 }
9397
9398 if (IsFirstBitField && IsSecondBitField) {
9399 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9400 FieldDifferentWidthBitField)
9401 << FirstII << FirstField->getBitWidth()->getSourceRange();
9402 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9403 FieldDifferentWidthBitField)
9404 << SecondII << SecondField->getBitWidth()->getSourceRange();
9405 Diagnosed = true;
9406 break;
9407 }
9408
Richard Trieu8d543e22017-02-24 23:35:37 +00009409 const bool IsFirstMutable = FirstField->isMutable();
9410 const bool IsSecondMutable = SecondField->isMutable();
9411 if (IsFirstMutable != IsSecondMutable) {
9412 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9413 FieldSingleMutable)
9414 << FirstII << IsFirstMutable;
9415 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9416 FieldSingleMutable)
9417 << SecondII << IsSecondMutable;
9418 Diagnosed = true;
9419 break;
9420 }
9421
9422 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9423 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9424 if ((!FirstInitializer && SecondInitializer) ||
9425 (FirstInitializer && !SecondInitializer)) {
9426 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9427 FieldSingleInitializer)
9428 << FirstII << (FirstInitializer != nullptr);
9429 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9430 FieldSingleInitializer)
9431 << SecondII << (SecondInitializer != nullptr);
9432 Diagnosed = true;
9433 break;
9434 }
9435
9436 if (FirstInitializer && SecondInitializer) {
9437 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9438 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9439 if (FirstInitHash != SecondInitHash) {
9440 ODRDiagError(FirstField->getLocation(),
9441 FirstField->getSourceRange(),
9442 FieldDifferentInitializers)
9443 << FirstII << FirstInitializer->getSourceRange();
9444 ODRDiagNote(SecondField->getLocation(),
9445 SecondField->getSourceRange(),
9446 FieldDifferentInitializers)
9447 << SecondII << SecondInitializer->getSourceRange();
9448 Diagnosed = true;
9449 break;
9450 }
9451 }
9452
Richard Trieud0786092017-02-23 00:23:01 +00009453 break;
9454 }
Richard Trieu48143742017-02-28 21:24:38 +00009455 case CXXMethod: {
9456 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9457 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu583e2c12017-03-04 00:08:58 +00009458 auto FirstName = FirstMethod->getDeclName();
9459 auto SecondName = SecondMethod->getDeclName();
9460 if (FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009461 ODRDiagError(FirstMethod->getLocation(),
9462 FirstMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009463 << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009464 ODRDiagNote(SecondMethod->getLocation(),
9465 SecondMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009466 << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009467
9468 Diagnosed = true;
9469 break;
9470 }
9471
Richard Trieu583e2c12017-03-04 00:08:58 +00009472 const bool FirstDeleted = FirstMethod->isDeleted();
9473 const bool SecondDeleted = SecondMethod->isDeleted();
9474 if (FirstDeleted != SecondDeleted) {
9475 ODRDiagError(FirstMethod->getLocation(),
9476 FirstMethod->getSourceRange(), MethodDeleted)
9477 << FirstName << FirstDeleted;
9478
9479 ODRDiagNote(SecondMethod->getLocation(),
9480 SecondMethod->getSourceRange(), MethodDeleted)
9481 << SecondName << SecondDeleted;
9482 Diagnosed = true;
9483 break;
9484 }
9485
9486 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9487 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9488 const bool FirstPure = FirstMethod->isPure();
9489 const bool SecondPure = SecondMethod->isPure();
9490 if ((FirstVirtual || SecondVirtual) &&
9491 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9492 ODRDiagError(FirstMethod->getLocation(),
9493 FirstMethod->getSourceRange(), MethodVirtual)
9494 << FirstName << FirstPure << FirstVirtual;
9495 ODRDiagNote(SecondMethod->getLocation(),
9496 SecondMethod->getSourceRange(), MethodVirtual)
9497 << SecondName << SecondPure << SecondVirtual;
9498 Diagnosed = true;
9499 break;
9500 }
9501
9502 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9503 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9504 // class needs to be checked instead.
9505 const auto FirstStorage = FirstMethod->getStorageClass();
9506 const auto SecondStorage = SecondMethod->getStorageClass();
9507 const bool FirstStatic = FirstStorage == SC_Static;
9508 const bool SecondStatic = SecondStorage == SC_Static;
9509 if (FirstStatic != SecondStatic) {
9510 ODRDiagError(FirstMethod->getLocation(),
9511 FirstMethod->getSourceRange(), MethodStatic)
9512 << FirstName << FirstStatic;
9513 ODRDiagNote(SecondMethod->getLocation(),
9514 SecondMethod->getSourceRange(), MethodStatic)
9515 << SecondName << SecondStatic;
9516 Diagnosed = true;
9517 break;
9518 }
9519
9520 const bool FirstVolatile = FirstMethod->isVolatile();
9521 const bool SecondVolatile = SecondMethod->isVolatile();
9522 if (FirstVolatile != SecondVolatile) {
9523 ODRDiagError(FirstMethod->getLocation(),
9524 FirstMethod->getSourceRange(), MethodVolatile)
9525 << FirstName << FirstVolatile;
9526 ODRDiagNote(SecondMethod->getLocation(),
9527 SecondMethod->getSourceRange(), MethodVolatile)
9528 << SecondName << SecondVolatile;
9529 Diagnosed = true;
9530 break;
9531 }
9532
9533 const bool FirstConst = FirstMethod->isConst();
9534 const bool SecondConst = SecondMethod->isConst();
9535 if (FirstConst != SecondConst) {
9536 ODRDiagError(FirstMethod->getLocation(),
9537 FirstMethod->getSourceRange(), MethodConst)
9538 << FirstName << FirstConst;
9539 ODRDiagNote(SecondMethod->getLocation(),
9540 SecondMethod->getSourceRange(), MethodConst)
9541 << SecondName << SecondConst;
9542 Diagnosed = true;
9543 break;
9544 }
9545
9546 const bool FirstInline = FirstMethod->isInlineSpecified();
9547 const bool SecondInline = SecondMethod->isInlineSpecified();
9548 if (FirstInline != SecondInline) {
9549 ODRDiagError(FirstMethod->getLocation(),
9550 FirstMethod->getSourceRange(), MethodInline)
9551 << FirstName << FirstInline;
9552 ODRDiagNote(SecondMethod->getLocation(),
9553 SecondMethod->getSourceRange(), MethodInline)
9554 << SecondName << SecondInline;
9555 Diagnosed = true;
9556 break;
9557 }
9558
Richard Trieu48143742017-02-28 21:24:38 +00009559 break;
9560 }
Richard Trieu639d7b62017-02-22 22:22:42 +00009561 }
9562
Richard Trieue7f7ed22017-02-22 01:11:25 +00009563 if (Diagnosed == true)
9564 continue;
9565
9566 Diag(FirstRecord->getLocation(),
9567 diag::err_module_odr_violation_different_definitions)
9568 << FirstRecord << FirstModule.empty() << FirstModule;
9569
9570 Diag(SecondRecord->getLocation(),
9571 diag::note_module_odr_violation_different_definitions)
9572 << SecondModule;
9573 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009574 }
9575
9576 if (!Diagnosed) {
9577 // All definitions are updates to the same declaration. This happens if a
9578 // module instantiates the declaration of a class template specialization
9579 // and two or more other modules instantiate its definition.
9580 //
9581 // FIXME: Indicate which modules had instantiations of this definition.
9582 // FIXME: How can this even happen?
9583 Diag(Merge.first->getLocation(),
9584 diag::err_module_odr_violation_different_instantiations)
9585 << Merge.first;
9586 }
9587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009588}
9589
Richard Smithce18a182015-07-14 00:26:00 +00009590void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009591 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009592 ReadTimer->startTimer();
9593}
9594
Guy Benyei11169dd2012-12-18 14:30:41 +00009595void ASTReader::FinishedDeserializing() {
9596 assert(NumCurrentElementsDeserializing &&
9597 "FinishedDeserializing not paired with StartedDeserializing");
9598 if (NumCurrentElementsDeserializing == 1) {
9599 // We decrease NumCurrentElementsDeserializing only after pending actions
9600 // are finished, to avoid recursively re-calling finishPendingActions().
9601 finishPendingActions();
9602 }
9603 --NumCurrentElementsDeserializing;
9604
Richard Smitha0ce9c42014-07-29 23:23:27 +00009605 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009606 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009607 while (!PendingExceptionSpecUpdates.empty()) {
9608 auto Updates = std::move(PendingExceptionSpecUpdates);
9609 PendingExceptionSpecUpdates.clear();
9610 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009611 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009612 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009613 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009614 if (auto *Listener = Context.getASTMutationListener())
9615 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009616 for (auto *Redecl : Update.second->redecls())
9617 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009618 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009619 }
9620
Richard Smithce18a182015-07-14 00:26:00 +00009621 if (ReadTimer)
9622 ReadTimer->stopTimer();
9623
Richard Smith0f4e2c42015-08-06 04:23:48 +00009624 diagnoseOdrViolations();
9625
Richard Smith04d05b52014-03-23 00:27:18 +00009626 // We are not in recursive loading, so it's safe to pass the "interesting"
9627 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009628 if (Consumer)
9629 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009630 }
9631}
9632
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009633void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009634 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9635 // Remove any fake results before adding any real ones.
9636 auto It = PendingFakeLookupResults.find(II);
9637 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009638 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009639 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009640 // FIXME: this works around module+PCH performance issue.
9641 // Rather than erase the result from the map, which is O(n), just clear
9642 // the vector of NamedDecls.
9643 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009644 }
9645 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009646
9647 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9648 SemaObj->TUScope->AddDecl(D);
9649 } else if (SemaObj->TUScope) {
9650 // Adding the decl to IdResolver may have failed because it was already in
9651 // (even though it was not added in scope). If it is already in, make sure
9652 // it gets in the scope as well.
9653 if (std::find(SemaObj->IdResolver.begin(Name),
9654 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9655 SemaObj->TUScope->AddDecl(D);
9656 }
9657}
9658
David Blaikie61137e12017-01-05 18:23:18 +00009659ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9660 const PCHContainerReader &PCHContainerRdr,
9661 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9662 StringRef isysroot, bool DisableValidation,
9663 bool AllowASTWithCompilerErrors,
9664 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9665 bool UseGlobalIndex,
9666 std::unique_ptr<llvm::Timer> ReadTimer)
9667 : Listener(DisableValidation
9668 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9669 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009670 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009671 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00009672 Context(Context),
9673 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9674 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9675 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009676 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009677 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9678 AllowConfigurationMismatch(AllowConfigurationMismatch),
9679 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009680 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009681 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009682
9683 for (const auto &Ext : Extensions) {
9684 auto BlockName = Ext->getExtensionMetadata().BlockName;
9685 auto Known = ModuleFileExtensions.find(BlockName);
9686 if (Known != ModuleFileExtensions.end()) {
9687 Diags.Report(diag::warn_duplicate_module_file_extension)
9688 << BlockName;
9689 continue;
9690 }
9691
9692 ModuleFileExtensions.insert({BlockName, Ext});
9693 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009694}
9695
9696ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009697 if (OwnsDeserializationListener)
9698 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009699}
Richard Smith10379092016-05-06 23:14:07 +00009700
9701IdentifierResolver &ASTReader::getIdResolver() {
9702 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9703}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009704
9705unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9706 unsigned AbbrevID) {
9707 Idx = 0;
9708 Record.clear();
9709 return Cursor.readRecord(AbbrevID, Record);
9710}