blob: 74da6be206cdb66c1b0a9b0e736ccfc6c392f732 [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 Trieufa3d93a2017-01-31 01:44:15 +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"
40#include "clang/Basic/ObjCRuntime.h"
41#include "clang/Basic/OperatorKinds.h"
42#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Basic/TargetInfo.h"
47#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "clang/Basic/Version.h"
50#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000051#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "clang/Lex/HeaderSearch.h"
53#include "clang/Lex/HeaderSearchOptions.h"
54#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000055#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include "clang/Lex/PreprocessingRecord.h"
57#include "clang/Lex/Preprocessor.h"
58#include "clang/Lex/PreprocessorOptions.h"
59#include "clang/Sema/Scope.h"
60#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000061#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000062#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000063#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000064#include "clang/Serialization/ModuleManager.h"
65#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include "llvm/ADT/APFloat.h"
67#include "llvm/ADT/APInt.h"
68#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000069#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000070#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000071#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000072#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000073#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000074#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000075#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000076#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000077#include "llvm/Support/ErrorHandling.h"
78#include "llvm/Support/FileSystem.h"
79#include "llvm/Support/MemoryBuffer.h"
80#include "llvm/Support/Path.h"
81#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000082#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include <cassert>
85#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000086#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000087#include <cstring>
88#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000089#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000090#include <limits>
91#include <map>
92#include <memory>
93#include <new>
94#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000095#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000096#include <tuple>
97#include <utility>
98#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000099
100using namespace clang;
101using namespace clang::serialization;
102using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000103using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000104
Ben Langmuircb69b572014-03-07 06:40:32 +0000105//===----------------------------------------------------------------------===//
106// ChainedASTReaderListener implementation
107//===----------------------------------------------------------------------===//
108
109bool
110ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
111 return First->ReadFullVersionInformation(FullVersion) ||
112 Second->ReadFullVersionInformation(FullVersion);
113}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000114
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000115void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
116 First->ReadModuleName(ModuleName);
117 Second->ReadModuleName(ModuleName);
118}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000119
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000120void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
121 First->ReadModuleMapFile(ModuleMapPath);
122 Second->ReadModuleMapFile(ModuleMapPath);
123}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000125bool
126ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
127 bool Complain,
128 bool AllowCompatibleDifferences) {
129 return First->ReadLanguageOptions(LangOpts, Complain,
130 AllowCompatibleDifferences) ||
131 Second->ReadLanguageOptions(LangOpts, Complain,
132 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000133}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000134
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000135bool ChainedASTReaderListener::ReadTargetOptions(
136 const TargetOptions &TargetOpts, bool Complain,
137 bool AllowCompatibleDifferences) {
138 return First->ReadTargetOptions(TargetOpts, Complain,
139 AllowCompatibleDifferences) ||
140 Second->ReadTargetOptions(TargetOpts, Complain,
141 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000142}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000143
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000145 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000146 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
147 Second->ReadDiagnosticOptions(DiagOpts, Complain);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuircb69b572014-03-07 06:40:32 +0000150bool
151ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
152 bool Complain) {
153 return First->ReadFileSystemOptions(FSOpts, Complain) ||
154 Second->ReadFileSystemOptions(FSOpts, Complain);
155}
156
157bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000158 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
159 bool Complain) {
160 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
161 Complain) ||
162 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
163 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000165
Ben Langmuircb69b572014-03-07 06:40:32 +0000166bool ChainedASTReaderListener::ReadPreprocessorOptions(
167 const PreprocessorOptions &PPOpts, bool Complain,
168 std::string &SuggestedPredefines) {
169 return First->ReadPreprocessorOptions(PPOpts, Complain,
170 SuggestedPredefines) ||
171 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
172}
173void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
174 unsigned Value) {
175 First->ReadCounter(M, Value);
176 Second->ReadCounter(M, Value);
177}
178bool ChainedASTReaderListener::needsInputFileVisitation() {
179 return First->needsInputFileVisitation() ||
180 Second->needsInputFileVisitation();
181}
182bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
183 return First->needsSystemInputFileVisitation() ||
184 Second->needsSystemInputFileVisitation();
185}
Richard Smith216a3bd2015-08-13 17:57:10 +0000186void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
187 ModuleKind Kind) {
188 First->visitModuleFile(Filename, Kind);
189 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000190}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000191
Ben Langmuircb69b572014-03-07 06:40:32 +0000192bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000193 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000194 bool isOverridden,
195 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000196 bool Continue = false;
197 if (First->needsInputFileVisitation() &&
198 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000199 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
200 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000201 if (Second->needsInputFileVisitation() &&
202 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000203 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
204 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000205 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000206}
207
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000208void ChainedASTReaderListener::readModuleFileExtension(
209 const ModuleFileExtensionMetadata &Metadata) {
210 First->readModuleFileExtension(Metadata);
211 Second->readModuleFileExtension(Metadata);
212}
213
Guy Benyei11169dd2012-12-18 14:30:41 +0000214//===----------------------------------------------------------------------===//
215// PCH validator implementation
216//===----------------------------------------------------------------------===//
217
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000218ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000219
220/// \brief Compare the given set of language options against an existing set of
221/// language options.
222///
223/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000224/// \param AllowCompatibleDifferences If true, differences between compatible
225/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000226///
227/// \returns true if the languagae options mis-match, false otherwise.
228static bool checkLanguageOptions(const LangOptions &LangOpts,
229 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000230 DiagnosticsEngine *Diags,
231 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000232#define LANGOPT(Name, Bits, Default, Description) \
233 if (ExistingLangOpts.Name != LangOpts.Name) { \
234 if (Diags) \
235 Diags->Report(diag::err_pch_langopt_mismatch) \
236 << Description << LangOpts.Name << ExistingLangOpts.Name; \
237 return true; \
238 }
239
240#define VALUE_LANGOPT(Name, Bits, Default, Description) \
241 if (ExistingLangOpts.Name != LangOpts.Name) { \
242 if (Diags) \
243 Diags->Report(diag::err_pch_langopt_value_mismatch) \
244 << Description; \
245 return true; \
246 }
247
248#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
249 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
250 if (Diags) \
251 Diags->Report(diag::err_pch_langopt_value_mismatch) \
252 << Description; \
253 return true; \
254 }
255
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000256#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
257 if (!AllowCompatibleDifferences) \
258 LANGOPT(Name, Bits, Default, Description)
259
260#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
261 if (!AllowCompatibleDifferences) \
262 ENUM_LANGOPT(Name, Bits, Default, Description)
263
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000264#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
265 if (!AllowCompatibleDifferences) \
266 VALUE_LANGOPT(Name, Bits, Default, Description)
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#define BENIGN_LANGOPT(Name, Bits, Default, Description)
269#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000270#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#include "clang/Basic/LangOptions.def"
272
Ben Langmuircd98cb72015-06-23 18:20:18 +0000273 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
274 if (Diags)
275 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
276 return true;
277 }
278
Guy Benyei11169dd2012-12-18 14:30:41 +0000279 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
280 if (Diags)
281 Diags->Report(diag::err_pch_langopt_value_mismatch)
282 << "target Objective-C runtime";
283 return true;
284 }
285
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000286 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
287 LangOpts.CommentOpts.BlockCommandNames) {
288 if (Diags)
289 Diags->Report(diag::err_pch_langopt_value_mismatch)
290 << "block command names";
291 return true;
292 }
293
Guy Benyei11169dd2012-12-18 14:30:41 +0000294 return false;
295}
296
297/// \brief Compare the given set of target options against an existing set of
298/// target options.
299///
300/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
301///
302/// \returns true if the target options mis-match, false otherwise.
303static bool checkTargetOptions(const TargetOptions &TargetOpts,
304 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000305 DiagnosticsEngine *Diags,
306 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define CHECK_TARGET_OPT(Field, Name) \
308 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
309 if (Diags) \
310 Diags->Report(diag::err_pch_targetopt_mismatch) \
311 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
312 return true; \
313 }
314
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000315 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000318
319 // We can tolerate different CPUs in many cases, notably when one CPU
320 // supports a strict superset of another. When allowing compatible
321 // differences skip this check.
322 if (!AllowCompatibleDifferences)
323 CHECK_TARGET_OPT(CPU, "target CPU");
324
Guy Benyei11169dd2012-12-18 14:30:41 +0000325#undef CHECK_TARGET_OPT
326
327 // Compare feature sets.
328 SmallVector<StringRef, 4> ExistingFeatures(
329 ExistingTargetOpts.FeaturesAsWritten.begin(),
330 ExistingTargetOpts.FeaturesAsWritten.end());
331 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
332 TargetOpts.FeaturesAsWritten.end());
333 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
334 std::sort(ReadFeatures.begin(), ReadFeatures.end());
335
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000336 // We compute the set difference in both directions explicitly so that we can
337 // diagnose the differences differently.
338 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
339 std::set_difference(
340 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
341 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
342 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
343 ExistingFeatures.begin(), ExistingFeatures.end(),
344 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000345
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000346 // If we are allowing compatible differences and the read feature set is
347 // a strict subset of the existing feature set, there is nothing to diagnose.
348 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
349 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000350
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000351 if (Diags) {
352 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000353 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000354 << /* is-existing-feature */ false << Feature;
355 for (StringRef Feature : UnmatchedExistingFeatures)
356 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
357 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000358 }
359
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000360 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000361}
362
363bool
364PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000365 bool Complain,
366 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 const LangOptions &ExistingLangOpts = PP.getLangOpts();
368 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000369 Complain ? &Reader.Diags : nullptr,
370 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000371}
372
373bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000374 bool Complain,
375 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000376 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
377 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000378 Complain ? &Reader.Diags : nullptr,
379 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000380}
381
382namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000383
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
385 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000386 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
387 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000388
389} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000390
Ben Langmuirb92de022014-04-29 16:25:26 +0000391static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
392 DiagnosticsEngine &Diags,
393 bool Complain) {
394 typedef DiagnosticsEngine::Level Level;
395
396 // Check current mappings for new -Werror mappings, and the stored mappings
397 // for cases that were explicitly mapped to *not* be errors that are now
398 // errors because of options like -Werror.
399 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
400
401 for (DiagnosticsEngine *MappingSource : MappingSources) {
402 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
403 diag::kind DiagID = DiagIDMappingPair.first;
404 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
405 if (CurLevel < DiagnosticsEngine::Error)
406 continue; // not significant
407 Level StoredLevel =
408 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
409 if (StoredLevel < DiagnosticsEngine::Error) {
410 if (Complain)
411 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
412 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
413 return true;
414 }
415 }
416 }
417
418 return false;
419}
420
Alp Tokerac4e8e52014-06-22 21:58:33 +0000421static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
422 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
423 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
424 return true;
425 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000426}
427
428static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
429 DiagnosticsEngine &Diags,
430 bool IsSystem, bool Complain) {
431 // Top-level options
432 if (IsSystem) {
433 if (Diags.getSuppressSystemWarnings())
434 return false;
435 // If -Wsystem-headers was not enabled before, be conservative
436 if (StoredDiags.getSuppressSystemWarnings()) {
437 if (Complain)
438 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
439 return true;
440 }
441 }
442
443 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
444 if (Complain)
445 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
446 return true;
447 }
448
449 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
450 !StoredDiags.getEnableAllWarnings()) {
451 if (Complain)
452 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
453 return true;
454 }
455
456 if (isExtHandlingFromDiagsError(Diags) &&
457 !isExtHandlingFromDiagsError(StoredDiags)) {
458 if (Complain)
459 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
460 return true;
461 }
462
463 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
464}
465
466bool PCHValidator::ReadDiagnosticOptions(
467 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
468 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
469 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
470 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000471 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000472 // This should never fail, because we would have processed these options
473 // before writing them to an ASTFile.
474 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
475
476 ModuleManager &ModuleMgr = Reader.getModuleManager();
477 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
478
479 // If the original import came from a file explicitly generated by the user,
480 // don't check the diagnostic mappings.
481 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000482 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000483 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
484 // the transitive closure of its imports, since unrelated modules cannot be
485 // imported until after this module finishes validation.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000486 ModuleFile *TopImport = &*ModuleMgr.rbegin();
Ben Langmuirb92de022014-04-29 16:25:26 +0000487 while (!TopImport->ImportedBy.empty())
488 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000489 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000490 return false;
491
492 StringRef ModuleName = TopImport->ModuleName;
493 assert(!ModuleName.empty() && "diagnostic options read before module name");
494
495 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
496 assert(M && "missing module");
497
498 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
499 // contains the union of their flags.
500 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
501}
502
Guy Benyei11169dd2012-12-18 14:30:41 +0000503/// \brief Collect the macro definitions provided by the given preprocessor
504/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000505static void
506collectMacroDefinitions(const PreprocessorOptions &PPOpts,
507 MacroDefinitionsMap &Macros,
508 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
510 StringRef Macro = PPOpts.Macros[I].first;
511 bool IsUndef = PPOpts.Macros[I].second;
512
513 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
514 StringRef MacroName = MacroPair.first;
515 StringRef MacroBody = MacroPair.second;
516
517 // For an #undef'd macro, we only care about the name.
518 if (IsUndef) {
519 if (MacroNames && !Macros.count(MacroName))
520 MacroNames->push_back(MacroName);
521
522 Macros[MacroName] = std::make_pair("", true);
523 continue;
524 }
525
526 // For a #define'd macro, figure out the actual definition.
527 if (MacroName.size() == Macro.size())
528 MacroBody = "1";
529 else {
530 // Note: GCC drops anything following an end-of-line character.
531 StringRef::size_type End = MacroBody.find_first_of("\n\r");
532 MacroBody = MacroBody.substr(0, End);
533 }
534
535 if (MacroNames && !Macros.count(MacroName))
536 MacroNames->push_back(MacroName);
537 Macros[MacroName] = std::make_pair(MacroBody, false);
538 }
539}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000540
Guy Benyei11169dd2012-12-18 14:30:41 +0000541/// \brief Check the preprocessor options deserialized from the control block
542/// against the preprocessor options in an existing preprocessor.
543///
544/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000545/// \param Validate If true, validate preprocessor options. If false, allow
546/// macros defined by \p ExistingPPOpts to override those defined by
547/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000548static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
549 const PreprocessorOptions &ExistingPPOpts,
550 DiagnosticsEngine *Diags,
551 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000552 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000553 const LangOptions &LangOpts,
554 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Check macro definitions.
556 MacroDefinitionsMap ASTFileMacros;
557 collectMacroDefinitions(PPOpts, ASTFileMacros);
558 MacroDefinitionsMap ExistingMacros;
559 SmallVector<StringRef, 4> ExistingMacroNames;
560 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
561
562 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
563 // Dig out the macro definition in the existing preprocessor options.
564 StringRef MacroName = ExistingMacroNames[I];
565 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
566
567 // Check whether we know anything about this macro name or not.
568 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
569 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000570 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000571 // FIXME: Check whether this identifier was referenced anywhere in the
572 // AST file. If so, we should reject the AST file. Unfortunately, this
573 // information isn't in the control block. What shall we do about it?
574
575 if (Existing.second) {
576 SuggestedPredefines += "#undef ";
577 SuggestedPredefines += MacroName.str();
578 SuggestedPredefines += '\n';
579 } else {
580 SuggestedPredefines += "#define ";
581 SuggestedPredefines += MacroName.str();
582 SuggestedPredefines += ' ';
583 SuggestedPredefines += Existing.first.str();
584 SuggestedPredefines += '\n';
585 }
586 continue;
587 }
588
589 // If the macro was defined in one but undef'd in the other, we have a
590 // conflict.
591 if (Existing.second != Known->second.second) {
592 if (Diags) {
593 Diags->Report(diag::err_pch_macro_def_undef)
594 << MacroName << Known->second.second;
595 }
596 return true;
597 }
598
599 // If the macro was #undef'd in both, or if the macro bodies are identical,
600 // it's fine.
601 if (Existing.second || Existing.first == Known->second.first)
602 continue;
603
604 // The macro bodies differ; complain.
605 if (Diags) {
606 Diags->Report(diag::err_pch_macro_def_conflict)
607 << MacroName << Known->second.first << Existing.first;
608 }
609 return true;
610 }
611
612 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000613 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000614 if (Diags) {
615 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
616 }
617 return true;
618 }
619
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000620 // Detailed record is important since it is used for the module cache hash.
621 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000622 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000623 if (Diags) {
624 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
625 }
626 return true;
627 }
628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 // Compute the #include and #include_macros lines we need.
630 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
631 StringRef File = ExistingPPOpts.Includes[I];
632 if (File == ExistingPPOpts.ImplicitPCHInclude)
633 continue;
634
635 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
636 != PPOpts.Includes.end())
637 continue;
638
639 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000640 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 SuggestedPredefines += "\"\n";
642 }
643
644 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
645 StringRef File = ExistingPPOpts.MacroIncludes[I];
646 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
647 File)
648 != PPOpts.MacroIncludes.end())
649 continue;
650
651 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000652 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 SuggestedPredefines += "\"\n##\n";
654 }
655
656 return false;
657}
658
659bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
660 bool Complain,
661 std::string &SuggestedPredefines) {
662 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
663
664 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000665 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000667 SuggestedPredefines,
668 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000669}
670
Yaxun Liu43712e02016-09-07 18:40:20 +0000671bool SimpleASTReaderListener::ReadPreprocessorOptions(
672 const PreprocessorOptions &PPOpts,
673 bool Complain,
674 std::string &SuggestedPredefines) {
675 return checkPreprocessorOptions(PPOpts,
676 PP.getPreprocessorOpts(),
677 nullptr,
678 PP.getFileManager(),
679 SuggestedPredefines,
680 PP.getLangOpts(),
681 false);
682}
683
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000684/// Check the header search options deserialized from the control block
685/// against the header search options in an existing preprocessor.
686///
687/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
688static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
689 StringRef SpecificModuleCachePath,
690 StringRef ExistingModuleCachePath,
691 DiagnosticsEngine *Diags,
692 const LangOptions &LangOpts) {
693 if (LangOpts.Modules) {
694 if (SpecificModuleCachePath != ExistingModuleCachePath) {
695 if (Diags)
696 Diags->Report(diag::err_pch_modulecache_mismatch)
697 << SpecificModuleCachePath << ExistingModuleCachePath;
698 return true;
699 }
700 }
701
702 return false;
703}
704
705bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
706 StringRef SpecificModuleCachePath,
707 bool Complain) {
708 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
709 PP.getHeaderSearchInfo().getModuleCachePath(),
710 Complain ? &Reader.Diags : nullptr,
711 PP.getLangOpts());
712}
713
Guy Benyei11169dd2012-12-18 14:30:41 +0000714void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
715 PP.setCounterValue(Value);
716}
717
718//===----------------------------------------------------------------------===//
719// AST reader implementation
720//===----------------------------------------------------------------------===//
721
Nico Weber824285e2014-05-08 04:26:47 +0000722void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
723 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000725 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000726}
727
Guy Benyei11169dd2012-12-18 14:30:41 +0000728unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
729 return serialization::ComputeHash(Sel);
730}
731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732std::pair<unsigned, unsigned>
733ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000734 using namespace llvm::support;
735 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
736 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 return std::make_pair(KeyLen, DataLen);
738}
739
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000740ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000741ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000742 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000744 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
745 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
746 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 if (N == 0)
748 return SelTable.getNullarySelector(FirstII);
749 else if (N == 1)
750 return SelTable.getUnarySelector(FirstII);
751
752 SmallVector<IdentifierInfo *, 16> Args;
753 Args.push_back(FirstII);
754 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000755 Args.push_back(Reader.getLocalIdentifier(
756 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000757
758 return SelTable.getSelector(N, Args.data());
759}
760
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000761ASTSelectorLookupTrait::data_type
762ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000764 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000765
766 data_type Result;
767
Justin Bogner57ba0b22014-03-28 22:03:24 +0000768 Result.ID = Reader.getGlobalSelectorID(
769 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000770 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
772 Result.InstanceBits = FullInstanceBits & 0x3;
773 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
774 Result.FactoryBits = FullFactoryBits & 0x3;
775 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
776 unsigned NumInstanceMethods = FullInstanceBits >> 3;
777 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000778
779 // Load instance methods
780 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000781 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
782 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000783 Result.Instance.push_back(Method);
784 }
785
786 // Load factory methods
787 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000788 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
789 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 Result.Factory.push_back(Method);
791 }
792
793 return Result;
794}
795
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000796unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
797 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000798}
799
800std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000801ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000802 using namespace llvm::support;
803 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
804 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 return std::make_pair(KeyLen, DataLen);
806}
807
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000808ASTIdentifierLookupTraitBase::internal_key_type
809ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000811 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000812}
813
Douglas Gregordcf25082013-02-11 18:16:18 +0000814/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000815static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
816 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000817 return II.hadMacroDefinition() ||
818 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000819 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000820 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000821 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
822 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000823}
824
Richard Smith76c2f2c2015-07-17 20:09:43 +0000825static bool readBit(unsigned &Bits) {
826 bool Value = Bits & 0x1;
827 Bits >>= 1;
828 return Value;
829}
830
Richard Smith79bf9202015-08-24 03:33:22 +0000831IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
832 using namespace llvm::support;
833 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
834 return Reader.getGlobalIdentifierID(F, RawID >> 1);
835}
836
Richard Smitheb4b58f62016-02-05 01:40:54 +0000837static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
838 if (!II.isFromAST()) {
839 II.setIsFromAST();
840 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
841 if (isInterestingIdentifier(Reader, II, IsModule))
842 II.setChangedSinceDeserialization();
843 }
844}
845
Guy Benyei11169dd2012-12-18 14:30:41 +0000846IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
847 const unsigned char* d,
848 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000849 using namespace llvm::support;
850 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 bool IsInteresting = RawID & 0x01;
852
853 // Wipe out the "is interesting" bit.
854 RawID = RawID >> 1;
855
Richard Smith76c2f2c2015-07-17 20:09:43 +0000856 // Build the IdentifierInfo and link the identifier ID with it.
857 IdentifierInfo *II = KnownII;
858 if (!II) {
859 II = &Reader.getIdentifierTable().getOwn(k);
860 KnownII = II;
861 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000862 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000863 Reader.markIdentifierUpToDate(II);
864
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
866 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000867 // For uninteresting identifiers, there's nothing else to do. Just notify
868 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 return II;
871 }
872
Justin Bogner57ba0b22014-03-28 22:03:24 +0000873 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
874 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000875 bool CPlusPlusOperatorKeyword = readBit(Bits);
876 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000877 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000878 bool Poisoned = readBit(Bits);
879 bool ExtensionToken = readBit(Bits);
880 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000881
882 assert(Bits == 0 && "Extra bits in the identifier?");
883 DataLen -= 8;
884
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 // Set or check the various bits in the IdentifierInfo structure.
886 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000887 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000888 II->revertTokenIDToIdentifier();
889 if (!F.isModule())
890 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
891 else if (HasRevertedBuiltin && II->getBuiltinID()) {
892 II->revertBuiltin();
893 assert((II->hasRevertedBuiltin() ||
894 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
895 "Incorrect ObjC keyword or builtin ID");
896 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 assert(II->isExtensionToken() == ExtensionToken &&
898 "Incorrect extension token flag");
899 (void)ExtensionToken;
900 if (Poisoned)
901 II->setIsPoisoned(true);
902 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
903 "Incorrect C++ operator keyword flag");
904 (void)CPlusPlusOperatorKeyword;
905
906 // If this identifier is a macro, deserialize the macro
907 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000908 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 uint32_t MacroDirectivesOffset =
910 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000911 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000912
Richard Smithd7329392015-04-21 21:46:32 +0000913 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 }
915
916 Reader.SetIdentifierInfo(ID, II);
917
918 // Read all of the declarations visible at global scope with this
919 // name.
920 if (DataLen > 0) {
921 SmallVector<uint32_t, 4> DeclIDs;
922 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 DeclIDs.push_back(Reader.getGlobalDeclID(
924 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 Reader.SetGloballyVisibleDecls(II, DeclIDs);
926 }
927
928 return II;
929}
930
Richard Smitha06c7e62015-08-26 23:55:49 +0000931DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
932 : Kind(Name.getNameKind()) {
933 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000935 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 break;
937 case DeclarationName::ObjCZeroArgSelector:
938 case DeclarationName::ObjCOneArgSelector:
939 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000940 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 break;
942 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 Data = Name.getCXXOverloadedOperator();
944 break;
945 case DeclarationName::CXXLiteralOperatorName:
946 Data = (uint64_t)Name.getCXXLiteralIdentifier();
947 break;
948 case DeclarationName::CXXConstructorName:
949 case DeclarationName::CXXDestructorName:
950 case DeclarationName::CXXConversionFunctionName:
951 case DeclarationName::CXXUsingDirective:
952 Data = 0;
953 break;
954 }
955}
956
957unsigned DeclarationNameKey::getHash() const {
958 llvm::FoldingSetNodeID ID;
959 ID.AddInteger(Kind);
960
961 switch (Kind) {
962 case DeclarationName::Identifier:
963 case DeclarationName::CXXLiteralOperatorName:
964 ID.AddString(((IdentifierInfo*)Data)->getName());
965 break;
966 case DeclarationName::ObjCZeroArgSelector:
967 case DeclarationName::ObjCOneArgSelector:
968 case DeclarationName::ObjCMultiArgSelector:
969 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
970 break;
971 case DeclarationName::CXXOperatorName:
972 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 break;
974 case DeclarationName::CXXConstructorName:
975 case DeclarationName::CXXDestructorName:
976 case DeclarationName::CXXConversionFunctionName:
977 case DeclarationName::CXXUsingDirective:
978 break;
979 }
980
981 return ID.ComputeHash();
982}
983
Richard Smithd88a7f12015-09-01 20:35:42 +0000984ModuleFile *
985ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
986 using namespace llvm::support;
987 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
988 return Reader.getLocalModuleFile(F, ModuleFileID);
989}
990
Guy Benyei11169dd2012-12-18 14:30:41 +0000991std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000992ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000993 using namespace llvm::support;
994 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
995 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000996 return std::make_pair(KeyLen, DataLen);
997}
998
Richard Smitha06c7e62015-08-26 23:55:49 +0000999ASTDeclContextNameLookupTrait::internal_key_type
1000ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001001 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001002
Richard Smitha06c7e62015-08-26 23:55:49 +00001003 auto Kind = (DeclarationName::NameKind)*d++;
1004 uint64_t Data;
1005 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001006 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001007 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001008 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 break;
1010 case DeclarationName::ObjCZeroArgSelector:
1011 case DeclarationName::ObjCOneArgSelector:
1012 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001013 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 (uint64_t)Reader.getLocalSelector(
1015 F, endian::readNext<uint32_t, little, unaligned>(
1016 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001017 break;
1018 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 break;
1021 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001022 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001023 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 break;
1025 case DeclarationName::CXXConstructorName:
1026 case DeclarationName::CXXDestructorName:
1027 case DeclarationName::CXXConversionFunctionName:
1028 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001029 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 break;
1031 }
1032
Richard Smitha06c7e62015-08-26 23:55:49 +00001033 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034}
1035
Richard Smithd88a7f12015-09-01 20:35:42 +00001036void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1037 const unsigned char *d,
1038 unsigned DataLen,
1039 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001040 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001041 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1042 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1043 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1044 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001045}
1046
Richard Smith0f4e2c42015-08-06 04:23:48 +00001047bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1048 BitstreamCursor &Cursor,
1049 uint64_t Offset,
1050 DeclContext *DC) {
1051 assert(Offset != 0);
1052
Guy Benyei11169dd2012-12-18 14:30:41 +00001053 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001054 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
Richard Smith0f4e2c42015-08-06 04:23:48 +00001056 RecordData Record;
1057 StringRef Blob;
1058 unsigned Code = Cursor.ReadCode();
1059 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1060 if (RecCode != DECL_CONTEXT_LEXICAL) {
1061 Error("Expected lexical block");
1062 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 }
1064
Richard Smith82f8fcd2015-08-06 22:07:25 +00001065 assert(!isa<TranslationUnitDecl>(DC) &&
1066 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001067 // If we are handling a C++ class template instantiation, we can see multiple
1068 // lexical updates for the same record. It's important that we select only one
1069 // of them, so that field numbering works properly. Just pick the first one we
1070 // see.
1071 auto &Lex = LexicalDecls[DC];
1072 if (!Lex.first) {
1073 Lex = std::make_pair(
1074 &M, llvm::makeArrayRef(
1075 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1076 Blob.data()),
1077 Blob.size() / 4));
1078 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001079 DC->setHasExternalLexicalStorage(true);
1080 return false;
1081}
Guy Benyei11169dd2012-12-18 14:30:41 +00001082
Richard Smith0f4e2c42015-08-06 04:23:48 +00001083bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1084 BitstreamCursor &Cursor,
1085 uint64_t Offset,
1086 DeclID ID) {
1087 assert(Offset != 0);
1088
1089 SavedStreamPosition SavedPosition(Cursor);
1090 Cursor.JumpToBit(Offset);
1091
1092 RecordData Record;
1093 StringRef Blob;
1094 unsigned Code = Cursor.ReadCode();
1095 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1096 if (RecCode != DECL_CONTEXT_VISIBLE) {
1097 Error("Expected visible lookup table block");
1098 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 }
1100
Richard Smith0f4e2c42015-08-06 04:23:48 +00001101 // We can't safely determine the primary context yet, so delay attaching the
1102 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001103 auto *Data = (const unsigned char*)Blob.data();
1104 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 return false;
1106}
1107
1108void ASTReader::Error(StringRef Msg) {
1109 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001110 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1111 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001112 Diag(diag::note_module_cache_path)
1113 << PP.getHeaderSearchInfo().getModuleCachePath();
1114 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001115}
1116
1117void ASTReader::Error(unsigned DiagID,
1118 StringRef Arg1, StringRef Arg2) {
1119 if (Diags.isDiagnosticInFlight())
1120 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1121 else
1122 Diag(DiagID) << Arg1 << Arg2;
1123}
1124
1125//===----------------------------------------------------------------------===//
1126// Source Manager Deserialization
1127//===----------------------------------------------------------------------===//
1128
1129/// \brief Read the line table in the source manager block.
1130/// \returns true if there was an error.
1131bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001132 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 unsigned Idx = 0;
1134 LineTableInfo &LineTable = SourceMgr.getLineTable();
1135
1136 // Parse the file names
1137 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001138 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001140 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1142 }
Richard Smith63078492015-09-01 07:41:55 +00001143 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144
1145 // Parse the line entries
1146 std::vector<LineEntry> Entries;
1147 while (Idx < Record.size()) {
1148 int FID = Record[Idx++];
1149 assert(FID >= 0 && "Serialized line entries for non-local file.");
1150 // Remap FileID from 1-based old view.
1151 FID += F.SLocEntryBaseID - 1;
1152
1153 // Extract the line entries
1154 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001155 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001156 Entries.clear();
1157 Entries.reserve(NumEntries);
1158 for (unsigned I = 0; I != NumEntries; ++I) {
1159 unsigned FileOffset = Record[Idx++];
1160 unsigned LineNo = Record[Idx++];
1161 int FilenameID = FileIDs[Record[Idx++]];
1162 SrcMgr::CharacteristicKind FileKind
1163 = (SrcMgr::CharacteristicKind)Record[Idx++];
1164 unsigned IncludeOffset = Record[Idx++];
1165 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1166 FileKind, IncludeOffset));
1167 }
1168 LineTable.AddEntry(FileID::get(FID), Entries);
1169 }
1170
1171 return false;
1172}
1173
1174/// \brief Read a source manager block
1175bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1176 using namespace SrcMgr;
1177
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001178 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001179
1180 // Set the source-location entry cursor to the current position in
1181 // the stream. This cursor will be used to read the contents of the
1182 // source manager block initially, and then lazily read
1183 // source-location entries as needed.
1184 SLocEntryCursor = F.Stream;
1185
1186 // The stream itself is going to skip over the source manager block.
1187 if (F.Stream.SkipBlock()) {
1188 Error("malformed block record in AST file");
1189 return true;
1190 }
1191
1192 // Enter the source manager block.
1193 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1194 Error("malformed source manager block record in AST file");
1195 return true;
1196 }
1197
1198 RecordData Record;
1199 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001200 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001201
Chris Lattnere7b154b2013-01-19 21:39:22 +00001202 switch (E.Kind) {
1203 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1204 case llvm::BitstreamEntry::Error:
1205 Error("malformed block record in AST file");
1206 return true;
1207 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001208 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001209 case llvm::BitstreamEntry::Record:
1210 // The interesting case.
1211 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001213
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001216 StringRef Blob;
1217 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 default: // Default behavior: ignore.
1219 break;
1220
1221 case SM_SLOC_FILE_ENTRY:
1222 case SM_SLOC_BUFFER_ENTRY:
1223 case SM_SLOC_EXPANSION_ENTRY:
1224 // Once we hit one of the source location entries, we're done.
1225 return false;
1226 }
1227 }
1228}
1229
1230/// \brief If a header file is not found at the path that we expect it to be
1231/// and the PCH file was moved from its original location, try to resolve the
1232/// file by assuming that header+PCH were moved together and the header is in
1233/// the same place relative to the PCH.
1234static std::string
1235resolveFileRelativeToOriginalDir(const std::string &Filename,
1236 const std::string &OriginalDir,
1237 const std::string &CurrDir) {
1238 assert(OriginalDir != CurrDir &&
1239 "No point trying to resolve the file if the PCH dir didn't change");
1240 using namespace llvm::sys;
1241 SmallString<128> filePath(Filename);
1242 fs::make_absolute(filePath);
1243 assert(path::is_absolute(OriginalDir));
1244 SmallString<128> currPCHPath(CurrDir);
1245
1246 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1247 fileDirE = path::end(path::parent_path(filePath));
1248 path::const_iterator origDirI = path::begin(OriginalDir),
1249 origDirE = path::end(OriginalDir);
1250 // Skip the common path components from filePath and OriginalDir.
1251 while (fileDirI != fileDirE && origDirI != origDirE &&
1252 *fileDirI == *origDirI) {
1253 ++fileDirI;
1254 ++origDirI;
1255 }
1256 for (; origDirI != origDirE; ++origDirI)
1257 path::append(currPCHPath, "..");
1258 path::append(currPCHPath, fileDirI, fileDirE);
1259 path::append(currPCHPath, path::filename(Filename));
1260 return currPCHPath.str();
1261}
1262
1263bool ASTReader::ReadSLocEntry(int ID) {
1264 if (ID == 0)
1265 return false;
1266
1267 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1268 Error("source location entry ID out-of-range for AST file");
1269 return true;
1270 }
1271
Richard Smithaada85c2016-02-06 02:06:43 +00001272 // Local helper to read the (possibly-compressed) buffer data following the
1273 // entry record.
1274 auto ReadBuffer = [this](
1275 BitstreamCursor &SLocEntryCursor,
1276 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1277 RecordData Record;
1278 StringRef Blob;
1279 unsigned Code = SLocEntryCursor.ReadCode();
1280 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1281
1282 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001283 if (!llvm::zlib::isAvailable()) {
1284 Error("zlib is not available");
1285 return nullptr;
1286 }
Richard Smithaada85c2016-02-06 02:06:43 +00001287 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001288 if (llvm::Error E =
1289 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1290 Error("could not decompress embedded file contents: " +
1291 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001292 return nullptr;
1293 }
1294 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1295 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1296 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1297 } else {
1298 Error("AST record has invalid code");
1299 return nullptr;
1300 }
1301 };
1302
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1304 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001305 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 unsigned BaseOffset = F->SLocEntryBaseOffset;
1307
1308 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001309 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1310 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 Error("incorrectly-formatted source location entry in AST file");
1312 return true;
1313 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001314
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001316 StringRef Blob;
1317 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 default:
1319 Error("incorrectly-formatted source location entry in AST file");
1320 return true;
1321
1322 case SM_SLOC_FILE_ENTRY: {
1323 // We will detect whether a file changed and return 'Failure' for it, but
1324 // we will also try to fail gracefully by setting up the SLocEntry.
1325 unsigned InputID = Record[4];
1326 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001327 const FileEntry *File = IF.getFile();
1328 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001329
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001330 // Note that we only check if a File was returned. If it was out-of-date
1331 // we have complained but we will continue creating a FileID to recover
1332 // gracefully.
1333 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001334 return true;
1335
1336 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1337 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1338 // This is the module's main file.
1339 IncludeLoc = getImportLocation(F);
1340 }
1341 SrcMgr::CharacteristicKind
1342 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1343 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1344 ID, BaseOffset + Record[0]);
1345 SrcMgr::FileInfo &FileInfo =
1346 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1347 FileInfo.NumCreatedFIDs = Record[5];
1348 if (Record[3])
1349 FileInfo.setHasLineDirectives();
1350
1351 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1352 unsigned NumFileDecls = Record[7];
1353 if (NumFileDecls) {
1354 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1355 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1356 NumFileDecls));
1357 }
Richard Smithaada85c2016-02-06 02:06:43 +00001358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 const SrcMgr::ContentCache *ContentCache
1360 = SourceMgr.getOrCreateContentCache(File,
1361 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1362 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001363 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1364 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001365 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1366 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001367 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001368 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 }
1370
1371 break;
1372 }
1373
1374 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001375 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 unsigned Offset = Record[0];
1377 SrcMgr::CharacteristicKind
1378 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1379 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001380 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 IncludeLoc = getImportLocation(F);
1382 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001383
Richard Smithaada85c2016-02-06 02:06:43 +00001384 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1385 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001387 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001388 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 break;
1390 }
1391
1392 case SM_SLOC_EXPANSION_ENTRY: {
1393 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1394 SourceMgr.createExpansionLoc(SpellingLoc,
1395 ReadSourceLocation(*F, Record[2]),
1396 ReadSourceLocation(*F, Record[3]),
1397 Record[4],
1398 ID,
1399 BaseOffset + Record[0]);
1400 break;
1401 }
1402 }
1403
1404 return false;
1405}
1406
1407std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1408 if (ID == 0)
1409 return std::make_pair(SourceLocation(), "");
1410
1411 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1412 Error("source location entry ID out-of-range for AST file");
1413 return std::make_pair(SourceLocation(), "");
1414 }
1415
1416 // Find which module file this entry lands in.
1417 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001418 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001419 return std::make_pair(SourceLocation(), "");
1420
1421 // FIXME: Can we map this down to a particular submodule? That would be
1422 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001423 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001424}
1425
1426/// \brief Find the location where the module F is imported.
1427SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1428 if (F->ImportLoc.isValid())
1429 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001430
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 // Otherwise we have a PCH. It's considered to be "imported" at the first
1432 // location of its includer.
1433 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001434 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001435 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001436 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 return F->ImportedBy[0]->FirstLoc;
1439}
1440
1441/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1442/// specified cursor. Read the abbreviations that are at the top of the block
1443/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001444bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001445 if (Cursor.EnterSubBlock(BlockID))
1446 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
1448 while (true) {
1449 uint64_t Offset = Cursor.GetCurrentBitNo();
1450 unsigned Code = Cursor.ReadCode();
1451
1452 // We expect all abbrevs to be at the start of the block.
1453 if (Code != llvm::bitc::DEFINE_ABBREV) {
1454 Cursor.JumpToBit(Offset);
1455 return false;
1456 }
1457 Cursor.ReadAbbrevRecord();
1458 }
1459}
1460
Richard Smithe40f2ba2013-08-07 21:41:30 +00001461Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001462 unsigned &Idx) {
1463 Token Tok;
1464 Tok.startToken();
1465 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1466 Tok.setLength(Record[Idx++]);
1467 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1468 Tok.setIdentifierInfo(II);
1469 Tok.setKind((tok::TokenKind)Record[Idx++]);
1470 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1471 return Tok;
1472}
1473
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001474MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001475 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001476
1477 // Keep track of where we are in the stream, then jump back there
1478 // after reading this macro.
1479 SavedStreamPosition SavedPosition(Stream);
1480
1481 Stream.JumpToBit(Offset);
1482 RecordData Record;
1483 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001484 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001485
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001487 // Advance to the next record, but if we get to the end of the block, don't
1488 // pop it (removing all the abbreviations from the cursor) since we want to
1489 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001490 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001491 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001492
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 switch (Entry.Kind) {
1494 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1495 case llvm::BitstreamEntry::Error:
1496 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001497 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001498 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001499 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001500 case llvm::BitstreamEntry::Record:
1501 // The interesting case.
1502 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001503 }
1504
1505 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 Record.clear();
1507 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001508 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001510 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001511 case PP_MACRO_DIRECTIVE_HISTORY:
1512 return Macro;
1513
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 case PP_MACRO_OBJECT_LIKE:
1515 case PP_MACRO_FUNCTION_LIKE: {
1516 // If we already have a macro, that means that we've hit the end
1517 // of the definition of the macro we were looking for. We're
1518 // done.
1519 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001520 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001521
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001522 unsigned NextIndex = 1; // Skip identifier ID.
1523 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001525 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001526 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001528 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001529
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1531 // Decode function-like macro info.
1532 bool isC99VarArgs = Record[NextIndex++];
1533 bool isGNUVarArgs = Record[NextIndex++];
1534 bool hasCommaPasting = Record[NextIndex++];
1535 MacroArgs.clear();
1536 unsigned NumArgs = Record[NextIndex++];
1537 for (unsigned i = 0; i != NumArgs; ++i)
1538 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1539
1540 // Install function-like macro info.
1541 MI->setIsFunctionLike();
1542 if (isC99VarArgs) MI->setIsC99Varargs();
1543 if (isGNUVarArgs) MI->setIsGNUVarargs();
1544 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001545 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 }
1547
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 // Remember that we saw this macro last so that we add the tokens that
1549 // form its body to it.
1550 Macro = MI;
1551
1552 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1553 Record[NextIndex]) {
1554 // We have a macro definition. Register the association
1555 PreprocessedEntityID
1556 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1557 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001558 PreprocessingRecord::PPEntityID PPID =
1559 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1560 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1561 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001562 if (PPDef)
1563 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 }
1565
1566 ++NumMacrosRead;
1567 break;
1568 }
1569
1570 case PP_TOKEN: {
1571 // If we see a TOKEN before a PP_MACRO_*, then the file is
1572 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001573 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001574
John McCallf413f5e2013-05-03 00:10:13 +00001575 unsigned Idx = 0;
1576 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001577 Macro->AddTokenToBody(Tok);
1578 break;
1579 }
1580 }
1581 }
1582}
1583
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001584PreprocessedEntityID
Guy Benyei11169dd2012-12-18 14:30:41 +00001585ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001586 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001588 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001590
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 return LocalID + I->second;
1592}
1593
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001594unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1595 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001596}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001597
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001598HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001599HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001600 internal_key_type ikey = {FE->getSize(),
1601 M.HasTimestamps ? FE->getModificationTime() : 0,
1602 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001603 return ikey;
1604}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001605
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001606bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001607 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001608 return false;
1609
Mehdi Amini004b9c72016-10-10 22:52:47 +00001610 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001611 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001612
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001614 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001615 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1616 if (!Key.Imported)
1617 return FileMgr.getFile(Key.Filename);
1618
1619 std::string Resolved = Key.Filename;
1620 Reader.ResolveImportedPath(M, Resolved);
1621 return FileMgr.getFile(Resolved);
1622 };
1623
1624 const FileEntry *FEA = GetFile(a);
1625 const FileEntry *FEB = GetFile(b);
1626 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001627}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001628
Guy Benyei11169dd2012-12-18 14:30:41 +00001629std::pair<unsigned, unsigned>
1630HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001631 using namespace llvm::support;
1632 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001634 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001635}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636
1637HeaderFileInfoTrait::internal_key_type
1638HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001639 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001640 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001641 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1642 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001643 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001644 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001645 return ikey;
1646}
1647
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001648HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001649HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 unsigned DataLen) {
1651 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001652 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 HeaderFileInfo HFI;
1654 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001655 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1656 HFI.isImport |= (Flags >> 4) & 0x01;
1657 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1658 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001660 // FIXME: Find a better way to handle this. Maybe just store a
1661 // "has been included" flag?
1662 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1663 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001664 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1665 M, endian::readNext<uint32_t, little, unaligned>(d));
1666 if (unsigned FrameworkOffset =
1667 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001668 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 // since 0 is used as an indicator for "no framework name".
1670 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1671 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1672 }
Richard Smith386bb072015-08-18 23:42:23 +00001673
1674 assert((End - d) % 4 == 0 &&
1675 "Wrong data length in HeaderFileInfo deserialization");
1676 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001677 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001678 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1679 LocalSMID >>= 2;
1680
1681 // This header is part of a module. Associate it with the module to enable
1682 // implicit module import.
1683 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1684 Module *Mod = Reader.getSubmodule(GlobalSMID);
1685 FileManager &FileMgr = Reader.getFileManager();
1686 ModuleMap &ModMap =
1687 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1688
1689 std::string Filename = key.Filename;
1690 if (key.Imported)
1691 Reader.ResolveImportedPath(M, Filename);
1692 // FIXME: This is not always the right filename-as-written, but we're not
1693 // going to use this information to rebuild the module, so it doesn't make
1694 // a lot of difference.
1695 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001696 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1697 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001698 }
1699
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 // This HeaderFileInfo was externally loaded.
1701 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001702 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 return HFI;
1704}
1705
Richard Smithd7329392015-04-21 21:46:32 +00001706void ASTReader::addPendingMacro(IdentifierInfo *II,
1707 ModuleFile *M,
1708 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001709 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1710 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001711}
1712
1713void ASTReader::ReadDefinedMacros() {
1714 // Note that we are loading defined macros.
1715 Deserializing Macros(this);
1716
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001717 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1718 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001719
1720 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001721 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 continue;
1723
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001724 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001725 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001726
1727 RecordData Record;
1728 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001729 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001730
Chris Lattnere7b154b2013-01-19 21:39:22 +00001731 switch (E.Kind) {
1732 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1733 case llvm::BitstreamEntry::Error:
1734 Error("malformed block record in AST file");
1735 return;
1736 case llvm::BitstreamEntry::EndBlock:
1737 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001738
Chris Lattnere7b154b2013-01-19 21:39:22 +00001739 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001740 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001741 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001742 default: // Default behavior: ignore.
1743 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001744
Chris Lattnere7b154b2013-01-19 21:39:22 +00001745 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001746 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001747 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001748 if (II->isOutOfDate())
1749 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001750 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001751 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001752
Chris Lattnere7b154b2013-01-19 21:39:22 +00001753 case PP_TOKEN:
1754 // Ignore tokens.
1755 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001757 break;
1758 }
1759 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001760 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001761 }
1762}
1763
1764namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001765
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 /// \brief Visitor class used to look up identifirs in an AST file.
1767 class IdentifierLookupVisitor {
1768 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001769 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001770 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001771 unsigned &NumIdentifierLookups;
1772 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001773 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001774
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001776 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1777 unsigned &NumIdentifierLookups,
1778 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001779 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1780 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001781 NumIdentifierLookups(NumIdentifierLookups),
1782 NumIdentifierLookupHits(NumIdentifierLookupHits),
1783 Found()
1784 {
1785 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001786
1787 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001788 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001789 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001791
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 ASTIdentifierLookupTable *IdTable
1793 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1794 if (!IdTable)
1795 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001796
1797 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001798 Found);
1799 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001800 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001801 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001802 if (Pos == IdTable->end())
1803 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001804
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 // Dereferencing the iterator has the effect of building the
1806 // IdentifierInfo node and populating it with the various
1807 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001808 ++NumIdentifierLookupHits;
1809 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 return true;
1811 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001812
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 // \brief Retrieve the identifier info found within the module
1814 // files.
1815 IdentifierInfo *getIdentifierInfo() const { return Found; }
1816 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001817
1818} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001819
1820void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1821 // Note that we are loading an identifier.
1822 Deserializing AnIdentifier(this);
1823
1824 unsigned PriorGeneration = 0;
1825 if (getContext().getLangOpts().Modules)
1826 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001827
1828 // If there is a global index, look there first to determine which modules
1829 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001830 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001831 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001832 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001833 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1834 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001835 }
1836 }
1837
Douglas Gregor7211ac12013-01-25 23:32:03 +00001838 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001839 NumIdentifierLookups,
1840 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001841 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 markIdentifierUpToDate(&II);
1843}
1844
1845void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1846 if (!II)
1847 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001848
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 II->setOutOfDate(false);
1850
1851 // Update the generation for this identifier.
1852 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001853 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001854}
1855
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001856void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1857 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001858 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001859
1860 BitstreamCursor &Cursor = M.MacroCursor;
1861 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001862 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863
Richard Smith713369b2015-04-23 20:40:50 +00001864 struct ModuleMacroRecord {
1865 SubmoduleID SubModID;
1866 MacroInfo *MI;
1867 SmallVector<SubmoduleID, 8> Overrides;
1868 };
1869 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001870
Richard Smithd7329392015-04-21 21:46:32 +00001871 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1872 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1873 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001874 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001875 while (true) {
1876 llvm::BitstreamEntry Entry =
1877 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1878 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1879 Error("malformed block record in AST file");
1880 return;
1881 }
1882
1883 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001884 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001885 case PP_MACRO_DIRECTIVE_HISTORY:
1886 break;
1887
1888 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001889 ModuleMacros.push_back(ModuleMacroRecord());
1890 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001891 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1892 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001893 for (int I = 2, N = Record.size(); I != N; ++I)
1894 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001895 continue;
1896 }
1897
1898 default:
1899 Error("malformed block record in AST file");
1900 return;
1901 }
1902
1903 // We found the macro directive history; that's the last record
1904 // for this macro.
1905 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001906 }
1907
Richard Smithd7329392015-04-21 21:46:32 +00001908 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001909 {
1910 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001911 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001912 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001913 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001914 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001915 Module *Mod = getSubmodule(ModID);
1916 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001917 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001918 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001919 }
1920
1921 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001922 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001923 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001924 }
1925 }
1926
1927 // Don't read the directive history for a module; we don't have anywhere
1928 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001929 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001930 return;
1931
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001932 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001933 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001934 unsigned Idx = 0, N = Record.size();
1935 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001936 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001937 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001938 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1939 switch (K) {
1940 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001941 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001942 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001943 break;
1944 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001945 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001946 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001947 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001948 }
1949 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001950 bool isPublic = Record[Idx++];
1951 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1952 break;
1953 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001954
1955 if (!Latest)
1956 Latest = MD;
1957 if (Earliest)
1958 Earliest->setPrevious(MD);
1959 Earliest = MD;
1960 }
1961
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001962 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001963 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001964}
1965
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001966ASTReader::InputFileInfo
1967ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001968 // Go find this input file.
1969 BitstreamCursor &Cursor = F.InputFilesCursor;
1970 SavedStreamPosition SavedPosition(Cursor);
1971 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1972
1973 unsigned Code = Cursor.ReadCode();
1974 RecordData Record;
1975 StringRef Blob;
1976
1977 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1978 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1979 "invalid record type for input file");
1980 (void)Result;
1981
1982 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001983 InputFileInfo R;
1984 R.StoredSize = static_cast<off_t>(Record[1]);
1985 R.StoredTime = static_cast<time_t>(Record[2]);
1986 R.Overridden = static_cast<bool>(Record[3]);
1987 R.Transient = static_cast<bool>(Record[4]);
1988 R.Filename = Blob;
1989 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001990 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001991}
1992
Manman Renc8c94152016-10-21 23:35:03 +00001993static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001994InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001995 // If this ID is bogus, just return an empty input file.
1996 if (ID == 0 || ID > F.InputFilesLoaded.size())
1997 return InputFile();
1998
1999 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002000 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 return F.InputFilesLoaded[ID-1];
2002
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002003 if (F.InputFilesLoaded[ID-1].isNotFound())
2004 return InputFile();
2005
Guy Benyei11169dd2012-12-18 14:30:41 +00002006 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002007 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 SavedStreamPosition SavedPosition(Cursor);
2009 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002010
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002011 InputFileInfo FI = readInputFileInfo(F, ID);
2012 off_t StoredSize = FI.StoredSize;
2013 time_t StoredTime = FI.StoredTime;
2014 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002015 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002016 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002017
Richard Smitha8cfffa2015-11-26 02:04:16 +00002018 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002019
2020 // If we didn't find the file, resolve it relative to the
2021 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002022 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002023 F.OriginalDir != CurrentDir) {
2024 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2025 F.OriginalDir,
2026 CurrentDir);
2027 if (!Resolved.empty())
2028 File = FileMgr.getFile(Resolved);
2029 }
2030
2031 // For an overridden file, create a virtual file with the stored
2032 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002033 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002034 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002035
Craig Toppera13603a2014-05-22 05:54:18 +00002036 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002037 if (Complain) {
2038 std::string ErrorStr = "could not find file '";
2039 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002040 ErrorStr += "' referenced by AST file '";
2041 ErrorStr += F.FileName;
2042 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002043 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002044 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002045 // Record that we didn't find the file.
2046 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2047 return InputFile();
2048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002049
Ben Langmuir198c1682014-03-07 07:27:49 +00002050 // Check if there was a request to override the contents of the file
2051 // that was part of the precompiled header. Overridding such a file
2052 // can lead to problems when lexing using the source locations from the
2053 // PCH.
2054 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002055 // FIXME: Reject if the overrides are different.
2056 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002057 if (Complain)
2058 Error(diag::err_fe_pch_file_overridden, Filename);
2059 // After emitting the diagnostic, recover by disabling the override so
2060 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002061 //
2062 // FIXME: This recovery is just as broken as the original state; there may
2063 // be another precompiled module that's using the overridden contents, or
2064 // we might be half way through parsing it. Instead, we should treat the
2065 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002066 SM.disableFileContentsOverride(File);
2067 // The FileEntry is a virtual file entry with the size of the contents
2068 // that would override the original contents. Set it to the original's
2069 // size/time.
2070 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2071 StoredSize, StoredTime);
2072 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002073
Ben Langmuir198c1682014-03-07 07:27:49 +00002074 bool IsOutOfDate = false;
2075
2076 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002077 if (!Overridden && //
2078 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002079 (StoredTime && StoredTime != File->getModificationTime() &&
2080 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 )) {
2082 if (Complain) {
2083 // Build a list of the PCH imports that got us here (in reverse).
2084 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2085 while (ImportStack.back()->ImportedBy.size() > 0)
2086 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002087
Ben Langmuir198c1682014-03-07 07:27:49 +00002088 // The top-level PCH is stale.
2089 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002090 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2091 if (DiagnosticKind == 0)
2092 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2093 else if (DiagnosticKind == 1)
2094 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2095 else
2096 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002097
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 // Print the import stack.
2099 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2100 Diag(diag::note_pch_required_by)
2101 << Filename << ImportStack[0]->FileName;
2102 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002103 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002104 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002105 }
2106
Ben Langmuir198c1682014-03-07 07:27:49 +00002107 if (!Diags.isDiagnosticInFlight())
2108 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 }
2110
Ben Langmuir198c1682014-03-07 07:27:49 +00002111 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002112 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002113 // FIXME: If the file is overridden and we've already opened it,
2114 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002115
Richard Smitha8cfffa2015-11-26 02:04:16 +00002116 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002117
2118 // Note that we've loaded this input file.
2119 F.InputFilesLoaded[ID-1] = IF;
2120 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002121}
2122
Richard Smith7ed1bc92014-12-05 22:42:13 +00002123/// \brief If we are loading a relocatable PCH or module file, and the filename
2124/// is not an absolute path, add the system or module root to the beginning of
2125/// the file name.
2126void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2127 // Resolve relative to the base directory, if we have one.
2128 if (!M.BaseDirectory.empty())
2129 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002130}
2131
Richard Smith7ed1bc92014-12-05 22:42:13 +00002132void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002133 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2134 return;
2135
Richard Smith7ed1bc92014-12-05 22:42:13 +00002136 SmallString<128> Buffer;
2137 llvm::sys::path::append(Buffer, Prefix, Filename);
2138 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002139}
2140
Richard Smith0f99d6a2015-08-09 08:48:41 +00002141static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2142 switch (ARR) {
2143 case ASTReader::Failure: return true;
2144 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2145 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2146 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2147 case ASTReader::ConfigurationMismatch:
2148 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2149 case ASTReader::HadErrors: return true;
2150 case ASTReader::Success: return false;
2151 }
2152
2153 llvm_unreachable("unknown ASTReadResult");
2154}
2155
Richard Smith0516b182015-09-08 19:40:14 +00002156ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2157 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2158 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002159 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002160 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2161 return Failure;
2162
2163 // Read all of the records in the options block.
2164 RecordData Record;
2165 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002166 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002167 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002168
Richard Smith0516b182015-09-08 19:40:14 +00002169 switch (Entry.Kind) {
2170 case llvm::BitstreamEntry::Error:
2171 case llvm::BitstreamEntry::SubBlock:
2172 return Failure;
2173
2174 case llvm::BitstreamEntry::EndBlock:
2175 return Result;
2176
2177 case llvm::BitstreamEntry::Record:
2178 // The interesting case.
2179 break;
2180 }
2181
2182 // Read and process a record.
2183 Record.clear();
2184 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2185 case LANGUAGE_OPTIONS: {
2186 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2187 if (ParseLanguageOptions(Record, Complain, Listener,
2188 AllowCompatibleConfigurationMismatch))
2189 Result = ConfigurationMismatch;
2190 break;
2191 }
2192
2193 case TARGET_OPTIONS: {
2194 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2195 if (ParseTargetOptions(Record, Complain, Listener,
2196 AllowCompatibleConfigurationMismatch))
2197 Result = ConfigurationMismatch;
2198 break;
2199 }
2200
2201 case DIAGNOSTIC_OPTIONS: {
2202 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002203 if (ValidateDiagnosticOptions &&
2204 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002205 ParseDiagnosticOptions(Record, Complain, Listener))
2206 return OutOfDate;
2207 break;
2208 }
2209
2210 case FILE_SYSTEM_OPTIONS: {
2211 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2212 if (!AllowCompatibleConfigurationMismatch &&
2213 ParseFileSystemOptions(Record, Complain, Listener))
2214 Result = ConfigurationMismatch;
2215 break;
2216 }
2217
2218 case HEADER_SEARCH_OPTIONS: {
2219 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2220 if (!AllowCompatibleConfigurationMismatch &&
2221 ParseHeaderSearchOptions(Record, Complain, Listener))
2222 Result = ConfigurationMismatch;
2223 break;
2224 }
2225
2226 case PREPROCESSOR_OPTIONS:
2227 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2228 if (!AllowCompatibleConfigurationMismatch &&
2229 ParsePreprocessorOptions(Record, Complain, Listener,
2230 SuggestedPredefines))
2231 Result = ConfigurationMismatch;
2232 break;
2233 }
2234 }
2235}
2236
Guy Benyei11169dd2012-12-18 14:30:41 +00002237ASTReader::ASTReadResult
2238ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002239 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002240 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002242 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002243 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002244
2245 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2246 Error("malformed block record in AST file");
2247 return Failure;
2248 }
2249
2250 // Read all of the records and blocks in the control block.
2251 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002252 unsigned NumInputs = 0;
2253 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002254 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002255 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002256
Chris Lattnere7b154b2013-01-19 21:39:22 +00002257 switch (Entry.Kind) {
2258 case llvm::BitstreamEntry::Error:
2259 Error("malformed block record in AST file");
2260 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002261 case llvm::BitstreamEntry::EndBlock: {
2262 // Validate input files.
2263 const HeaderSearchOptions &HSOpts =
2264 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002265
Richard Smitha1825302014-10-23 22:18:29 +00002266 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002267 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2268 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002269 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2270 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002272
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002273 // If we are reading a module, we will create a verification timestamp,
2274 // so we verify all input files. Otherwise, verify only user input
2275 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002276
2277 unsigned N = NumUserInputs;
2278 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002279 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002280 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002281 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002282 N = NumInputs;
2283
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002284 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002285 InputFile IF = getInputFile(F, I+1, Complain);
2286 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002288 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002290
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002291 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002292 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002293
Ben Langmuircb69b572014-03-07 06:40:32 +00002294 if (Listener && Listener->needsInputFileVisitation()) {
2295 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2296 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002297 for (unsigned I = 0; I < N; ++I) {
2298 bool IsSystem = I >= NumUserInputs;
2299 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002300 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002301 F.Kind == MK_ExplicitModule ||
2302 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002303 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002304 }
2305
Richard Smith8a308ec2015-11-05 00:54:55 +00002306 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002307 }
2308
Chris Lattnere7b154b2013-01-19 21:39:22 +00002309 case llvm::BitstreamEntry::SubBlock:
2310 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 case INPUT_FILES_BLOCK_ID:
2312 F.InputFilesCursor = Stream;
2313 if (Stream.SkipBlock() || // Skip with the main cursor
2314 // Read the abbreviations
2315 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2316 Error("malformed block record in AST file");
2317 return Failure;
2318 }
2319 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002320
2321 case OPTIONS_BLOCK_ID:
2322 // If we're reading the first module for this group, check its options
2323 // are compatible with ours. For modules it imports, no further checking
2324 // is required, because we checked them when we built it.
2325 if (Listener && !ImportedBy) {
2326 // Should we allow the configuration of the module file to differ from
2327 // the configuration of the current translation unit in a compatible
2328 // way?
2329 //
2330 // FIXME: Allow this for files explicitly specified with -include-pch.
2331 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002332 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002333 const HeaderSearchOptions &HSOpts =
2334 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002335
Richard Smith8a308ec2015-11-05 00:54:55 +00002336 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2337 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002338 *Listener, SuggestedPredefines,
2339 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002340 if (Result == Failure) {
2341 Error("malformed block record in AST file");
2342 return Result;
2343 }
2344
Richard Smith8a308ec2015-11-05 00:54:55 +00002345 if (DisableValidation ||
2346 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2347 Result = Success;
2348
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002349 // If we can't load the module, exit early since we likely
2350 // will rebuild the module anyway. The stream may be in the
2351 // middle of a block.
2352 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002353 return Result;
2354 } else if (Stream.SkipBlock()) {
2355 Error("malformed block record in AST file");
2356 return Failure;
2357 }
2358 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002359
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002361 if (Stream.SkipBlock()) {
2362 Error("malformed block record in AST file");
2363 return Failure;
2364 }
2365 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002367
Chris Lattnere7b154b2013-01-19 21:39:22 +00002368 case llvm::BitstreamEntry::Record:
2369 // The interesting case.
2370 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
2372
2373 // Read and process a record.
2374 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002375 StringRef Blob;
2376 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 case METADATA: {
2378 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2379 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002380 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2381 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 return VersionMismatch;
2383 }
2384
Richard Smithe75ee0f2015-08-17 07:13:32 +00002385 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2387 Diag(diag::err_pch_with_compiler_errors);
2388 return HadErrors;
2389 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002390 if (hasErrors) {
2391 Diags.ErrorOccurred = true;
2392 Diags.UncompilableErrorOccurred = true;
2393 Diags.UnrecoverableErrorOccurred = true;
2394 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002395
2396 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002397 // Relative paths in a relocatable PCH are relative to our sysroot.
2398 if (F.RelocatablePCH)
2399 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002400
Richard Smithe75ee0f2015-08-17 07:13:32 +00002401 F.HasTimestamps = Record[5];
2402
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002404 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2406 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002407 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 return VersionMismatch;
2409 }
2410 break;
2411 }
2412
Ben Langmuir487ea142014-10-23 18:05:36 +00002413 case SIGNATURE:
2414 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2415 F.Signature = Record[0];
2416 break;
2417
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002419 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 unsigned Idx = 0, N = Record.size();
2421 while (Idx < N) {
2422 // Read information about the AST file.
2423 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2424 // The import location will be the local one for now; we will adjust
2425 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002426 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002428 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002429 off_t StoredSize = (off_t)Record[Idx++];
2430 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002431 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002432 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002433
Richard Smith0f99d6a2015-08-09 08:48:41 +00002434 // If our client can't cope with us being out of date, we can't cope with
2435 // our dependency being missing.
2436 unsigned Capabilities = ClientLoadCapabilities;
2437 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2438 Capabilities &= ~ARR_Missing;
2439
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002441 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2442 Loaded, StoredSize, StoredModTime,
2443 StoredSignature, Capabilities);
2444
2445 // If we diagnosed a problem, produce a backtrace.
2446 if (isDiagnosedResult(Result, Capabilities))
2447 Diag(diag::note_module_file_imported_by)
2448 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2449
2450 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 case Failure: return Failure;
2452 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002453 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 case OutOfDate: return OutOfDate;
2455 case VersionMismatch: return VersionMismatch;
2456 case ConfigurationMismatch: return ConfigurationMismatch;
2457 case HadErrors: return HadErrors;
2458 case Success: break;
2459 }
2460 }
2461 break;
2462 }
2463
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 case ORIGINAL_FILE:
2465 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002466 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002468 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 break;
2470
2471 case ORIGINAL_FILE_ID:
2472 F.OriginalSourceFileID = FileID::get(Record[0]);
2473 break;
2474
2475 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002476 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 break;
2478
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002479 case MODULE_NAME:
2480 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002481 if (Listener)
2482 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002483 break;
2484
Richard Smith223d3f22014-12-06 03:21:08 +00002485 case MODULE_DIRECTORY: {
2486 assert(!F.ModuleName.empty() &&
2487 "MODULE_DIRECTORY found before MODULE_NAME");
2488 // If we've already loaded a module map file covering this module, we may
2489 // have a better path for it (relative to the current build).
2490 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2491 if (M && M->Directory) {
2492 // If we're implicitly loading a module, the base directory can't
2493 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002494 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002495 const DirectoryEntry *BuildDir =
2496 PP.getFileManager().getDirectory(Blob);
2497 if (!BuildDir || BuildDir != M->Directory) {
2498 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2499 Diag(diag::err_imported_module_relocated)
2500 << F.ModuleName << Blob << M->Directory->getName();
2501 return OutOfDate;
2502 }
2503 }
2504 F.BaseDirectory = M->Directory->getName();
2505 } else {
2506 F.BaseDirectory = Blob;
2507 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002508 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002509 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002510
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002511 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002512 if (ASTReadResult Result =
2513 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2514 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002515 break;
2516
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002517 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002518 NumInputs = Record[0];
2519 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002520 F.InputFileOffsets =
2521 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002522 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002523 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 break;
2525 }
2526 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002527}
2528
Ben Langmuir2c9af442014-04-10 17:57:43 +00002529ASTReader::ASTReadResult
2530ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002531 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002532
2533 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2534 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002535 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 }
2537
2538 // Read all of the records and blocks for the AST file.
2539 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002540 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002541 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002542
Chris Lattnere7b154b2013-01-19 21:39:22 +00002543 switch (Entry.Kind) {
2544 case llvm::BitstreamEntry::Error:
2545 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002546 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002548 // Outside of C++, we do not store a lookup map for the translation unit.
2549 // Instead, mark it as needing a lookup map to be built if this module
2550 // contains any declarations lexically within it (which it always does!).
2551 // This usually has no cost, since we very rarely need the lookup map for
2552 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002554 if (DC->hasExternalLexicalStorage() &&
2555 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002557
Ben Langmuir2c9af442014-04-10 17:57:43 +00002558 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002560 case llvm::BitstreamEntry::SubBlock:
2561 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 case DECLTYPES_BLOCK_ID:
2563 // We lazily load the decls block, but we want to set up the
2564 // DeclsCursor cursor to point into it. Clone our current bitcode
2565 // cursor to it, enter the block and read the abbrevs in that block.
2566 // With the main cursor, we just skip over it.
2567 F.DeclsCursor = Stream;
2568 if (Stream.SkipBlock() || // Skip with the main cursor.
2569 // Read the abbrevs.
2570 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2571 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002572 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 }
2574 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002575
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 case PREPROCESSOR_BLOCK_ID:
2577 F.MacroCursor = Stream;
2578 if (!PP.getExternalSource())
2579 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002580
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 if (Stream.SkipBlock() ||
2582 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2583 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 }
2586 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2587 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002588
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 case PREPROCESSOR_DETAIL_BLOCK_ID:
2590 F.PreprocessorDetailCursor = Stream;
2591 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002595 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002599
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 if (!PP.getPreprocessingRecord())
2601 PP.createPreprocessingRecord();
2602 if (!PP.getPreprocessingRecord()->getExternalSource())
2603 PP.getPreprocessingRecord()->SetExternalSource(*this);
2604 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002605
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 case SOURCE_MANAGER_BLOCK_ID:
2607 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002610
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002612 if (ASTReadResult Result =
2613 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002614 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002616
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002618 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 if (Stream.SkipBlock() ||
2620 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2621 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
2624 CommentsCursors.push_back(std::make_pair(C, &F));
2625 break;
2626 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002627
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002629 if (Stream.SkipBlock()) {
2630 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002631 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002632 }
2633 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 }
2635 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002636
Chris Lattnere7b154b2013-01-19 21:39:22 +00002637 case llvm::BitstreamEntry::Record:
2638 // The interesting case.
2639 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 }
2641
2642 // Read and process a record.
2643 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002644 StringRef Blob;
2645 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 default: // Default behavior: ignore.
2647 break;
2648
2649 case TYPE_OFFSET: {
2650 if (F.LocalNumTypes != 0) {
2651 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002654 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 F.LocalNumTypes = Record[0];
2656 unsigned LocalBaseTypeIndex = Record[1];
2657 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002658
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 if (F.LocalNumTypes > 0) {
2660 // Introduce the global -> local mapping for types within this module.
2661 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002662
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 // Introduce the local -> global mapping for types within this module.
2664 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002665 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002667
2668 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 }
2670 break;
2671 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002672
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 case DECL_OFFSET: {
2674 if (F.LocalNumDecls != 0) {
2675 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002676 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002678 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 F.LocalNumDecls = Record[0];
2680 unsigned LocalBaseDeclID = Record[1];
2681 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002682
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002684 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 // module.
2686 GlobalDeclMap.insert(
2687 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002688
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 // Introduce the local -> global mapping for declarations within this
2690 // module.
2691 F.DeclRemap.insertOrReplace(
2692 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002693
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 // Introduce the global -> local mapping for declarations within this
2695 // module.
2696 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002697
Ben Langmuir52ca6782014-10-20 16:27:32 +00002698 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2699 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 break;
2701 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002702
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 case TU_UPDATE_LEXICAL: {
2704 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002705 LexicalContents Contents(
2706 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2707 Blob.data()),
2708 static_cast<unsigned int>(Blob.size() / 4));
2709 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 TU->setHasExternalLexicalStorage(true);
2711 break;
2712 }
2713
2714 case UPDATE_VISIBLE: {
2715 unsigned Idx = 0;
2716 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002717 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002718 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002719 // If we've already loaded the decl, perform the updates when we finish
2720 // loading this block.
2721 if (Decl *D = GetExistingDecl(ID))
2722 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 break;
2724 }
2725
2726 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002727 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002729 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2730 (const unsigned char *)F.IdentifierTableData + Record[0],
2731 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2732 (const unsigned char *)F.IdentifierTableData,
2733 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2736 }
2737 break;
2738
2739 case IDENTIFIER_OFFSET: {
2740 if (F.LocalNumIdentifiers != 0) {
2741 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002742 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002744 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 F.LocalNumIdentifiers = Record[0];
2746 unsigned LocalBaseIdentifierID = Record[1];
2747 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 if (F.LocalNumIdentifiers > 0) {
2750 // Introduce the global -> local mapping for identifiers within this
2751 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002752 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002754
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 // Introduce the local -> global mapping for identifiers within this
2756 // module.
2757 F.IdentifierRemap.insertOrReplace(
2758 std::make_pair(LocalBaseIdentifierID,
2759 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002760
Ben Langmuir52ca6782014-10-20 16:27:32 +00002761 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2762 + F.LocalNumIdentifiers);
2763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 break;
2765 }
2766
Richard Smith33e0f7e2015-07-22 02:08:40 +00002767 case INTERESTING_IDENTIFIERS:
2768 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2769 break;
2770
Ben Langmuir332aafe2014-01-31 01:06:56 +00002771 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002772 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2773 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002775 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 break;
2777
David Blaikie9ffe5a32017-01-30 05:00:26 +00002778 case MODULAR_CODEGEN_DECLS:
2779 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2780 // them (ie: if we're not codegenerating this module).
2781 if (F.Kind == MK_MainFile)
2782 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2783 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2784 break;
2785
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002787 if (SpecialTypes.empty()) {
2788 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2789 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2790 break;
2791 }
2792
2793 if (SpecialTypes.size() != Record.size()) {
2794 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002795 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002796 }
2797
2798 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2799 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2800 if (!SpecialTypes[I])
2801 SpecialTypes[I] = ID;
2802 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2803 // merge step?
2804 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 break;
2806
2807 case STATISTICS:
2808 TotalNumStatements += Record[0];
2809 TotalNumMacros += Record[1];
2810 TotalLexicalDeclContexts += Record[2];
2811 TotalVisibleDeclContexts += Record[3];
2812 break;
2813
2814 case UNUSED_FILESCOPED_DECLS:
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2817 break;
2818
2819 case DELEGATING_CTORS:
2820 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2822 break;
2823
2824 case WEAK_UNDECLARED_IDENTIFIERS:
2825 if (Record.size() % 4 != 0) {
2826 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002827 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002829
2830 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 // files. This isn't the way to do it :)
2832 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002833
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 // Translate the weak, undeclared identifiers into global IDs.
2835 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2836 WeakUndeclaredIdentifiers.push_back(
2837 getGlobalIdentifierID(F, Record[I++]));
2838 WeakUndeclaredIdentifiers.push_back(
2839 getGlobalIdentifierID(F, Record[I++]));
2840 WeakUndeclaredIdentifiers.push_back(
2841 ReadSourceLocation(F, Record, I).getRawEncoding());
2842 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2843 }
2844 break;
2845
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002847 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 F.LocalNumSelectors = Record[0];
2849 unsigned LocalBaseSelectorID = Record[1];
2850 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002851
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 // module.
2855 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002856
2857 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 // module.
2859 F.SelectorRemap.insertOrReplace(
2860 std::make_pair(LocalBaseSelectorID,
2861 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002862
2863 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 }
2865 break;
2866 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002867
Guy Benyei11169dd2012-12-18 14:30:41 +00002868 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002869 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 if (Record[0])
2871 F.SelectorLookupTable
2872 = ASTSelectorLookupTable::Create(
2873 F.SelectorLookupTableData + Record[0],
2874 F.SelectorLookupTableData,
2875 ASTSelectorLookupTrait(*this, F));
2876 TotalNumMethodPoolEntries += Record[1];
2877 break;
2878
2879 case REFERENCED_SELECTOR_POOL:
2880 if (!Record.empty()) {
2881 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002882 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 Record[Idx++]));
2884 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2885 getRawEncoding());
2886 }
2887 }
2888 break;
2889
2890 case PP_COUNTER_VALUE:
2891 if (!Record.empty() && Listener)
2892 Listener->ReadCounter(F, Record[0]);
2893 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002894
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002896 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 F.NumFileSortedDecls = Record[0];
2898 break;
2899
2900 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002901 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 F.LocalNumSLocEntries = Record[0];
2903 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002904 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002905 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002907 if (!F.SLocEntryBaseID) {
2908 Error("ran out of source locations");
2909 break;
2910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 // Make our entry in the range map. BaseID is negative and growing, so
2912 // we invert it. Because we invert it, though, we need the other end of
2913 // the range.
2914 unsigned RangeStart =
2915 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2916 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2917 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2918
2919 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2920 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2921 GlobalSLocOffsetMap.insert(
2922 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2923 - SLocSpaceSize,&F));
2924
2925 // Initialize the remapping table.
2926 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002927 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002929 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002931
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 TotalNumSLocEntries += F.LocalNumSLocEntries;
2933 break;
2934 }
2935
2936 case MODULE_OFFSET_MAP: {
2937 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002938 const unsigned char *Data = (const unsigned char*)Blob.data();
2939 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002940
2941 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2942 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2943 F.SLocRemap.insert(std::make_pair(0U, 0));
2944 F.SLocRemap.insert(std::make_pair(2U, 1));
2945 }
2946
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002948 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2949 RemapBuilder;
2950 RemapBuilder SLocRemap(F.SLocRemap);
2951 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2952 RemapBuilder MacroRemap(F.MacroRemap);
2953 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2954 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2955 RemapBuilder SelectorRemap(F.SelectorRemap);
2956 RemapBuilder DeclRemap(F.DeclRemap);
2957 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002958
Richard Smithd8879c82015-08-24 21:59:32 +00002959 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002960 using namespace llvm::support;
2961 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 StringRef Name = StringRef((const char*)Data, Len);
2963 Data += Len;
2964 ModuleFile *OM = ModuleMgr.lookup(Name);
2965 if (!OM) {
2966 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002967 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 }
2969
Justin Bogner57ba0b22014-03-28 22:03:24 +00002970 uint32_t SLocOffset =
2971 endian::readNext<uint32_t, little, unaligned>(Data);
2972 uint32_t IdentifierIDOffset =
2973 endian::readNext<uint32_t, little, unaligned>(Data);
2974 uint32_t MacroIDOffset =
2975 endian::readNext<uint32_t, little, unaligned>(Data);
2976 uint32_t PreprocessedEntityIDOffset =
2977 endian::readNext<uint32_t, little, unaligned>(Data);
2978 uint32_t SubmoduleIDOffset =
2979 endian::readNext<uint32_t, little, unaligned>(Data);
2980 uint32_t SelectorIDOffset =
2981 endian::readNext<uint32_t, little, unaligned>(Data);
2982 uint32_t DeclIDOffset =
2983 endian::readNext<uint32_t, little, unaligned>(Data);
2984 uint32_t TypeIndexOffset =
2985 endian::readNext<uint32_t, little, unaligned>(Data);
2986
Ben Langmuir785180e2014-10-20 16:27:30 +00002987 uint32_t None = std::numeric_limits<uint32_t>::max();
2988
2989 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2990 RemapBuilder &Remap) {
2991 if (Offset != None)
2992 Remap.insert(std::make_pair(Offset,
2993 static_cast<int>(BaseOffset - Offset)));
2994 };
2995 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2996 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2997 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2998 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2999 PreprocessedEntityRemap);
3000 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3001 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3002 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3003 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003004
3005 // Global -> local mappings.
3006 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3007 }
3008 break;
3009 }
3010
3011 case SOURCE_MANAGER_LINE_TABLE:
3012 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003013 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003014 break;
3015
3016 case SOURCE_LOCATION_PRELOADS: {
3017 // Need to transform from the local view (1-based IDs) to the global view,
3018 // which is based off F.SLocEntryBaseID.
3019 if (!F.PreloadSLocEntries.empty()) {
3020 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003023
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 F.PreloadSLocEntries.swap(Record);
3025 break;
3026 }
3027
3028 case EXT_VECTOR_DECLS:
3029 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3030 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3031 break;
3032
3033 case VTABLE_USES:
3034 if (Record.size() % 3 != 0) {
3035 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003036 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003038
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 // Later tables overwrite earlier ones.
3040 // FIXME: Modules will have some trouble with this. This is clearly not
3041 // the right way to do this.
3042 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003043
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3045 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3046 VTableUses.push_back(
3047 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3048 VTableUses.push_back(Record[Idx++]);
3049 }
3050 break;
3051
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 case PENDING_IMPLICIT_INSTANTIATIONS:
3053 if (PendingInstantiations.size() % 2 != 0) {
3054 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003055 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
3057
3058 if (Record.size() % 2 != 0) {
3059 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003060 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 }
3062
3063 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3064 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3065 PendingInstantiations.push_back(
3066 ReadSourceLocation(F, Record, I).getRawEncoding());
3067 }
3068 break;
3069
3070 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003071 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003072 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3076 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3077 break;
3078
3079 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003080 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3081 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3082 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003083
3084 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003085
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 unsigned StartingID;
3087 if (!PP.getPreprocessingRecord())
3088 PP.createPreprocessingRecord();
3089 if (!PP.getPreprocessingRecord()->getExternalSource())
3090 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003091 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003093 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 F.BasePreprocessedEntityID = StartingID;
3095
3096 if (F.NumPreprocessedEntities > 0) {
3097 // Introduce the global -> local mapping for preprocessed entities in
3098 // this module.
3099 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 // Introduce the local -> global mapping for preprocessed entities in
3102 // this module.
3103 F.PreprocessedEntityRemap.insertOrReplace(
3104 std::make_pair(LocalBasePreprocessedEntityID,
3105 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3106 }
3107
3108 break;
3109 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 case DECL_UPDATE_OFFSETS: {
3112 if (Record.size() % 2 != 0) {
3113 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003116 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3117 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3118 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3119
3120 // If we've already loaded the decl, perform the updates when we finish
3121 // loading this block.
3122 if (Decl *D = GetExistingDecl(ID))
3123 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 break;
3126 }
3127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 case OBJC_CATEGORIES_MAP: {
3129 if (F.LocalNumObjCCategoriesInMap != 0) {
3130 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003131 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003133
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003135 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 break;
3137 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003138
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 case OBJC_CATEGORIES:
3140 F.ObjCCategories.swap(Record);
3141 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003142
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 case DIAG_PRAGMA_MAPPINGS:
3144 if (F.PragmaDiagMappings.empty())
3145 F.PragmaDiagMappings.swap(Record);
3146 else
3147 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3148 Record.begin(), Record.end());
3149 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 case CUDA_SPECIAL_DECL_REFS:
3152 // Later tables overwrite earlier ones.
3153 // FIXME: Modules will have trouble with this.
3154 CUDASpecialDeclRefs.clear();
3155 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3156 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3157 break;
3158
3159 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003160 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 if (Record[0]) {
3163 F.HeaderFileInfoTable
3164 = HeaderFileInfoLookupTable::Create(
3165 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3166 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003167 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003169 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003170
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 PP.getHeaderSearchInfo().SetExternalSource(this);
3172 if (!PP.getHeaderSearchInfo().getExternalLookup())
3173 PP.getHeaderSearchInfo().SetExternalLookup(this);
3174 }
3175 break;
3176 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003177
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 case FP_PRAGMA_OPTIONS:
3179 // Later tables overwrite earlier ones.
3180 FPPragmaOptions.swap(Record);
3181 break;
3182
3183 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003184 for (unsigned I = 0, E = Record.size(); I != E; ) {
3185 auto Name = ReadString(Record, I);
3186 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003187 Opt.Supported = Record[I++] != 0;
3188 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003189 Opt.Avail = Record[I++];
3190 Opt.Core = Record[I++];
3191 }
3192 break;
3193
3194 case OPENCL_EXTENSION_TYPES:
3195 for (unsigned I = 0, E = Record.size(); I != E;) {
3196 auto TypeID = static_cast<::TypeID>(Record[I++]);
3197 auto *Type = GetType(TypeID).getTypePtr();
3198 auto NumExt = static_cast<unsigned>(Record[I++]);
3199 for (unsigned II = 0; II != NumExt; ++II) {
3200 auto Ext = ReadString(Record, I);
3201 OpenCLTypeExtMap[Type].insert(Ext);
3202 }
3203 }
3204 break;
3205
3206 case OPENCL_EXTENSION_DECLS:
3207 for (unsigned I = 0, E = Record.size(); I != E;) {
3208 auto DeclID = static_cast<::DeclID>(Record[I++]);
3209 auto *Decl = GetDecl(DeclID);
3210 auto NumExt = static_cast<unsigned>(Record[I++]);
3211 for (unsigned II = 0; II != NumExt; ++II) {
3212 auto Ext = ReadString(Record, I);
3213 OpenCLDeclExtMap[Decl].insert(Ext);
3214 }
3215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 break;
3217
3218 case TENTATIVE_DEFINITIONS:
3219 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3220 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3221 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003222
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 case KNOWN_NAMESPACES:
3224 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3225 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3226 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003227
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003228 case UNDEFINED_BUT_USED:
3229 if (UndefinedButUsed.size() % 2 != 0) {
3230 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003231 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003232 }
3233
3234 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003235 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003236 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003237 }
3238 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003239 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3240 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003241 ReadSourceLocation(F, Record, I).getRawEncoding());
3242 }
3243 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003244 case DELETE_EXPRS_TO_ANALYZE:
3245 for (unsigned I = 0, N = Record.size(); I != N;) {
3246 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3247 const uint64_t Count = Record[I++];
3248 DelayedDeleteExprs.push_back(Count);
3249 for (uint64_t C = 0; C < Count; ++C) {
3250 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3251 bool IsArrayForm = Record[I++] == 1;
3252 DelayedDeleteExprs.push_back(IsArrayForm);
3253 }
3254 }
3255 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003256
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003258 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 // If we aren't loading a module (which has its own exports), make
3260 // all of the imported modules visible.
3261 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003262 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3263 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3264 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003265 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003266 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003267 if (DeserializationListener)
3268 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3269 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 }
3271 }
3272 break;
3273 }
3274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 case MACRO_OFFSET: {
3276 if (F.LocalNumMacros != 0) {
3277 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003278 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003280 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 F.LocalNumMacros = Record[0];
3282 unsigned LocalBaseMacroID = Record[1];
3283 F.BaseMacroID = getTotalNumMacros();
3284
3285 if (F.LocalNumMacros > 0) {
3286 // Introduce the global -> local mapping for macros within this module.
3287 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3288
3289 // Introduce the local -> global mapping for macros within this module.
3290 F.MacroRemap.insertOrReplace(
3291 std::make_pair(LocalBaseMacroID,
3292 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003293
3294 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 }
3296 break;
3297 }
3298
Richard Smithe40f2ba2013-08-07 21:41:30 +00003299 case LATE_PARSED_TEMPLATE: {
3300 LateParsedTemplates.append(Record.begin(), Record.end());
3301 break;
3302 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003303
3304 case OPTIMIZE_PRAGMA_OPTIONS:
3305 if (Record.size() != 1) {
3306 Error("invalid pragma optimize record");
3307 return Failure;
3308 }
3309 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3310 break;
Nico Weber72889432014-09-06 01:25:55 +00003311
Nico Weber779355f2016-03-02 23:22:00 +00003312 case MSSTRUCT_PRAGMA_OPTIONS:
3313 if (Record.size() != 1) {
3314 Error("invalid pragma ms_struct record");
3315 return Failure;
3316 }
3317 PragmaMSStructState = Record[0];
3318 break;
3319
Nico Weber42932312016-03-03 00:17:35 +00003320 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3321 if (Record.size() != 2) {
3322 Error("invalid pragma ms_struct record");
3323 return Failure;
3324 }
3325 PragmaMSPointersToMembersState = Record[0];
3326 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3327 break;
3328
Nico Weber72889432014-09-06 01:25:55 +00003329 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3330 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3331 UnusedLocalTypedefNameCandidates.push_back(
3332 getGlobalDeclID(F, Record[I]));
3333 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003334
3335 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3336 if (Record.size() != 1) {
3337 Error("invalid cuda pragma options record");
3338 return Failure;
3339 }
3340 ForceCUDAHostDeviceDepth = Record[0];
3341 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 }
3343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003344}
3345
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003346ASTReader::ASTReadResult
3347ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3348 const ModuleFile *ImportedBy,
3349 unsigned ClientLoadCapabilities) {
3350 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003351 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003352
Manman Ren11f2a472016-08-18 17:42:15 +00003353 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003354 // For an explicitly-loaded module, we don't care whether the original
3355 // module map file exists or matches.
3356 return Success;
3357 }
3358
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003359 // Try to resolve ModuleName in the current header search context and
3360 // verify that it is found in the same module map file as we saved. If the
3361 // top-level AST file is a main file, skip this check because there is no
3362 // usable header search context.
3363 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003364 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003365 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003366 // An implicitly-loaded module file should have its module listed in some
3367 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003368 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003369 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3370 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3371 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003372 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003373 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3374 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3375 // This module was defined by an imported (explicit) module.
3376 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3377 << ASTFE->getName();
3378 else
3379 // This module was built with a different module map.
3380 Diag(diag::err_imported_module_not_found)
3381 << F.ModuleName << F.FileName << ImportedBy->FileName
3382 << F.ModuleMapPath;
3383 }
3384 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003385 }
3386
Richard Smithe842a472014-10-22 02:05:46 +00003387 assert(M->Name == F.ModuleName && "found module with different name");
3388
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003389 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003390 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003391 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3392 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003393 assert(ImportedBy && "top-level import should be verified");
3394 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3395 Diag(diag::err_imported_module_modmap_changed)
3396 << F.ModuleName << ImportedBy->FileName
3397 << ModMap->getName() << F.ModuleMapPath;
3398 return OutOfDate;
3399 }
3400
3401 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3402 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3403 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003404 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003405 const FileEntry *F =
3406 FileMgr.getFile(Filename, false, false);
3407 if (F == nullptr) {
3408 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3409 Error("could not find file '" + Filename +"' referenced by AST file");
3410 return OutOfDate;
3411 }
3412 AdditionalStoredMaps.insert(F);
3413 }
3414
3415 // Check any additional module map files (e.g. module.private.modulemap)
3416 // that are not in the pcm.
3417 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3418 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3419 // Remove files that match
3420 // Note: SmallPtrSet::erase is really remove
3421 if (!AdditionalStoredMaps.erase(ModMap)) {
3422 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3423 Diag(diag::err_module_different_modmap)
3424 << F.ModuleName << /*new*/0 << ModMap->getName();
3425 return OutOfDate;
3426 }
3427 }
3428 }
3429
3430 // Check any additional module map files that are in the pcm, but not
3431 // found in header search. Cases that match are already removed.
3432 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3433 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3434 Diag(diag::err_module_different_modmap)
3435 << F.ModuleName << /*not new*/1 << ModMap->getName();
3436 return OutOfDate;
3437 }
3438 }
3439
3440 if (Listener)
3441 Listener->ReadModuleMapFile(F.ModuleMapPath);
3442 return Success;
3443}
3444
3445
Douglas Gregorc1489562013-02-12 23:36:21 +00003446/// \brief Move the given method to the back of the global list of methods.
3447static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3448 // Find the entry for this selector in the method pool.
3449 Sema::GlobalMethodPool::iterator Known
3450 = S.MethodPool.find(Method->getSelector());
3451 if (Known == S.MethodPool.end())
3452 return;
3453
3454 // Retrieve the appropriate method list.
3455 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3456 : Known->second.second;
3457 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003458 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003459 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003460 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003461 Found = true;
3462 } else {
3463 // Keep searching.
3464 continue;
3465 }
3466 }
3467
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003468 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003469 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003470 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003471 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003472 }
3473}
3474
Richard Smithde711422015-04-23 21:20:19 +00003475void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003476 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003477 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003478 bool wasHidden = D->Hidden;
3479 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003480
Richard Smith49f906a2014-03-01 00:08:04 +00003481 if (wasHidden && SemaObj) {
3482 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3483 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003484 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 }
3486 }
3487}
3488
Richard Smith49f906a2014-03-01 00:08:04 +00003489void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003490 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003491 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003493 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003494 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003496 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
3498 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003499 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 // there is nothing more to do.
3501 continue;
3502 }
Richard Smith49f906a2014-03-01 00:08:04 +00003503
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 if (!Mod->isAvailable()) {
3505 // Modules that aren't available cannot be made visible.
3506 continue;
3507 }
3508
3509 // Update the module's name visibility.
3510 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003511
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 // If we've already deserialized any names from this module,
3513 // mark them as visible.
3514 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3515 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003516 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003518 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003519 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3520 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003522
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003524 SmallVector<Module *, 16> Exports;
3525 Mod->getExportedModules(Exports);
3526 for (SmallVectorImpl<Module *>::iterator
3527 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3528 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003529 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003530 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 }
3532 }
3533}
3534
Richard Smith6561f922016-09-12 21:06:40 +00003535/// We've merged the definition \p MergedDef into the existing definition
3536/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3537/// visible.
3538void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3539 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003540 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3541 // in modules other than its owning module. We should instead give the
3542 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003543 if (Def->isHidden()) {
3544 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003545 if (!MergedDef->isHidden())
3546 Def->Hidden = false;
3547 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3548 getContext().mergeDefinitionIntoModule(
3549 Def, MergedDef->getImportedOwningModule(),
3550 /*NotifyListeners*/ false);
3551 PendingMergedDefinitionsToDeduplicate.insert(Def);
3552 } else {
3553 auto SubmoduleID = MergedDef->getOwningModuleID();
3554 assert(SubmoduleID && "hidden definition in no module");
3555 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3556 }
Richard Smith6561f922016-09-12 21:06:40 +00003557 }
3558}
3559
Douglas Gregore060e572013-01-25 01:03:03 +00003560bool ASTReader::loadGlobalIndex() {
3561 if (GlobalIndex)
3562 return false;
3563
3564 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3565 !Context.getLangOpts().Modules)
3566 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003567
Douglas Gregore060e572013-01-25 01:03:03 +00003568 // Try to load the global index.
3569 TriedLoadingGlobalIndex = true;
3570 StringRef ModuleCachePath
3571 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3572 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003574 if (!Result.first)
3575 return true;
3576
3577 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003578 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003579 return false;
3580}
3581
3582bool ASTReader::isGlobalIndexUnavailable() const {
3583 return Context.getLangOpts().Modules && UseGlobalIndex &&
3584 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3585}
3586
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003587static void updateModuleTimestamp(ModuleFile &MF) {
3588 // Overwrite the timestamp file contents so that file's mtime changes.
3589 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003590 std::error_code EC;
3591 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3592 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003593 return;
3594 OS << "Timestamp file\n";
3595}
3596
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003597/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3598/// cursor into the start of the given block ID, returning false on success and
3599/// true on failure.
3600static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003601 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003602 llvm::BitstreamEntry Entry = Cursor.advance();
3603 switch (Entry.Kind) {
3604 case llvm::BitstreamEntry::Error:
3605 case llvm::BitstreamEntry::EndBlock:
3606 return true;
3607
3608 case llvm::BitstreamEntry::Record:
3609 // Ignore top-level records.
3610 Cursor.skipRecord(Entry.ID);
3611 break;
3612
3613 case llvm::BitstreamEntry::SubBlock:
3614 if (Entry.ID == BlockID) {
3615 if (Cursor.EnterSubBlock(BlockID))
3616 return true;
3617 // Found it!
3618 return false;
3619 }
3620
3621 if (Cursor.SkipBlock())
3622 return true;
3623 }
3624 }
3625}
3626
Benjamin Kramer0772c422016-02-13 13:42:54 +00003627ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 ModuleKind Type,
3629 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003630 unsigned ClientLoadCapabilities,
3631 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003632 llvm::SaveAndRestore<SourceLocation>
3633 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3634
Richard Smithd1c46742014-04-30 02:24:17 +00003635 // Defer any pending actions until we get to the end of reading the AST file.
3636 Deserializing AnASTFile(this);
3637
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003639 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003640
3641 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003642 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003643 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003644 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003645 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 ClientLoadCapabilities)) {
3647 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003648 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 case OutOfDate:
3650 case VersionMismatch:
3651 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003652 case HadErrors: {
3653 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3654 for (const ImportedModule &IM : Loaded)
3655 LoadedSet.insert(IM.Mod);
3656
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003657 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003658 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003659 ? &PP.getHeaderSearchInfo().getModuleMap()
3660 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003661
3662 // If we find that any modules are unusable, the global index is going
3663 // to be out-of-date. Just remove it.
3664 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003665 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003667 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 case Success:
3669 break;
3670 }
3671
3672 // Here comes stuff that we only do once the entire chain is loaded.
3673
3674 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003675 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3676 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 M != MEnd; ++M) {
3678 ModuleFile &F = *M->Mod;
3679
3680 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003681 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3682 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003683
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003684 // Read the extension blocks.
3685 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3686 if (ASTReadResult Result = ReadExtensionBlock(F))
3687 return Result;
3688 }
3689
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003690 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 // bits of all files we've seen.
3692 F.GlobalBitOffset = TotalModulesSizeInBits;
3693 TotalModulesSizeInBits += F.SizeInBits;
3694 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003695
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 // Preload SLocEntries.
3697 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3698 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3699 // Load it through the SourceManager and don't call ReadSLocEntry()
3700 // directly because the entry may have already been loaded in which case
3701 // calling ReadSLocEntry() directly would trigger an assertion in
3702 // SourceManager.
3703 SourceMgr.getLoadedSLocEntryByID(Index);
3704 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003705
3706 // Preload all the pending interesting identifiers by marking them out of
3707 // date.
3708 for (auto Offset : F.PreloadIdentifierOffsets) {
3709 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3710 F.IdentifierTableData + Offset);
3711
3712 ASTIdentifierLookupTrait Trait(*this, F);
3713 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3714 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003715 auto &II = PP.getIdentifierTable().getOwn(Key);
3716 II.setOutOfDate(true);
3717
3718 // Mark this identifier as being from an AST file so that we can track
3719 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003720 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003721
3722 // Associate the ID with the identifier so that the writer can reuse it.
3723 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3724 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003725 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 }
3727
Douglas Gregor603cd862013-03-22 18:50:14 +00003728 // Setup the import locations and notify the module manager that we've
3729 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003730 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3731 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 M != MEnd; ++M) {
3733 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003734
3735 ModuleMgr.moduleFileAccepted(&F);
3736
3737 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003738 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003739 // FIXME: We assume that locations from PCH / preamble do not need
3740 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 if (!M->ImportedBy)
3742 F.ImportLoc = M->ImportLoc;
3743 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003744 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 }
3746
Richard Smith33e0f7e2015-07-22 02:08:40 +00003747 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003748 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3749 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003750 // Mark all of the identifiers in the identifier table as being out of date,
3751 // so that various accessors know to check the loaded modules when the
3752 // identifier is used.
3753 //
3754 // For C++ modules, we don't need information on many identifiers (just
3755 // those that provide macros or are poisoned), so we mark all of
3756 // the interesting ones via PreloadIdentifierOffsets.
3757 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3758 IdEnd = PP.getIdentifierTable().end();
3759 Id != IdEnd; ++Id)
3760 Id->second->setOutOfDate(true);
3761 }
Manman Rena0f31a02016-04-29 19:04:05 +00003762 // Mark selectors as out of date.
3763 for (auto Sel : SelectorGeneration)
3764 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003765
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003767 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3768 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3770 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003771
3772 switch (Unresolved.Kind) {
3773 case UnresolvedModuleRef::Conflict:
3774 if (ResolvedMod) {
3775 Module::Conflict Conflict;
3776 Conflict.Other = ResolvedMod;
3777 Conflict.Message = Unresolved.String.str();
3778 Unresolved.Mod->Conflicts.push_back(Conflict);
3779 }
3780 continue;
3781
3782 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003783 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003784 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003786
Douglas Gregorfb912652013-03-20 21:10:35 +00003787 case UnresolvedModuleRef::Export:
3788 if (ResolvedMod || Unresolved.IsWildcard)
3789 Unresolved.Mod->Exports.push_back(
3790 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3791 continue;
3792 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003793 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003794 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003795
Graydon Hoaree7196af2016-12-09 21:45:49 +00003796 if (Imported)
3797 Imported->append(ImportedModules.begin(),
3798 ImportedModules.end());
3799
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003800 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3801 // Might be unnecessary as use declarations are only used to build the
3802 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003803
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 InitializeContext();
3805
Richard Smith3d8e97e2013-10-18 06:54:39 +00003806 if (SemaObj)
3807 UpdateSema();
3808
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 if (DeserializationListener)
3810 DeserializationListener->ReaderInitialized(this);
3811
3812 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003813 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003814 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 = FileID::get(PrimaryModule.SLocEntryBaseID
3816 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3817
3818 // If this AST file is a precompiled preamble, then set the
3819 // preamble file ID of the source manager to the file source file
3820 // from which the preamble was built.
3821 if (Type == MK_Preamble) {
3822 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3823 } else if (Type == MK_MainFile) {
3824 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3825 }
3826 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003827
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 // For any Objective-C class definitions we have already loaded, make sure
3829 // that we load any additional categories.
3830 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003831 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 ObjCClassesLoaded[I],
3833 PreviousGeneration);
3834 }
Douglas Gregore060e572013-01-25 01:03:03 +00003835
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003836 if (PP.getHeaderSearchInfo()
3837 .getHeaderSearchOpts()
3838 .ModulesValidateOncePerBuildSession) {
3839 // Now we are certain that the module and all modules it depends on are
3840 // up to date. Create or update timestamp files for modules that are
3841 // located in the module cache (not for PCH files that could be anywhere
3842 // in the filesystem).
3843 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3844 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003845 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003846 updateModuleTimestamp(*M.Mod);
3847 }
3848 }
3849 }
3850
Guy Benyei11169dd2012-12-18 14:30:41 +00003851 return Success;
3852}
3853
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003854static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003855
Ben Langmuir70a1b812015-03-24 04:43:52 +00003856/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3857static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003858 return Stream.canSkipToPos(4) &&
3859 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003860 Stream.Read(8) == 'P' &&
3861 Stream.Read(8) == 'C' &&
3862 Stream.Read(8) == 'H';
3863}
3864
Richard Smith0f99d6a2015-08-09 08:48:41 +00003865static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3866 switch (Kind) {
3867 case MK_PCH:
3868 return 0; // PCH
3869 case MK_ImplicitModule:
3870 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003871 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003872 return 1; // module
3873 case MK_MainFile:
3874 case MK_Preamble:
3875 return 2; // main source file
3876 }
3877 llvm_unreachable("unknown module kind");
3878}
3879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880ASTReader::ASTReadResult
3881ASTReader::ReadASTCore(StringRef FileName,
3882 ModuleKind Type,
3883 SourceLocation ImportLoc,
3884 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003885 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003886 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003887 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 unsigned ClientLoadCapabilities) {
3889 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003891 ModuleManager::AddModuleResult AddResult
3892 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003893 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003894 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003895 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003896
Douglas Gregor7029ce12013-03-19 00:28:20 +00003897 switch (AddResult) {
3898 case ModuleManager::AlreadyLoaded:
3899 return Success;
3900
3901 case ModuleManager::NewlyLoaded:
3902 // Load module file below.
3903 break;
3904
3905 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003906 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003907 // it.
3908 if (ClientLoadCapabilities & ARR_Missing)
3909 return Missing;
3910
3911 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003912 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003913 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003914 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003915 return Failure;
3916
3917 case ModuleManager::OutOfDate:
3918 // We couldn't load the module file because it is out-of-date. If the
3919 // client can handle out-of-date, return it.
3920 if (ClientLoadCapabilities & ARR_OutOfDate)
3921 return OutOfDate;
3922
3923 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003924 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003925 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003926 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 return Failure;
3928 }
3929
Douglas Gregor7029ce12013-03-19 00:28:20 +00003930 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003931
3932 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3933 // module?
3934 if (FileName != "-") {
3935 CurrentDir = llvm::sys::path::parent_path(FileName);
3936 if (CurrentDir.empty()) CurrentDir = ".";
3937 }
3938
3939 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003940 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003941 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003942 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003943
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003945 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003946 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3947 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 return Failure;
3949 }
3950
3951 // This is used for compatibility with older PCH formats.
3952 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003953 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003954 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003955
Chris Lattnerefa77172013-01-20 00:00:22 +00003956 switch (Entry.Kind) {
3957 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003958 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003959 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 Error("invalid record at top-level of AST file");
3961 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003962
Chris Lattnerefa77172013-01-20 00:00:22 +00003963 case llvm::BitstreamEntry::SubBlock:
3964 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 }
3966
Chris Lattnerefa77172013-01-20 00:00:22 +00003967 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 case CONTROL_BLOCK_ID:
3969 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003970 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003972 // Check that we didn't try to load a non-module AST file as a module.
3973 //
3974 // FIXME: Should we also perform the converse check? Loading a module as
3975 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003976 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3977 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003978 F.ModuleName.empty()) {
3979 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3980 if (Result != OutOfDate ||
3981 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3982 Diag(diag::err_module_file_not_module) << FileName;
3983 return Result;
3984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 break;
3986
3987 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003988 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 case OutOfDate: return OutOfDate;
3990 case VersionMismatch: return VersionMismatch;
3991 case ConfigurationMismatch: return ConfigurationMismatch;
3992 case HadErrors: return HadErrors;
3993 }
3994 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003995
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 case AST_BLOCK_ID:
3997 if (!HaveReadControlBlock) {
3998 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003999 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 return VersionMismatch;
4001 }
4002
4003 // Record that we've loaded this module.
4004 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4005 return Success;
4006
4007 default:
4008 if (Stream.SkipBlock()) {
4009 Error("malformed block record in AST file");
4010 return Failure;
4011 }
4012 break;
4013 }
4014 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004015
4016 return Success;
4017}
4018
4019/// Parse a record and blob containing module file extension metadata.
4020static bool parseModuleFileExtensionMetadata(
4021 const SmallVectorImpl<uint64_t> &Record,
4022 StringRef Blob,
4023 ModuleFileExtensionMetadata &Metadata) {
4024 if (Record.size() < 4) return true;
4025
4026 Metadata.MajorVersion = Record[0];
4027 Metadata.MinorVersion = Record[1];
4028
4029 unsigned BlockNameLen = Record[2];
4030 unsigned UserInfoLen = Record[3];
4031
4032 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4033
4034 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4035 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4036 Blob.data() + BlockNameLen + UserInfoLen);
4037 return false;
4038}
4039
4040ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4041 BitstreamCursor &Stream = F.Stream;
4042
4043 RecordData Record;
4044 while (true) {
4045 llvm::BitstreamEntry Entry = Stream.advance();
4046 switch (Entry.Kind) {
4047 case llvm::BitstreamEntry::SubBlock:
4048 if (Stream.SkipBlock())
4049 return Failure;
4050
4051 continue;
4052
4053 case llvm::BitstreamEntry::EndBlock:
4054 return Success;
4055
4056 case llvm::BitstreamEntry::Error:
4057 return HadErrors;
4058
4059 case llvm::BitstreamEntry::Record:
4060 break;
4061 }
4062
4063 Record.clear();
4064 StringRef Blob;
4065 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4066 switch (RecCode) {
4067 case EXTENSION_METADATA: {
4068 ModuleFileExtensionMetadata Metadata;
4069 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4070 return Failure;
4071
4072 // Find a module file extension with this block name.
4073 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4074 if (Known == ModuleFileExtensions.end()) break;
4075
4076 // Form a reader.
4077 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4078 F, Stream)) {
4079 F.ExtensionReaders.push_back(std::move(Reader));
4080 }
4081
4082 break;
4083 }
4084 }
4085 }
4086
4087 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004088}
4089
Richard Smitha7e2cc62015-05-01 01:53:09 +00004090void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 // If there's a listener, notify them that we "read" the translation unit.
4092 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004093 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 Context.getTranslationUnitDecl());
4095
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 // FIXME: Find a better way to deal with collisions between these
4097 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004098
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 // Load the special types.
4100 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4101 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4102 if (!Context.CFConstantStringTypeDecl)
4103 Context.setCFConstantStringType(GetType(String));
4104 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4107 QualType FileType = GetType(File);
4108 if (FileType.isNull()) {
4109 Error("FILE type is NULL");
4110 return;
4111 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004112
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 if (!Context.FILEDecl) {
4114 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4115 Context.setFILEDecl(Typedef->getDecl());
4116 else {
4117 const TagType *Tag = FileType->getAs<TagType>();
4118 if (!Tag) {
4119 Error("Invalid FILE type in AST file");
4120 return;
4121 }
4122 Context.setFILEDecl(Tag->getDecl());
4123 }
4124 }
4125 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4128 QualType Jmp_bufType = GetType(Jmp_buf);
4129 if (Jmp_bufType.isNull()) {
4130 Error("jmp_buf type is NULL");
4131 return;
4132 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004133
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 if (!Context.jmp_bufDecl) {
4135 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4136 Context.setjmp_bufDecl(Typedef->getDecl());
4137 else {
4138 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4139 if (!Tag) {
4140 Error("Invalid jmp_buf type in AST file");
4141 return;
4142 }
4143 Context.setjmp_bufDecl(Tag->getDecl());
4144 }
4145 }
4146 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004147
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4149 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4150 if (Sigjmp_bufType.isNull()) {
4151 Error("sigjmp_buf type is NULL");
4152 return;
4153 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004154
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 if (!Context.sigjmp_bufDecl) {
4156 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4157 Context.setsigjmp_bufDecl(Typedef->getDecl());
4158 else {
4159 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4160 assert(Tag && "Invalid sigjmp_buf type in AST file");
4161 Context.setsigjmp_bufDecl(Tag->getDecl());
4162 }
4163 }
4164 }
4165
4166 if (unsigned ObjCIdRedef
4167 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4168 if (Context.ObjCIdRedefinitionType.isNull())
4169 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4170 }
4171
4172 if (unsigned ObjCClassRedef
4173 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4174 if (Context.ObjCClassRedefinitionType.isNull())
4175 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4176 }
4177
4178 if (unsigned ObjCSelRedef
4179 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4180 if (Context.ObjCSelRedefinitionType.isNull())
4181 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4182 }
4183
4184 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4185 QualType Ucontext_tType = GetType(Ucontext_t);
4186 if (Ucontext_tType.isNull()) {
4187 Error("ucontext_t type is NULL");
4188 return;
4189 }
4190
4191 if (!Context.ucontext_tDecl) {
4192 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4193 Context.setucontext_tDecl(Typedef->getDecl());
4194 else {
4195 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4196 assert(Tag && "Invalid ucontext_t type in AST file");
4197 Context.setucontext_tDecl(Tag->getDecl());
4198 }
4199 }
4200 }
4201 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004202
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4204
4205 // If there were any CUDA special declarations, deserialize them.
4206 if (!CUDASpecialDeclRefs.empty()) {
4207 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4208 Context.setcudaConfigureCallDecl(
4209 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4210 }
Richard Smith56be7542014-03-21 00:33:59 +00004211
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004213 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004214 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004215 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004216 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004217 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004218 if (Import.ImportLoc.isValid())
4219 PP.makeModuleVisible(Imported, Import.ImportLoc);
4220 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004221 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 }
4223 ImportedModules.clear();
4224}
4225
4226void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004227 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004228}
4229
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004230/// \brief Reads and return the signature record from \p PCH's control block, or
4231/// else returns 0.
4232static ASTFileSignature readASTFileSignature(StringRef PCH) {
4233 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004234 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004235 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004236
4237 // Scan for the CONTROL_BLOCK_ID block.
4238 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4239 return 0;
4240
4241 // Scan for SIGNATURE inside the control block.
4242 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004243 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004244 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004245 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004246 return 0;
4247
4248 Record.clear();
4249 StringRef Blob;
4250 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4251 return Record[0];
4252 }
4253}
4254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255/// \brief Retrieve the name of the original source file name
4256/// directly from the AST file, without actually loading the AST
4257/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004258std::string ASTReader::getOriginalSourceFile(
4259 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004260 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004262 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004264 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4265 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 return std::string();
4267 }
4268
4269 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004270 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004271
4272 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004273 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4275 return std::string();
4276 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004277
Chris Lattnere7b154b2013-01-19 21:39:22 +00004278 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004279 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004280 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4281 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004282 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004283
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004284 // Scan for ORIGINAL_FILE inside the control block.
4285 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004286 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004287 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004288 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4289 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004290
Chris Lattnere7b154b2013-01-19 21:39:22 +00004291 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4292 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4293 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004295
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004297 StringRef Blob;
4298 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4299 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004301}
4302
4303namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004304
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 class SimplePCHValidator : public ASTReaderListener {
4306 const LangOptions &ExistingLangOpts;
4307 const TargetOptions &ExistingTargetOpts;
4308 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004309 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004311
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 public:
4313 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4314 const TargetOptions &ExistingTargetOpts,
4315 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004316 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 FileManager &FileMgr)
4318 : ExistingLangOpts(ExistingLangOpts),
4319 ExistingTargetOpts(ExistingTargetOpts),
4320 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004321 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 FileMgr(FileMgr)
4323 {
4324 }
4325
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004326 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4327 bool AllowCompatibleDifferences) override {
4328 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4329 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004331
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004332 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4333 bool AllowCompatibleDifferences) override {
4334 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4335 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004337
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004338 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4339 StringRef SpecificModuleCachePath,
4340 bool Complain) override {
4341 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4342 ExistingModuleCachePath,
4343 nullptr, ExistingLangOpts);
4344 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004345
Craig Topper3e89dfe2014-03-13 02:13:41 +00004346 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4347 bool Complain,
4348 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004349 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004350 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 }
4352 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004353
4354} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004355
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004356bool ASTReader::readASTFileControlBlock(
4357 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004358 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004359 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004360 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004362 // FIXME: This allows use of the VFS; we do not allow use of the
4363 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004364 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 if (!Buffer) {
4366 return true;
4367 }
4368
4369 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004370 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004371
4372 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004373 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004376 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004377 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004378 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004379
4380 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004381 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004382 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004383 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004384
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004386 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004387 bool DoneWithControlBlock = false;
4388 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004389 llvm::BitstreamEntry Entry = Stream.advance();
4390
4391 switch (Entry.Kind) {
4392 case llvm::BitstreamEntry::SubBlock: {
4393 switch (Entry.ID) {
4394 case OPTIONS_BLOCK_ID: {
4395 std::string IgnoredSuggestedPredefines;
4396 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4397 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004398 Listener, IgnoredSuggestedPredefines,
4399 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004400 return true;
4401 break;
4402 }
4403
4404 case INPUT_FILES_BLOCK_ID:
4405 InputFilesCursor = Stream;
4406 if (Stream.SkipBlock() ||
4407 (NeedsInputFiles &&
4408 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4409 return true;
4410 break;
4411
4412 default:
4413 if (Stream.SkipBlock())
4414 return true;
4415 break;
4416 }
4417
4418 continue;
4419 }
4420
4421 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004422 DoneWithControlBlock = true;
4423 break;
Richard Smith0516b182015-09-08 19:40:14 +00004424
4425 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004426 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004427
4428 case llvm::BitstreamEntry::Record:
4429 break;
4430 }
4431
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004432 if (DoneWithControlBlock) break;
4433
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004435 StringRef Blob;
4436 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004437 switch ((ControlRecordTypes)RecCode) {
4438 case METADATA: {
4439 if (Record[0] != VERSION_MAJOR)
4440 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004442 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004443 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004444
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004445 break;
4446 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004447 case MODULE_NAME:
4448 Listener.ReadModuleName(Blob);
4449 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004450 case MODULE_DIRECTORY:
4451 ModuleDir = Blob;
4452 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004453 case MODULE_MAP_FILE: {
4454 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004455 auto Path = ReadString(Record, Idx);
4456 ResolveImportedPath(Path, ModuleDir);
4457 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004458 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004459 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004460 case INPUT_FILE_OFFSETS: {
4461 if (!NeedsInputFiles)
4462 break;
4463
4464 unsigned NumInputFiles = Record[0];
4465 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004466 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004467 for (unsigned I = 0; I != NumInputFiles; ++I) {
4468 // Go find this input file.
4469 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004470
4471 if (isSystemFile && !NeedsSystemInputFiles)
4472 break; // the rest are system input files
4473
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004474 BitstreamCursor &Cursor = InputFilesCursor;
4475 SavedStreamPosition SavedPosition(Cursor);
4476 Cursor.JumpToBit(InputFileOffs[I]);
4477
4478 unsigned Code = Cursor.ReadCode();
4479 RecordData Record;
4480 StringRef Blob;
4481 bool shouldContinue = false;
4482 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4483 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004484 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004485 std::string Filename = Blob;
4486 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004487 shouldContinue = Listener.visitInputFile(
4488 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004489 break;
4490 }
4491 if (!shouldContinue)
4492 break;
4493 }
4494 break;
4495 }
4496
Richard Smithd4b230b2014-10-27 23:01:16 +00004497 case IMPORTS: {
4498 if (!NeedsImports)
4499 break;
4500
4501 unsigned Idx = 0, N = Record.size();
4502 while (Idx < N) {
4503 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004504 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004505 std::string Filename = ReadString(Record, Idx);
4506 ResolveImportedPath(Filename, ModuleDir);
4507 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004508 }
4509 break;
4510 }
4511
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004512 default:
4513 // No other validation to perform.
4514 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 }
4516 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004517
4518 // Look for module file extension blocks, if requested.
4519 if (FindModuleFileExtensions) {
4520 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4521 bool DoneWithExtensionBlock = false;
4522 while (!DoneWithExtensionBlock) {
4523 llvm::BitstreamEntry Entry = Stream.advance();
4524
4525 switch (Entry.Kind) {
4526 case llvm::BitstreamEntry::SubBlock:
4527 if (Stream.SkipBlock())
4528 return true;
4529
4530 continue;
4531
4532 case llvm::BitstreamEntry::EndBlock:
4533 DoneWithExtensionBlock = true;
4534 continue;
4535
4536 case llvm::BitstreamEntry::Error:
4537 return true;
4538
4539 case llvm::BitstreamEntry::Record:
4540 break;
4541 }
4542
4543 Record.clear();
4544 StringRef Blob;
4545 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4546 switch (RecCode) {
4547 case EXTENSION_METADATA: {
4548 ModuleFileExtensionMetadata Metadata;
4549 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4550 return true;
4551
4552 Listener.readModuleFileExtension(Metadata);
4553 break;
4554 }
4555 }
4556 }
4557 }
4558 }
4559
4560 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004561}
4562
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004563bool ASTReader::isAcceptableASTFile(
4564 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004565 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004566 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4567 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004568 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4569 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004570 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004571 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004572 validator,
4573 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004574}
4575
Ben Langmuir2c9af442014-04-10 17:57:43 +00004576ASTReader::ASTReadResult
4577ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 // Enter the submodule block.
4579 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4580 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004581 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583
4584 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4585 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004586 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 RecordData Record;
4588 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004589 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004590
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004591 switch (Entry.Kind) {
4592 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4593 case llvm::BitstreamEntry::Error:
4594 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004595 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004596 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004597 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004598 case llvm::BitstreamEntry::Record:
4599 // The interesting case.
4600 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004602
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004604 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004606 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4607
4608 if ((Kind == SUBMODULE_METADATA) != First) {
4609 Error("submodule metadata record should be at beginning of block");
4610 return Failure;
4611 }
4612 First = false;
4613
4614 // Submodule information is only valid if we have a current module.
4615 // FIXME: Should we error on these cases?
4616 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4617 Kind != SUBMODULE_DEFINITION)
4618 continue;
4619
4620 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 default: // Default behavior: ignore.
4622 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004623
Richard Smith03478d92014-10-23 22:12:14 +00004624 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004625 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004627 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 }
Richard Smith03478d92014-10-23 22:12:14 +00004629
Chris Lattner0e6c9402013-01-20 02:38:54 +00004630 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004631 unsigned Idx = 0;
4632 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4633 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4634 bool IsFramework = Record[Idx++];
4635 bool IsExplicit = Record[Idx++];
4636 bool IsSystem = Record[Idx++];
4637 bool IsExternC = Record[Idx++];
4638 bool InferSubmodules = Record[Idx++];
4639 bool InferExplicitSubmodules = Record[Idx++];
4640 bool InferExportWildcard = Record[Idx++];
4641 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004642 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004643
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004644 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004645 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004647
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 // Retrieve this (sub)module from the module map, creating it if
4649 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004650 CurrentModule =
4651 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4652 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004653
4654 // FIXME: set the definition loc for CurrentModule, or call
4655 // ModMap.setInferredModuleAllowedBy()
4656
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4658 if (GlobalIndex >= SubmodulesLoaded.size() ||
4659 SubmodulesLoaded[GlobalIndex]) {
4660 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004661 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004663
Douglas Gregor7029ce12013-03-19 00:28:20 +00004664 if (!ParentModule) {
4665 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4666 if (CurFile != F.File) {
4667 if (!Diags.isDiagnosticInFlight()) {
4668 Diag(diag::err_module_file_conflict)
4669 << CurrentModule->getTopLevelModuleName()
4670 << CurFile->getName()
4671 << F.File->getName();
4672 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004673 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004674 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004675 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004676
4677 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004678 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004679
Adrian Prantl15bcf702015-06-30 17:39:43 +00004680 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 CurrentModule->IsFromModuleFile = true;
4682 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004683 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 CurrentModule->InferSubmodules = InferSubmodules;
4685 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4686 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004687 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004688 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 if (DeserializationListener)
4690 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004691
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004693
Richard Smith8a3e39a2016-03-28 21:31:09 +00004694 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004695 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004696 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004697 CurrentModule->UnresolvedConflicts.clear();
4698 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004699
4700 // The module is available unless it's missing a requirement; relevant
4701 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4702 // Missing headers that were present when the module was built do not
4703 // make it unavailable -- if we got this far, this must be an explicitly
4704 // imported module file.
4705 CurrentModule->Requirements.clear();
4706 CurrentModule->MissingHeaders.clear();
4707 CurrentModule->IsMissingRequirement =
4708 ParentModule && ParentModule->IsMissingRequirement;
4709 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 break;
4711 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004712
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004714 std::string Filename = Blob;
4715 ResolveImportedPath(F, Filename);
4716 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004717 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004718 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4719 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004720 // This can be a spurious difference caused by changing the VFS to
4721 // point to a different copy of the file, and it is too late to
4722 // to rebuild safely.
4723 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4724 // after input file validation only real problems would remain and we
4725 // could just error. For now, assume it's okay.
4726 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 }
4728 }
4729 break;
4730 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004731
Richard Smith202210b2014-10-24 20:23:01 +00004732 case SUBMODULE_HEADER:
4733 case SUBMODULE_EXCLUDED_HEADER:
4734 case SUBMODULE_PRIVATE_HEADER:
4735 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004736 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4737 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004738 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004739
Richard Smith202210b2014-10-24 20:23:01 +00004740 case SUBMODULE_TEXTUAL_HEADER:
4741 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4742 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4743 // them here.
4744 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004745
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004747 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 break;
4749 }
4750
4751 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004752 std::string Dirname = Blob;
4753 ResolveImportedPath(F, Dirname);
4754 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004756 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4757 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004758 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4759 Error("mismatched umbrella directories in submodule");
4760 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 }
4762 }
4763 break;
4764 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004765
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 F.BaseSubmoduleID = getTotalNumSubmodules();
4768 F.LocalNumSubmodules = Record[0];
4769 unsigned LocalBaseSubmoduleID = Record[1];
4770 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004771 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 // module.
4773 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004774
4775 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 // module.
4777 F.SubmoduleRemap.insertOrReplace(
4778 std::make_pair(LocalBaseSubmoduleID,
4779 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004780
Ben Langmuir52ca6782014-10-20 16:27:32 +00004781 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4782 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 break;
4784 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004785
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004788 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 Unresolved.File = &F;
4790 Unresolved.Mod = CurrentModule;
4791 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004792 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004794 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 }
4796 break;
4797 }
4798
4799 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004800 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004801 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 Unresolved.File = &F;
4803 Unresolved.Mod = CurrentModule;
4804 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004805 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004807 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004809
4810 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004811 // the parsed, unresolved exports around.
4812 CurrentModule->UnresolvedExports.clear();
4813 break;
4814 }
4815 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004816 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 Context.getTargetInfo());
4818 break;
4819 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004820
4821 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004822 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004823 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004824 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004825
4826 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004827 CurrentModule->ConfigMacros.push_back(Blob.str());
4828 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004829
4830 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004831 UnresolvedModuleRef Unresolved;
4832 Unresolved.File = &F;
4833 Unresolved.Mod = CurrentModule;
4834 Unresolved.ID = Record[0];
4835 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4836 Unresolved.IsWildcard = false;
4837 Unresolved.String = Blob;
4838 UnresolvedModuleRefs.push_back(Unresolved);
4839 break;
4840 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004841
4842 case SUBMODULE_INITIALIZERS:
4843 SmallVector<uint32_t, 16> Inits;
4844 for (auto &ID : Record)
4845 Inits.push_back(getGlobalDeclID(F, ID));
4846 Context.addLazyModuleInitializers(CurrentModule, Inits);
4847 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 }
4849 }
4850}
4851
4852/// \brief Parse the record that corresponds to a LangOptions data
4853/// structure.
4854///
4855/// This routine parses the language options from the AST file and then gives
4856/// them to the AST listener if one is set.
4857///
4858/// \returns true if the listener deems the file unacceptable, false otherwise.
4859bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4860 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004861 ASTReaderListener &Listener,
4862 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004863 LangOptions LangOpts;
4864 unsigned Idx = 0;
4865#define LANGOPT(Name, Bits, Default, Description) \
4866 LangOpts.Name = Record[Idx++];
4867#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4868 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4869#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004870#define SANITIZER(NAME, ID) \
4871 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004872#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004873
Ben Langmuircd98cb72015-06-23 18:20:18 +00004874 for (unsigned N = Record[Idx++]; N; --N)
4875 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4876
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4878 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4879 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004880
Ben Langmuird4a667a2015-06-23 18:20:23 +00004881 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004882
4883 // Comment options.
4884 for (unsigned N = Record[Idx++]; N; --N) {
4885 LangOpts.CommentOpts.BlockCommandNames.push_back(
4886 ReadString(Record, Idx));
4887 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004888 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004889
Samuel Antaoee8fb302016-01-06 13:42:12 +00004890 // OpenMP offloading options.
4891 for (unsigned N = Record[Idx++]; N; --N) {
4892 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4893 }
4894
4895 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4896
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004897 return Listener.ReadLanguageOptions(LangOpts, Complain,
4898 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004899}
4900
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004901bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4902 ASTReaderListener &Listener,
4903 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 unsigned Idx = 0;
4905 TargetOptions TargetOpts;
4906 TargetOpts.Triple = ReadString(Record, Idx);
4907 TargetOpts.CPU = ReadString(Record, Idx);
4908 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 for (unsigned N = Record[Idx++]; N; --N) {
4910 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4911 }
4912 for (unsigned N = Record[Idx++]; N; --N) {
4913 TargetOpts.Features.push_back(ReadString(Record, Idx));
4914 }
4915
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004916 return Listener.ReadTargetOptions(TargetOpts, Complain,
4917 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004918}
4919
4920bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4921 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004922 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004924#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004925#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004926 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004927#include "clang/Basic/DiagnosticOptions.def"
4928
Richard Smith3be1cb22014-08-07 00:24:21 +00004929 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004930 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004931 for (unsigned N = Record[Idx++]; N; --N)
4932 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004933
4934 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4935}
4936
4937bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4938 ASTReaderListener &Listener) {
4939 FileSystemOptions FSOpts;
4940 unsigned Idx = 0;
4941 FSOpts.WorkingDir = ReadString(Record, Idx);
4942 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4943}
4944
4945bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4946 bool Complain,
4947 ASTReaderListener &Listener) {
4948 HeaderSearchOptions HSOpts;
4949 unsigned Idx = 0;
4950 HSOpts.Sysroot = ReadString(Record, Idx);
4951
4952 // Include entries.
4953 for (unsigned N = Record[Idx++]; N; --N) {
4954 std::string Path = ReadString(Record, Idx);
4955 frontend::IncludeDirGroup Group
4956 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 bool IsFramework = Record[Idx++];
4958 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004959 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4960 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 }
4962
4963 // System header prefixes.
4964 for (unsigned N = Record[Idx++]; N; --N) {
4965 std::string Prefix = ReadString(Record, Idx);
4966 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004967 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004968 }
4969
4970 HSOpts.ResourceDir = ReadString(Record, Idx);
4971 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004972 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 HSOpts.DisableModuleHash = Record[Idx++];
4974 HSOpts.UseBuiltinIncludes = Record[Idx++];
4975 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4976 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4977 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004978 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004979
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004980 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4981 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004982}
4983
4984bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4985 bool Complain,
4986 ASTReaderListener &Listener,
4987 std::string &SuggestedPredefines) {
4988 PreprocessorOptions PPOpts;
4989 unsigned Idx = 0;
4990
4991 // Macro definitions/undefs
4992 for (unsigned N = Record[Idx++]; N; --N) {
4993 std::string Macro = ReadString(Record, Idx);
4994 bool IsUndef = Record[Idx++];
4995 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4996 }
4997
4998 // Includes
4999 for (unsigned N = Record[Idx++]; N; --N) {
5000 PPOpts.Includes.push_back(ReadString(Record, Idx));
5001 }
5002
5003 // Macro Includes
5004 for (unsigned N = Record[Idx++]; N; --N) {
5005 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5006 }
5007
5008 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005009 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5011 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5012 PPOpts.ObjCXXARCStandardLibrary =
5013 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5014 SuggestedPredefines.clear();
5015 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5016 SuggestedPredefines);
5017}
5018
5019std::pair<ModuleFile *, unsigned>
5020ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5021 GlobalPreprocessedEntityMapType::iterator
5022 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005023 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 "Corrupted global preprocessed entity map");
5025 ModuleFile *M = I->second;
5026 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5027 return std::make_pair(M, LocalIndex);
5028}
5029
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005030llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005031ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5032 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5033 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5034 Mod.NumPreprocessedEntities);
5035
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005036 return llvm::make_range(PreprocessingRecord::iterator(),
5037 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005038}
5039
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005040llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005041ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005042 return llvm::make_range(
5043 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5044 ModuleDeclIterator(this, &Mod,
5045 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005046}
5047
5048PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5049 PreprocessedEntityID PPID = Index+1;
5050 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5051 ModuleFile &M = *PPInfo.first;
5052 unsigned LocalIndex = PPInfo.second;
5053 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5054
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 if (!PP.getPreprocessingRecord()) {
5056 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005057 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005059
5060 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005061 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5062
5063 llvm::BitstreamEntry Entry =
5064 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5065 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005066 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005067
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005069 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5070 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005072 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 RecordData Record;
5074 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005075 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5076 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 switch (RecType) {
5078 case PPD_MACRO_EXPANSION: {
5079 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005080 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005081 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 if (isBuiltin)
5083 Name = getLocalIdentifier(M, Record[1]);
5084 else {
Richard Smith66a81862015-05-04 02:25:31 +00005085 PreprocessedEntityID GlobalID =
5086 getGlobalPreprocessedEntityID(M, Record[1]);
5087 Def = cast<MacroDefinitionRecord>(
5088 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 }
5090
5091 MacroExpansion *ME;
5092 if (isBuiltin)
5093 ME = new (PPRec) MacroExpansion(Name, Range);
5094 else
5095 ME = new (PPRec) MacroExpansion(Def, Range);
5096
5097 return ME;
5098 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005099
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 case PPD_MACRO_DEFINITION: {
5101 // Decode the identifier info and then check again; if the macro is
5102 // still defined and associated with the identifier,
5103 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005104 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105
5106 if (DeserializationListener)
5107 DeserializationListener->MacroDefinitionRead(PPID, MD);
5108
5109 return MD;
5110 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005111
Guy Benyei11169dd2012-12-18 14:30:41 +00005112 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005113 const char *FullFileNameStart = Blob.data() + Record[0];
5114 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005115 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 if (!FullFileName.empty())
5117 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005118
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 // FIXME: Stable encoding
5120 InclusionDirective::InclusionKind Kind
5121 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5122 InclusionDirective *ID
5123 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005124 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 Record[1], Record[3],
5126 File,
5127 Range);
5128 return ID;
5129 }
5130 }
5131
5132 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5133}
5134
5135/// \brief \arg SLocMapI points at a chunk of a module that contains no
5136/// preprocessed entities or the entities it contains are not the ones we are
5137/// looking for. Find the next module that contains entities and return the ID
5138/// of the first entry.
5139PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5140 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5141 ++SLocMapI;
5142 for (GlobalSLocOffsetMapType::const_iterator
5143 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5144 ModuleFile &M = *SLocMapI->second;
5145 if (M.NumPreprocessedEntities)
5146 return M.BasePreprocessedEntityID;
5147 }
5148
5149 return getTotalNumPreprocessedEntities();
5150}
5151
5152namespace {
5153
Guy Benyei11169dd2012-12-18 14:30:41 +00005154struct PPEntityComp {
5155 const ASTReader &Reader;
5156 ModuleFile &M;
5157
5158 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5159
5160 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5161 SourceLocation LHS = getLoc(L);
5162 SourceLocation RHS = getLoc(R);
5163 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5164 }
5165
5166 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5167 SourceLocation LHS = getLoc(L);
5168 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5169 }
5170
5171 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5172 SourceLocation RHS = getLoc(R);
5173 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5174 }
5175
5176 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005177 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 }
5179};
5180
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005181} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005182
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005183PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5184 bool EndsAfter) const {
5185 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005186 return getTotalNumPreprocessedEntities();
5187
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005188 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5189 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5191 "Corrupted global sloc offset map");
5192
5193 if (SLocMapI->second->NumPreprocessedEntities == 0)
5194 return findNextPreprocessedEntity(SLocMapI);
5195
5196 ModuleFile &M = *SLocMapI->second;
5197 typedef const PPEntityOffset *pp_iterator;
5198 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5199 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5200
5201 size_t Count = M.NumPreprocessedEntities;
5202 size_t Half;
5203 pp_iterator First = pp_begin;
5204 pp_iterator PPI;
5205
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005206 if (EndsAfter) {
5207 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005208 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005209 } else {
5210 // Do a binary search manually instead of using std::lower_bound because
5211 // The end locations of entities may be unordered (when a macro expansion
5212 // is inside another macro argument), but for this case it is not important
5213 // whether we get the first macro expansion or its containing macro.
5214 while (Count > 0) {
5215 Half = Count / 2;
5216 PPI = First;
5217 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005218 if (SourceMgr.isBeforeInTranslationUnit(
5219 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005220 First = PPI;
5221 ++First;
5222 Count = Count - Half - 1;
5223 } else
5224 Count = Half;
5225 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005226 }
5227
5228 if (PPI == pp_end)
5229 return findNextPreprocessedEntity(SLocMapI);
5230
5231 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5232}
5233
Guy Benyei11169dd2012-12-18 14:30:41 +00005234/// \brief Returns a pair of [Begin, End) indices of preallocated
5235/// preprocessed entities that \arg Range encompasses.
5236std::pair<unsigned, unsigned>
5237 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5238 if (Range.isInvalid())
5239 return std::make_pair(0,0);
5240 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5241
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005242 PreprocessedEntityID BeginID =
5243 findPreprocessedEntity(Range.getBegin(), false);
5244 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 return std::make_pair(BeginID, EndID);
5246}
5247
5248/// \brief Optionally returns true or false if the preallocated preprocessed
5249/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005250Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 FileID FID) {
5252 if (FID.isInvalid())
5253 return false;
5254
5255 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5256 ModuleFile &M = *PPInfo.first;
5257 unsigned LocalIndex = PPInfo.second;
5258 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005259
Richard Smithcb34bd32016-03-27 07:28:06 +00005260 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005261 if (Loc.isInvalid())
5262 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005263
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5265 return true;
5266 else
5267 return false;
5268}
5269
5270namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005271
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 /// \brief Visitor used to search for information about a header file.
5273 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005275
David Blaikie05785d12013-02-20 22:23:23 +00005276 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005277
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005279 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5280 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005281
5282 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005283 HeaderFileInfoLookupTable *Table
5284 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5285 if (!Table)
5286 return false;
5287
5288 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005289 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005290 if (Pos == Table->end())
5291 return false;
5292
Richard Smithbdf2d932015-07-30 03:37:16 +00005293 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 return true;
5295 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005296
David Blaikie05785d12013-02-20 22:23:23 +00005297 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005298 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005299
5300} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005301
5302HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005303 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005304 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005305 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005307
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 return HeaderFileInfo();
5309}
5310
5311void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005312 using DiagState = DiagnosticsEngine::DiagState;
5313 SmallVector<DiagState *, 32> DiagStates;
5314
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005315 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005317 auto &Record = F.PragmaDiagMappings;
5318 if (Record.empty())
5319 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005320
Richard Smithd230de22017-01-26 01:01:01 +00005321 DiagStates.clear();
5322
5323 auto ReadDiagState =
5324 [&](const DiagState &BasedOn, SourceLocation Loc,
5325 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5326 unsigned BackrefID = Record[Idx++];
5327 if (BackrefID != 0)
5328 return DiagStates[BackrefID - 1];
5329
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005331 Diag.DiagStates.push_back(BasedOn);
5332 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005334 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5335 unsigned DiagID = Record[Idx++];
5336 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005337 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005338 if (Mapping.isPragma() || IncludeNonPragmaStates)
5339 NewState->setMapping(DiagID, Mapping);
5340 }
5341 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5342 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5343 ++Idx;
5344 return NewState;
5345 };
5346
5347 auto *FirstState = ReadDiagState(
5348 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5349 SourceLocation(), F.isModule());
5350 SourceLocation CurStateLoc =
5351 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5352 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5353
5354 if (!F.isModule()) {
5355 Diag.DiagStatesByLoc.CurDiagState = CurState;
5356 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5357
5358 // Preserve the property that the imaginary root file describes the
5359 // current state.
5360 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5361 if (T.empty())
5362 T.push_back({CurState, 0});
5363 else
5364 T[0].State = CurState;
5365 }
5366
5367 while (Idx < Record.size()) {
5368 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5369 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5370 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5371 unsigned Transitions = Record[Idx++];
5372
5373 // Note that we don't need to set up Parent/ParentOffset here, because
5374 // we won't be changing the diagnostic state within imported FileIDs
5375 // (other than perhaps appending to the main source file, which has no
5376 // parent).
5377 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5378 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5379 for (unsigned I = 0; I != Transitions; ++I) {
5380 unsigned Offset = Record[Idx++];
5381 auto *State =
5382 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5383 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 }
5385 }
Richard Smithd230de22017-01-26 01:01:01 +00005386
5387 // Don't try to read these mappings again.
5388 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 }
5390}
5391
5392/// \brief Get the correct cursor and offset for loading a type.
5393ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5394 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5395 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5396 ModuleFile *M = I->second;
5397 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5398}
5399
5400/// \brief Read and return the type with the given index..
5401///
5402/// The index is the type ID, shifted and minus the number of predefs. This
5403/// routine actually reads the record corresponding to the type at the given
5404/// location. It is a helper routine for GetType, which deals with reading type
5405/// IDs.
5406QualType ASTReader::readTypeRecord(unsigned Index) {
5407 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005408 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005409
5410 // Keep track of where we are in the stream, then jump back there
5411 // after reading this type.
5412 SavedStreamPosition SavedPosition(DeclsCursor);
5413
5414 ReadingKindTracker ReadingKind(Read_Type, *this);
5415
5416 // Note that we are loading a type record.
5417 Deserializing AType(this);
5418
5419 unsigned Idx = 0;
5420 DeclsCursor.JumpToBit(Loc.Offset);
5421 RecordData Record;
5422 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005423 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 case TYPE_EXT_QUAL: {
5425 if (Record.size() != 2) {
5426 Error("Incorrect encoding of extended qualifier type");
5427 return QualType();
5428 }
5429 QualType Base = readType(*Loc.F, Record, Idx);
5430 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5431 return Context.getQualifiedType(Base, Quals);
5432 }
5433
5434 case TYPE_COMPLEX: {
5435 if (Record.size() != 1) {
5436 Error("Incorrect encoding of complex type");
5437 return QualType();
5438 }
5439 QualType ElemType = readType(*Loc.F, Record, Idx);
5440 return Context.getComplexType(ElemType);
5441 }
5442
5443 case TYPE_POINTER: {
5444 if (Record.size() != 1) {
5445 Error("Incorrect encoding of pointer type");
5446 return QualType();
5447 }
5448 QualType PointeeType = readType(*Loc.F, Record, Idx);
5449 return Context.getPointerType(PointeeType);
5450 }
5451
Reid Kleckner8a365022013-06-24 17:51:48 +00005452 case TYPE_DECAYED: {
5453 if (Record.size() != 1) {
5454 Error("Incorrect encoding of decayed type");
5455 return QualType();
5456 }
5457 QualType OriginalType = readType(*Loc.F, Record, Idx);
5458 QualType DT = Context.getAdjustedParameterType(OriginalType);
5459 if (!isa<DecayedType>(DT))
5460 Error("Decayed type does not decay");
5461 return DT;
5462 }
5463
Reid Kleckner0503a872013-12-05 01:23:43 +00005464 case TYPE_ADJUSTED: {
5465 if (Record.size() != 2) {
5466 Error("Incorrect encoding of adjusted type");
5467 return QualType();
5468 }
5469 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5470 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5471 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5472 }
5473
Guy Benyei11169dd2012-12-18 14:30:41 +00005474 case TYPE_BLOCK_POINTER: {
5475 if (Record.size() != 1) {
5476 Error("Incorrect encoding of block pointer type");
5477 return QualType();
5478 }
5479 QualType PointeeType = readType(*Loc.F, Record, Idx);
5480 return Context.getBlockPointerType(PointeeType);
5481 }
5482
5483 case TYPE_LVALUE_REFERENCE: {
5484 if (Record.size() != 2) {
5485 Error("Incorrect encoding of lvalue reference type");
5486 return QualType();
5487 }
5488 QualType PointeeType = readType(*Loc.F, Record, Idx);
5489 return Context.getLValueReferenceType(PointeeType, Record[1]);
5490 }
5491
5492 case TYPE_RVALUE_REFERENCE: {
5493 if (Record.size() != 1) {
5494 Error("Incorrect encoding of rvalue reference type");
5495 return QualType();
5496 }
5497 QualType PointeeType = readType(*Loc.F, Record, Idx);
5498 return Context.getRValueReferenceType(PointeeType);
5499 }
5500
5501 case TYPE_MEMBER_POINTER: {
5502 if (Record.size() != 2) {
5503 Error("Incorrect encoding of member pointer type");
5504 return QualType();
5505 }
5506 QualType PointeeType = readType(*Loc.F, Record, Idx);
5507 QualType ClassType = readType(*Loc.F, Record, Idx);
5508 if (PointeeType.isNull() || ClassType.isNull())
5509 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005510
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5512 }
5513
5514 case TYPE_CONSTANT_ARRAY: {
5515 QualType ElementType = readType(*Loc.F, Record, Idx);
5516 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5517 unsigned IndexTypeQuals = Record[2];
5518 unsigned Idx = 3;
5519 llvm::APInt Size = ReadAPInt(Record, Idx);
5520 return Context.getConstantArrayType(ElementType, Size,
5521 ASM, IndexTypeQuals);
5522 }
5523
5524 case TYPE_INCOMPLETE_ARRAY: {
5525 QualType ElementType = readType(*Loc.F, Record, Idx);
5526 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5527 unsigned IndexTypeQuals = Record[2];
5528 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5529 }
5530
5531 case TYPE_VARIABLE_ARRAY: {
5532 QualType ElementType = readType(*Loc.F, Record, Idx);
5533 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5534 unsigned IndexTypeQuals = Record[2];
5535 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5536 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5537 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5538 ASM, IndexTypeQuals,
5539 SourceRange(LBLoc, RBLoc));
5540 }
5541
5542 case TYPE_VECTOR: {
5543 if (Record.size() != 3) {
5544 Error("incorrect encoding of vector type in AST file");
5545 return QualType();
5546 }
5547
5548 QualType ElementType = readType(*Loc.F, Record, Idx);
5549 unsigned NumElements = Record[1];
5550 unsigned VecKind = Record[2];
5551 return Context.getVectorType(ElementType, NumElements,
5552 (VectorType::VectorKind)VecKind);
5553 }
5554
5555 case TYPE_EXT_VECTOR: {
5556 if (Record.size() != 3) {
5557 Error("incorrect encoding of extended vector type in AST file");
5558 return QualType();
5559 }
5560
5561 QualType ElementType = readType(*Loc.F, Record, Idx);
5562 unsigned NumElements = Record[1];
5563 return Context.getExtVectorType(ElementType, NumElements);
5564 }
5565
5566 case TYPE_FUNCTION_NO_PROTO: {
5567 if (Record.size() != 6) {
5568 Error("incorrect encoding of no-proto function type");
5569 return QualType();
5570 }
5571 QualType ResultType = readType(*Loc.F, Record, Idx);
5572 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5573 (CallingConv)Record[4], Record[5]);
5574 return Context.getFunctionNoProtoType(ResultType, Info);
5575 }
5576
5577 case TYPE_FUNCTION_PROTO: {
5578 QualType ResultType = readType(*Loc.F, Record, Idx);
5579
5580 FunctionProtoType::ExtProtoInfo EPI;
5581 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5582 /*hasregparm*/ Record[2],
5583 /*regparm*/ Record[3],
5584 static_cast<CallingConv>(Record[4]),
5585 /*produces*/ Record[5]);
5586
5587 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005588
5589 EPI.Variadic = Record[Idx++];
5590 EPI.HasTrailingReturn = Record[Idx++];
5591 EPI.TypeQuals = Record[Idx++];
5592 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005593 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005594 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005595
5596 unsigned NumParams = Record[Idx++];
5597 SmallVector<QualType, 16> ParamTypes;
5598 for (unsigned I = 0; I != NumParams; ++I)
5599 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5600
John McCall18afab72016-03-01 00:49:02 +00005601 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5602 if (Idx != Record.size()) {
5603 for (unsigned I = 0; I != NumParams; ++I)
5604 ExtParameterInfos.push_back(
5605 FunctionProtoType::ExtParameterInfo
5606 ::getFromOpaqueValue(Record[Idx++]));
5607 EPI.ExtParameterInfos = ExtParameterInfos.data();
5608 }
5609
5610 assert(Idx == Record.size());
5611
Jordan Rose5c382722013-03-08 21:51:21 +00005612 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 }
5614
5615 case TYPE_UNRESOLVED_USING: {
5616 unsigned Idx = 0;
5617 return Context.getTypeDeclType(
5618 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5619 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005620
Guy Benyei11169dd2012-12-18 14:30:41 +00005621 case TYPE_TYPEDEF: {
5622 if (Record.size() != 2) {
5623 Error("incorrect encoding of typedef type");
5624 return QualType();
5625 }
5626 unsigned Idx = 0;
5627 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5628 QualType Canonical = readType(*Loc.F, Record, Idx);
5629 if (!Canonical.isNull())
5630 Canonical = Context.getCanonicalType(Canonical);
5631 return Context.getTypedefType(Decl, Canonical);
5632 }
5633
5634 case TYPE_TYPEOF_EXPR:
5635 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5636
5637 case TYPE_TYPEOF: {
5638 if (Record.size() != 1) {
5639 Error("incorrect encoding of typeof(type) in AST file");
5640 return QualType();
5641 }
5642 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5643 return Context.getTypeOfType(UnderlyingType);
5644 }
5645
5646 case TYPE_DECLTYPE: {
5647 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5648 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5649 }
5650
5651 case TYPE_UNARY_TRANSFORM: {
5652 QualType BaseType = readType(*Loc.F, Record, Idx);
5653 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5654 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5655 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5656 }
5657
Richard Smith74aeef52013-04-26 16:15:35 +00005658 case TYPE_AUTO: {
5659 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005660 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005661 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005662 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005664
Richard Smith600b5262017-01-26 20:40:47 +00005665 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5666 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5667 QualType Deduced = readType(*Loc.F, Record, Idx);
5668 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5669 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5670 IsDependent);
5671 }
5672
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 case TYPE_RECORD: {
5674 if (Record.size() != 2) {
5675 Error("incorrect encoding of record type");
5676 return QualType();
5677 }
5678 unsigned Idx = 0;
5679 bool IsDependent = Record[Idx++];
5680 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5681 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5682 QualType T = Context.getRecordType(RD);
5683 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5684 return T;
5685 }
5686
5687 case TYPE_ENUM: {
5688 if (Record.size() != 2) {
5689 Error("incorrect encoding of enum type");
5690 return QualType();
5691 }
5692 unsigned Idx = 0;
5693 bool IsDependent = Record[Idx++];
5694 QualType T
5695 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5696 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5697 return T;
5698 }
5699
5700 case TYPE_ATTRIBUTED: {
5701 if (Record.size() != 3) {
5702 Error("incorrect encoding of attributed type");
5703 return QualType();
5704 }
5705 QualType modifiedType = readType(*Loc.F, Record, Idx);
5706 QualType equivalentType = readType(*Loc.F, Record, Idx);
5707 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5708 return Context.getAttributedType(kind, modifiedType, equivalentType);
5709 }
5710
5711 case TYPE_PAREN: {
5712 if (Record.size() != 1) {
5713 Error("incorrect encoding of paren type");
5714 return QualType();
5715 }
5716 QualType InnerType = readType(*Loc.F, Record, Idx);
5717 return Context.getParenType(InnerType);
5718 }
5719
5720 case TYPE_PACK_EXPANSION: {
5721 if (Record.size() != 2) {
5722 Error("incorrect encoding of pack expansion type");
5723 return QualType();
5724 }
5725 QualType Pattern = readType(*Loc.F, Record, Idx);
5726 if (Pattern.isNull())
5727 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005728 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 if (Record[1])
5730 NumExpansions = Record[1] - 1;
5731 return Context.getPackExpansionType(Pattern, NumExpansions);
5732 }
5733
5734 case TYPE_ELABORATED: {
5735 unsigned Idx = 0;
5736 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5737 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5738 QualType NamedType = readType(*Loc.F, Record, Idx);
5739 return Context.getElaboratedType(Keyword, NNS, NamedType);
5740 }
5741
5742 case TYPE_OBJC_INTERFACE: {
5743 unsigned Idx = 0;
5744 ObjCInterfaceDecl *ItfD
5745 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5746 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5747 }
5748
Manman Rene6be26c2016-09-13 17:25:08 +00005749 case TYPE_OBJC_TYPE_PARAM: {
5750 unsigned Idx = 0;
5751 ObjCTypeParamDecl *Decl
5752 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5753 unsigned NumProtos = Record[Idx++];
5754 SmallVector<ObjCProtocolDecl*, 4> Protos;
5755 for (unsigned I = 0; I != NumProtos; ++I)
5756 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5757 return Context.getObjCTypeParamType(Decl, Protos);
5758 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005759 case TYPE_OBJC_OBJECT: {
5760 unsigned Idx = 0;
5761 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005762 unsigned NumTypeArgs = Record[Idx++];
5763 SmallVector<QualType, 4> TypeArgs;
5764 for (unsigned I = 0; I != NumTypeArgs; ++I)
5765 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005766 unsigned NumProtos = Record[Idx++];
5767 SmallVector<ObjCProtocolDecl*, 4> Protos;
5768 for (unsigned I = 0; I != NumProtos; ++I)
5769 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005770 bool IsKindOf = Record[Idx++];
5771 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005772 }
5773
5774 case TYPE_OBJC_OBJECT_POINTER: {
5775 unsigned Idx = 0;
5776 QualType Pointee = readType(*Loc.F, Record, Idx);
5777 return Context.getObjCObjectPointerType(Pointee);
5778 }
5779
5780 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5781 unsigned Idx = 0;
5782 QualType Parm = readType(*Loc.F, Record, Idx);
5783 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005784 return Context.getSubstTemplateTypeParmType(
5785 cast<TemplateTypeParmType>(Parm),
5786 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005787 }
5788
5789 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5790 unsigned Idx = 0;
5791 QualType Parm = readType(*Loc.F, Record, Idx);
5792 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5793 return Context.getSubstTemplateTypeParmPackType(
5794 cast<TemplateTypeParmType>(Parm),
5795 ArgPack);
5796 }
5797
5798 case TYPE_INJECTED_CLASS_NAME: {
5799 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5800 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5801 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5802 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005803 const Type *T = nullptr;
5804 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5805 if (const Type *Existing = DI->getTypeForDecl()) {
5806 T = Existing;
5807 break;
5808 }
5809 }
5810 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005811 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005812 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5813 DI->setTypeForDecl(T);
5814 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005815 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005816 }
5817
5818 case TYPE_TEMPLATE_TYPE_PARM: {
5819 unsigned Idx = 0;
5820 unsigned Depth = Record[Idx++];
5821 unsigned Index = Record[Idx++];
5822 bool Pack = Record[Idx++];
5823 TemplateTypeParmDecl *D
5824 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5825 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5826 }
5827
5828 case TYPE_DEPENDENT_NAME: {
5829 unsigned Idx = 0;
5830 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5831 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005832 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 QualType Canon = readType(*Loc.F, Record, Idx);
5834 if (!Canon.isNull())
5835 Canon = Context.getCanonicalType(Canon);
5836 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5837 }
5838
5839 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5840 unsigned Idx = 0;
5841 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5842 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005843 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 unsigned NumArgs = Record[Idx++];
5845 SmallVector<TemplateArgument, 8> Args;
5846 Args.reserve(NumArgs);
5847 while (NumArgs--)
5848 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5849 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005850 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 }
5852
5853 case TYPE_DEPENDENT_SIZED_ARRAY: {
5854 unsigned Idx = 0;
5855
5856 // ArrayType
5857 QualType ElementType = readType(*Loc.F, Record, Idx);
5858 ArrayType::ArraySizeModifier ASM
5859 = (ArrayType::ArraySizeModifier)Record[Idx++];
5860 unsigned IndexTypeQuals = Record[Idx++];
5861
5862 // DependentSizedArrayType
5863 Expr *NumElts = ReadExpr(*Loc.F);
5864 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5865
5866 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5867 IndexTypeQuals, Brackets);
5868 }
5869
5870 case TYPE_TEMPLATE_SPECIALIZATION: {
5871 unsigned Idx = 0;
5872 bool IsDependent = Record[Idx++];
5873 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5874 SmallVector<TemplateArgument, 8> Args;
5875 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5876 QualType Underlying = readType(*Loc.F, Record, Idx);
5877 QualType T;
5878 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005879 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005880 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005881 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005882 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5883 return T;
5884 }
5885
5886 case TYPE_ATOMIC: {
5887 if (Record.size() != 1) {
5888 Error("Incorrect encoding of atomic type");
5889 return QualType();
5890 }
5891 QualType ValueType = readType(*Loc.F, Record, Idx);
5892 return Context.getAtomicType(ValueType);
5893 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005894
Joey Goulye3c85de2016-12-01 11:30:49 +00005895 case TYPE_PIPE: {
5896 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005897 Error("Incorrect encoding of pipe type");
5898 return QualType();
5899 }
5900
5901 // Reading the pipe element type.
5902 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005903 unsigned ReadOnly = Record[1];
5904 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005905 }
5906
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 }
5908 llvm_unreachable("Invalid TypeCode!");
5909}
5910
Richard Smith564417a2014-03-20 21:47:22 +00005911void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5912 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005913 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005914 const RecordData &Record, unsigned &Idx) {
5915 ExceptionSpecificationType EST =
5916 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005917 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005918 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005919 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005920 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005921 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005922 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005923 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005924 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005925 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5926 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005927 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005928 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005929 }
5930}
5931
Guy Benyei11169dd2012-12-18 14:30:41 +00005932class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005933 ModuleFile *F;
5934 ASTReader *Reader;
5935 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 unsigned &Idx;
5937
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005938 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005939 return Reader->ReadSourceLocation(*F, Record, Idx);
5940 }
5941
5942 TypeSourceInfo *GetTypeSourceInfo() {
5943 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5944 }
5945
5946 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5947 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 }
5949
Guy Benyei11169dd2012-12-18 14:30:41 +00005950public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005951 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005953 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005954
5955 // We want compile-time assurance that we've enumerated all of
5956 // these, so unfortunately we have to declare them first, then
5957 // define them out-of-line.
5958#define ABSTRACT_TYPELOC(CLASS, PARENT)
5959#define TYPELOC(CLASS, PARENT) \
5960 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5961#include "clang/AST/TypeLocNodes.def"
5962
5963 void VisitFunctionTypeLoc(FunctionTypeLoc);
5964 void VisitArrayTypeLoc(ArrayTypeLoc);
5965};
5966
5967void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5968 // nothing to do
5969}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005970
Guy Benyei11169dd2012-12-18 14:30:41 +00005971void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005972 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005974 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5975 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5976 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5977 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 }
5979}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005980
Guy Benyei11169dd2012-12-18 14:30:41 +00005981void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005982 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005983}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005984
Guy Benyei11169dd2012-12-18 14:30:41 +00005985void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005986 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005987}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005988
Reid Kleckner8a365022013-06-24 17:51:48 +00005989void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5990 // nothing to do
5991}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005992
Reid Kleckner0503a872013-12-05 01:23:43 +00005993void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5994 // nothing to do
5995}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005996
Guy Benyei11169dd2012-12-18 14:30:41 +00005997void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005998 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005999}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006000
Guy Benyei11169dd2012-12-18 14:30:41 +00006001void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006002 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006003}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006004
Guy Benyei11169dd2012-12-18 14:30:41 +00006005void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006006 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006007}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006008
Guy Benyei11169dd2012-12-18 14:30:41 +00006009void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006010 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006011 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006013
Guy Benyei11169dd2012-12-18 14:30:41 +00006014void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006015 TL.setLBracketLoc(ReadSourceLocation());
6016 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006017 if (Record[Idx++])
6018 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 else
Craig Toppera13603a2014-05-22 05:54:18 +00006020 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006021}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006022
Guy Benyei11169dd2012-12-18 14:30:41 +00006023void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6024 VisitArrayTypeLoc(TL);
6025}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006026
Guy Benyei11169dd2012-12-18 14:30:41 +00006027void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6028 VisitArrayTypeLoc(TL);
6029}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006030
Guy Benyei11169dd2012-12-18 14:30:41 +00006031void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6032 VisitArrayTypeLoc(TL);
6033}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006034
Guy Benyei11169dd2012-12-18 14:30:41 +00006035void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6036 DependentSizedArrayTypeLoc TL) {
6037 VisitArrayTypeLoc(TL);
6038}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006039
Guy Benyei11169dd2012-12-18 14:30:41 +00006040void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6041 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006042 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006043}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006044
Guy Benyei11169dd2012-12-18 14:30:41 +00006045void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006046 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006047}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006048
Guy Benyei11169dd2012-12-18 14:30:41 +00006049void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006050 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006051}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006052
Guy Benyei11169dd2012-12-18 14:30:41 +00006053void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006054 TL.setLocalRangeBegin(ReadSourceLocation());
6055 TL.setLParenLoc(ReadSourceLocation());
6056 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006057 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6058 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006059 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006060 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006061 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 }
6063}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006064
Guy Benyei11169dd2012-12-18 14:30:41 +00006065void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6066 VisitFunctionTypeLoc(TL);
6067}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006068
Guy Benyei11169dd2012-12-18 14:30:41 +00006069void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6070 VisitFunctionTypeLoc(TL);
6071}
6072void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006073 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006074}
6075void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006076 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006077}
6078void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006079 TL.setTypeofLoc(ReadSourceLocation());
6080 TL.setLParenLoc(ReadSourceLocation());
6081 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006082}
6083void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006084 TL.setTypeofLoc(ReadSourceLocation());
6085 TL.setLParenLoc(ReadSourceLocation());
6086 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006087 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006088}
6089void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006090 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006091}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006092
Guy Benyei11169dd2012-12-18 14:30:41 +00006093void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006094 TL.setKWLoc(ReadSourceLocation());
6095 TL.setLParenLoc(ReadSourceLocation());
6096 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006097 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006098}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006099
Guy Benyei11169dd2012-12-18 14:30:41 +00006100void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006101 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006102}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006103
Richard Smith600b5262017-01-26 20:40:47 +00006104void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6105 DeducedTemplateSpecializationTypeLoc TL) {
6106 TL.setTemplateNameLoc(ReadSourceLocation());
6107}
6108
Guy Benyei11169dd2012-12-18 14:30:41 +00006109void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006110 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006111}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006112
Guy Benyei11169dd2012-12-18 14:30:41 +00006113void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006114 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006115}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006116
Guy Benyei11169dd2012-12-18 14:30:41 +00006117void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006118 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 if (TL.hasAttrOperand()) {
6120 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006121 range.setBegin(ReadSourceLocation());
6122 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 TL.setAttrOperandParensRange(range);
6124 }
6125 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006126 if (Record[Idx++])
6127 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006128 else
Craig Toppera13603a2014-05-22 05:54:18 +00006129 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006130 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006131 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006133
Guy Benyei11169dd2012-12-18 14:30:41 +00006134void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006135 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006136}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006137
Guy Benyei11169dd2012-12-18 14:30:41 +00006138void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6139 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006140 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006141}
6142void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6143 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006144 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006145}
6146void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6147 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006148 TL.setTemplateKeywordLoc(ReadSourceLocation());
6149 TL.setTemplateNameLoc(ReadSourceLocation());
6150 TL.setLAngleLoc(ReadSourceLocation());
6151 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006153 TL.setArgLocInfo(
6154 i,
6155 Reader->GetTemplateArgumentLocInfo(
6156 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006157}
6158void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006159 TL.setLParenLoc(ReadSourceLocation());
6160 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006161}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006164 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006165 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006166}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006167
Guy Benyei11169dd2012-12-18 14:30:41 +00006168void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006169 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006170}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006171
Guy Benyei11169dd2012-12-18 14:30:41 +00006172void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006173 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006174 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006175 TL.setNameLoc(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::VisitDependentTemplateSpecializationTypeLoc(
6179 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006180 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006181 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006182 TL.setTemplateKeywordLoc(ReadSourceLocation());
6183 TL.setTemplateNameLoc(ReadSourceLocation());
6184 TL.setLAngleLoc(ReadSourceLocation());
6185 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006187 TL.setArgLocInfo(
6188 I,
6189 Reader->GetTemplateArgumentLocInfo(
6190 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006191}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006192
Guy Benyei11169dd2012-12-18 14:30:41 +00006193void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006194 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006195}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006196
Guy Benyei11169dd2012-12-18 14:30:41 +00006197void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006198 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006200
Manman Rene6be26c2016-09-13 17:25:08 +00006201void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6202 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006203 TL.setProtocolLAngleLoc(ReadSourceLocation());
6204 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006205 }
6206 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006207 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006208}
6209
Guy Benyei11169dd2012-12-18 14:30:41 +00006210void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006211 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006212 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6213 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006214 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006215 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006216 TL.setProtocolLAngleLoc(ReadSourceLocation());
6217 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006219 TL.setProtocolLoc(i, 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::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006223 TL.setStarLoc(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::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006227 TL.setKWLoc(ReadSourceLocation());
6228 TL.setLParenLoc(ReadSourceLocation());
6229 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006230}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006231
Xiuli Pan9c14e282016-01-09 12:53:17 +00006232void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006233 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006234}
Guy Benyei11169dd2012-12-18 14:30:41 +00006235
David L. Jonesbe1557a2016-12-21 00:17:49 +00006236TypeSourceInfo *
6237ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6238 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 QualType InfoTy = readType(F, Record, Idx);
6240 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006241 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006242
6243 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006244 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6246 TLR.Visit(TL);
6247 return TInfo;
6248}
6249
6250QualType ASTReader::GetType(TypeID ID) {
6251 unsigned FastQuals = ID & Qualifiers::FastMask;
6252 unsigned Index = ID >> Qualifiers::FastWidth;
6253
6254 if (Index < NUM_PREDEF_TYPE_IDS) {
6255 QualType T;
6256 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006257 case PREDEF_TYPE_NULL_ID:
6258 return QualType();
6259 case PREDEF_TYPE_VOID_ID:
6260 T = Context.VoidTy;
6261 break;
6262 case PREDEF_TYPE_BOOL_ID:
6263 T = Context.BoolTy;
6264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006265
6266 case PREDEF_TYPE_CHAR_U_ID:
6267 case PREDEF_TYPE_CHAR_S_ID:
6268 // FIXME: Check that the signedness of CharTy is correct!
6269 T = Context.CharTy;
6270 break;
6271
Alexey Baderbdf7c842015-09-15 12:18:29 +00006272 case PREDEF_TYPE_UCHAR_ID:
6273 T = Context.UnsignedCharTy;
6274 break;
6275 case PREDEF_TYPE_USHORT_ID:
6276 T = Context.UnsignedShortTy;
6277 break;
6278 case PREDEF_TYPE_UINT_ID:
6279 T = Context.UnsignedIntTy;
6280 break;
6281 case PREDEF_TYPE_ULONG_ID:
6282 T = Context.UnsignedLongTy;
6283 break;
6284 case PREDEF_TYPE_ULONGLONG_ID:
6285 T = Context.UnsignedLongLongTy;
6286 break;
6287 case PREDEF_TYPE_UINT128_ID:
6288 T = Context.UnsignedInt128Ty;
6289 break;
6290 case PREDEF_TYPE_SCHAR_ID:
6291 T = Context.SignedCharTy;
6292 break;
6293 case PREDEF_TYPE_WCHAR_ID:
6294 T = Context.WCharTy;
6295 break;
6296 case PREDEF_TYPE_SHORT_ID:
6297 T = Context.ShortTy;
6298 break;
6299 case PREDEF_TYPE_INT_ID:
6300 T = Context.IntTy;
6301 break;
6302 case PREDEF_TYPE_LONG_ID:
6303 T = Context.LongTy;
6304 break;
6305 case PREDEF_TYPE_LONGLONG_ID:
6306 T = Context.LongLongTy;
6307 break;
6308 case PREDEF_TYPE_INT128_ID:
6309 T = Context.Int128Ty;
6310 break;
6311 case PREDEF_TYPE_HALF_ID:
6312 T = Context.HalfTy;
6313 break;
6314 case PREDEF_TYPE_FLOAT_ID:
6315 T = Context.FloatTy;
6316 break;
6317 case PREDEF_TYPE_DOUBLE_ID:
6318 T = Context.DoubleTy;
6319 break;
6320 case PREDEF_TYPE_LONGDOUBLE_ID:
6321 T = Context.LongDoubleTy;
6322 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006323 case PREDEF_TYPE_FLOAT128_ID:
6324 T = Context.Float128Ty;
6325 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006326 case PREDEF_TYPE_OVERLOAD_ID:
6327 T = Context.OverloadTy;
6328 break;
6329 case PREDEF_TYPE_BOUND_MEMBER:
6330 T = Context.BoundMemberTy;
6331 break;
6332 case PREDEF_TYPE_PSEUDO_OBJECT:
6333 T = Context.PseudoObjectTy;
6334 break;
6335 case PREDEF_TYPE_DEPENDENT_ID:
6336 T = Context.DependentTy;
6337 break;
6338 case PREDEF_TYPE_UNKNOWN_ANY:
6339 T = Context.UnknownAnyTy;
6340 break;
6341 case PREDEF_TYPE_NULLPTR_ID:
6342 T = Context.NullPtrTy;
6343 break;
6344 case PREDEF_TYPE_CHAR16_ID:
6345 T = Context.Char16Ty;
6346 break;
6347 case PREDEF_TYPE_CHAR32_ID:
6348 T = Context.Char32Ty;
6349 break;
6350 case PREDEF_TYPE_OBJC_ID:
6351 T = Context.ObjCBuiltinIdTy;
6352 break;
6353 case PREDEF_TYPE_OBJC_CLASS:
6354 T = Context.ObjCBuiltinClassTy;
6355 break;
6356 case PREDEF_TYPE_OBJC_SEL:
6357 T = Context.ObjCBuiltinSelTy;
6358 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006359#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6360 case PREDEF_TYPE_##Id##_ID: \
6361 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006362 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006363#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006364 case PREDEF_TYPE_SAMPLER_ID:
6365 T = Context.OCLSamplerTy;
6366 break;
6367 case PREDEF_TYPE_EVENT_ID:
6368 T = Context.OCLEventTy;
6369 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006370 case PREDEF_TYPE_CLK_EVENT_ID:
6371 T = Context.OCLClkEventTy;
6372 break;
6373 case PREDEF_TYPE_QUEUE_ID:
6374 T = Context.OCLQueueTy;
6375 break;
6376 case PREDEF_TYPE_NDRANGE_ID:
6377 T = Context.OCLNDRangeTy;
6378 break;
6379 case PREDEF_TYPE_RESERVE_ID_ID:
6380 T = Context.OCLReserveIDTy;
6381 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006382 case PREDEF_TYPE_AUTO_DEDUCT:
6383 T = Context.getAutoDeductType();
6384 break;
6385
6386 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6387 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006388 break;
6389
6390 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6391 T = Context.ARCUnbridgedCastTy;
6392 break;
6393
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 case PREDEF_TYPE_BUILTIN_FN:
6395 T = Context.BuiltinFnTy;
6396 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006397
6398 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6399 T = Context.OMPArraySectionTy;
6400 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 }
6402
6403 assert(!T.isNull() && "Unknown predefined type");
6404 return T.withFastQualifiers(FastQuals);
6405 }
6406
6407 Index -= NUM_PREDEF_TYPE_IDS;
6408 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6409 if (TypesLoaded[Index].isNull()) {
6410 TypesLoaded[Index] = readTypeRecord(Index);
6411 if (TypesLoaded[Index].isNull())
6412 return QualType();
6413
6414 TypesLoaded[Index]->setFromAST();
6415 if (DeserializationListener)
6416 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6417 TypesLoaded[Index]);
6418 }
6419
6420 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6421}
6422
6423QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6424 return GetType(getGlobalTypeID(F, LocalID));
6425}
6426
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006427serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006428ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6429 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6430 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006431
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6433 return LocalID;
6434
6435 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6436 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6437 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 unsigned GlobalIndex = LocalIndex + I->second;
6440 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6441}
6442
6443TemplateArgumentLocInfo
6444ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6445 TemplateArgument::ArgKind Kind,
6446 const RecordData &Record,
6447 unsigned &Index) {
6448 switch (Kind) {
6449 case TemplateArgument::Expression:
6450 return ReadExpr(F);
6451 case TemplateArgument::Type:
6452 return GetTypeSourceInfo(F, Record, Index);
6453 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006454 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006455 Index);
6456 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6457 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6458 SourceLocation());
6459 }
6460 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006461 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006462 Index);
6463 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6464 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006465 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006466 EllipsisLoc);
6467 }
6468 case TemplateArgument::Null:
6469 case TemplateArgument::Integral:
6470 case TemplateArgument::Declaration:
6471 case TemplateArgument::NullPtr:
6472 case TemplateArgument::Pack:
6473 // FIXME: Is this right?
6474 return TemplateArgumentLocInfo();
6475 }
6476 llvm_unreachable("unexpected template argument loc");
6477}
6478
6479TemplateArgumentLoc
6480ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6481 const RecordData &Record, unsigned &Index) {
6482 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6483
6484 if (Arg.getKind() == TemplateArgument::Expression) {
6485 if (Record[Index++]) // bool InfoHasSameExpr.
6486 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6487 }
6488 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6489 Record, Index));
6490}
6491
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006492const ASTTemplateArgumentListInfo*
6493ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6494 const RecordData &Record,
6495 unsigned &Index) {
6496 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6497 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6498 unsigned NumArgsAsWritten = Record[Index++];
6499 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6500 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6501 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6502 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6503}
6504
Guy Benyei11169dd2012-12-18 14:30:41 +00006505Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6506 return GetDecl(ID);
6507}
6508
Richard Smith50895422015-01-31 03:04:55 +00006509template<typename TemplateSpecializationDecl>
6510static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6511 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6512 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6513}
6514
Richard Smith053f6c62014-05-16 23:01:30 +00006515void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006516 if (NumCurrentElementsDeserializing) {
6517 // We arrange to not care about the complete redeclaration chain while we're
6518 // deserializing. Just remember that the AST has marked this one as complete
6519 // but that it's not actually complete yet, so we know we still need to
6520 // complete it later.
6521 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6522 return;
6523 }
6524
Richard Smith053f6c62014-05-16 23:01:30 +00006525 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6526
Richard Smith053f6c62014-05-16 23:01:30 +00006527 // If this is a named declaration, complete it by looking it up
6528 // within its context.
6529 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006530 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006531 // all mergeable entities within it.
6532 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6533 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6534 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006535 if (!getContext().getLangOpts().CPlusPlus &&
6536 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006537 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006538 // the identifier instead. (For C++ modules, we don't store decls
6539 // in the serialized identifier table, so we do the lookup in the TU.)
6540 auto *II = Name.getAsIdentifierInfo();
6541 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006542 if (II->isOutOfDate())
6543 updateOutOfDateIdentifier(*II);
6544 } else
6545 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006546 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006547 // Find all declarations of this kind from the relevant context.
6548 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6549 auto *DC = cast<DeclContext>(DCDecl);
6550 SmallVector<Decl*, 8> Decls;
6551 FindExternalLexicalDecls(
6552 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6553 }
Richard Smith053f6c62014-05-16 23:01:30 +00006554 }
6555 }
Richard Smith50895422015-01-31 03:04:55 +00006556
6557 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6558 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6559 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6560 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6561 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6562 if (auto *Template = FD->getPrimaryTemplate())
6563 Template->LoadLazySpecializations();
6564 }
Richard Smith053f6c62014-05-16 23:01:30 +00006565}
6566
Richard Smithc2bb8182015-03-24 06:36:48 +00006567CXXCtorInitializer **
6568ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6569 RecordLocation Loc = getLocalBitOffset(Offset);
6570 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6571 SavedStreamPosition SavedPosition(Cursor);
6572 Cursor.JumpToBit(Loc.Offset);
6573 ReadingKindTracker ReadingKind(Read_Decl, *this);
6574
6575 RecordData Record;
6576 unsigned Code = Cursor.ReadCode();
6577 unsigned RecCode = Cursor.readRecord(Code, Record);
6578 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6579 Error("malformed AST file: missing C++ ctor initializers");
6580 return nullptr;
6581 }
6582
6583 unsigned Idx = 0;
6584 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6585}
6586
Guy Benyei11169dd2012-12-18 14:30:41 +00006587CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6588 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006589 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 SavedStreamPosition SavedPosition(Cursor);
6591 Cursor.JumpToBit(Loc.Offset);
6592 ReadingKindTracker ReadingKind(Read_Decl, *this);
6593 RecordData Record;
6594 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006595 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006597 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006598 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006599 }
6600
6601 unsigned Idx = 0;
6602 unsigned NumBases = Record[Idx++];
6603 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6604 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6605 for (unsigned I = 0; I != NumBases; ++I)
6606 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6607 return Bases;
6608}
6609
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006610serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006611ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6612 if (LocalID < NUM_PREDEF_DECL_IDS)
6613 return LocalID;
6614
6615 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6616 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6617 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006618
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 return LocalID + I->second;
6620}
6621
6622bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6623 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006624 // Predefined decls aren't from any module.
6625 if (ID < NUM_PREDEF_DECL_IDS)
6626 return false;
6627
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006628 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006629 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006630}
6631
Douglas Gregor9f782892013-01-21 15:25:38 +00006632ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006634 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6636 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6637 return I->second;
6638}
6639
6640SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6641 if (ID < NUM_PREDEF_DECL_IDS)
6642 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006643
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6645
6646 if (Index > DeclsLoaded.size()) {
6647 Error("declaration ID out-of-range for AST file");
6648 return SourceLocation();
6649 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006650
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 if (Decl *D = DeclsLoaded[Index])
6652 return D->getLocation();
6653
Richard Smithcb34bd32016-03-27 07:28:06 +00006654 SourceLocation Loc;
6655 DeclCursorForID(ID, Loc);
6656 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006657}
6658
Richard Smithfe620d22015-03-05 23:24:12 +00006659static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6660 switch (ID) {
6661 case PREDEF_DECL_NULL_ID:
6662 return nullptr;
6663
6664 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6665 return Context.getTranslationUnitDecl();
6666
6667 case PREDEF_DECL_OBJC_ID_ID:
6668 return Context.getObjCIdDecl();
6669
6670 case PREDEF_DECL_OBJC_SEL_ID:
6671 return Context.getObjCSelDecl();
6672
6673 case PREDEF_DECL_OBJC_CLASS_ID:
6674 return Context.getObjCClassDecl();
6675
6676 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6677 return Context.getObjCProtocolDecl();
6678
6679 case PREDEF_DECL_INT_128_ID:
6680 return Context.getInt128Decl();
6681
6682 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6683 return Context.getUInt128Decl();
6684
6685 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6686 return Context.getObjCInstanceTypeDecl();
6687
6688 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6689 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006690
Richard Smith9b88a4c2015-07-27 05:40:23 +00006691 case PREDEF_DECL_VA_LIST_TAG:
6692 return Context.getVaListTagDecl();
6693
Charles Davisc7d5c942015-09-17 20:55:33 +00006694 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6695 return Context.getBuiltinMSVaListDecl();
6696
Richard Smithf19e1272015-03-07 00:04:49 +00006697 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6698 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006699
6700 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6701 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006702
6703 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6704 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006705
6706 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6707 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006708
6709 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6710 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006711 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006712 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006713}
6714
Richard Smithcd45dbc2014-04-19 03:48:30 +00006715Decl *ASTReader::GetExistingDecl(DeclID ID) {
6716 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006717 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6718 if (D) {
6719 // Track that we have merged the declaration with ID \p ID into the
6720 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006721 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006722 if (Merged.empty())
6723 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 }
Richard Smithfe620d22015-03-05 23:24:12 +00006725 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006727
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6729
6730 if (Index >= DeclsLoaded.size()) {
6731 assert(0 && "declaration ID out-of-range for AST file");
6732 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006733 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006735
6736 return DeclsLoaded[Index];
6737}
6738
6739Decl *ASTReader::GetDecl(DeclID ID) {
6740 if (ID < NUM_PREDEF_DECL_IDS)
6741 return GetExistingDecl(ID);
6742
6743 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6744
6745 if (Index >= DeclsLoaded.size()) {
6746 assert(0 && "declaration ID out-of-range for AST file");
6747 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006748 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006749 }
6750
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 if (!DeclsLoaded[Index]) {
6752 ReadDeclRecord(ID);
6753 if (DeserializationListener)
6754 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6755 }
6756
6757 return DeclsLoaded[Index];
6758}
6759
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006760DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 DeclID GlobalID) {
6762 if (GlobalID < NUM_PREDEF_DECL_IDS)
6763 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006764
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6766 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6767 ModuleFile *Owner = I->second;
6768
6769 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6770 = M.GlobalToLocalDeclIDs.find(Owner);
6771 if (Pos == M.GlobalToLocalDeclIDs.end())
6772 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006773
Guy Benyei11169dd2012-12-18 14:30:41 +00006774 return GlobalID - Owner->BaseDeclID + Pos->second;
6775}
6776
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006777serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 const RecordData &Record,
6779 unsigned &Idx) {
6780 if (Idx >= Record.size()) {
6781 Error("Corrupted AST file");
6782 return 0;
6783 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006784
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 return getGlobalDeclID(F, Record[Idx++]);
6786}
6787
6788/// \brief Resolve the offset of a statement into a statement.
6789///
6790/// This operation will read a new statement from the external
6791/// source each time it is called, and is meant to be used via a
6792/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6793Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6794 // Switch case IDs are per Decl.
6795 ClearSwitchCaseIDs();
6796
6797 // Offset here is a global offset across the entire chain.
6798 RecordLocation Loc = getLocalBitOffset(Offset);
6799 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6800 return ReadStmtFromStream(*Loc.F);
6801}
6802
Richard Smith3cb15722015-08-05 22:41:45 +00006803void ASTReader::FindExternalLexicalDecls(
6804 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6805 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006806 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6807
Richard Smith9ccdd932015-08-06 22:14:12 +00006808 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006809 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6810 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6811 auto K = (Decl::Kind)+LexicalDecls[I];
6812 if (!IsKindWeWant(K))
6813 continue;
6814
6815 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6816
6817 // Don't add predefined declarations to the lexical context more
6818 // than once.
6819 if (ID < NUM_PREDEF_DECL_IDS) {
6820 if (PredefsVisited[ID])
6821 continue;
6822
6823 PredefsVisited[ID] = true;
6824 }
6825
6826 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006827 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006828 if (!DC->isDeclInLexicalTraversal(D))
6829 Decls.push_back(D);
6830 }
6831 }
6832 };
6833
6834 if (isa<TranslationUnitDecl>(DC)) {
6835 for (auto Lexical : TULexicalDecls)
6836 Visit(Lexical.first, Lexical.second);
6837 } else {
6838 auto I = LexicalDecls.find(DC);
6839 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006840 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006841 }
6842
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006844}
6845
6846namespace {
6847
6848class DeclIDComp {
6849 ASTReader &Reader;
6850 ModuleFile &Mod;
6851
6852public:
6853 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6854
6855 bool operator()(LocalDeclID L, LocalDeclID R) const {
6856 SourceLocation LHS = getLocation(L);
6857 SourceLocation RHS = getLocation(R);
6858 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6859 }
6860
6861 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6862 SourceLocation RHS = getLocation(R);
6863 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6864 }
6865
6866 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6867 SourceLocation LHS = getLocation(L);
6868 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6869 }
6870
6871 SourceLocation getLocation(LocalDeclID ID) const {
6872 return Reader.getSourceManager().getFileLoc(
6873 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6874 }
6875};
6876
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006877} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006878
6879void ASTReader::FindFileRegionDecls(FileID File,
6880 unsigned Offset, unsigned Length,
6881 SmallVectorImpl<Decl *> &Decls) {
6882 SourceManager &SM = getSourceManager();
6883
6884 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6885 if (I == FileDeclIDs.end())
6886 return;
6887
6888 FileDeclsInfo &DInfo = I->second;
6889 if (DInfo.Decls.empty())
6890 return;
6891
6892 SourceLocation
6893 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6894 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6895
6896 DeclIDComp DIDComp(*this, *DInfo.Mod);
6897 ArrayRef<serialization::LocalDeclID>::iterator
6898 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6899 BeginLoc, DIDComp);
6900 if (BeginIt != DInfo.Decls.begin())
6901 --BeginIt;
6902
6903 // If we are pointing at a top-level decl inside an objc container, we need
6904 // to backtrack until we find it otherwise we will fail to report that the
6905 // region overlaps with an objc container.
6906 while (BeginIt != DInfo.Decls.begin() &&
6907 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6908 ->isTopLevelDeclInObjCContainer())
6909 --BeginIt;
6910
6911 ArrayRef<serialization::LocalDeclID>::iterator
6912 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6913 EndLoc, DIDComp);
6914 if (EndIt != DInfo.Decls.end())
6915 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006916
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 for (ArrayRef<serialization::LocalDeclID>::iterator
6918 DIt = BeginIt; DIt != EndIt; ++DIt)
6919 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6920}
6921
Richard Smith9ce12e32013-02-07 03:30:24 +00006922bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006923ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6924 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006925 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 "DeclContext has no visible decls in storage");
6927 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006928 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006929
Richard Smithd88a7f12015-09-01 20:35:42 +00006930 auto It = Lookups.find(DC);
6931 if (It == Lookups.end())
6932 return false;
6933
Richard Smith8c913ec2014-08-14 02:21:01 +00006934 Deserializing LookupResults(this);
6935
Richard Smithd88a7f12015-09-01 20:35:42 +00006936 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006938 for (DeclID ID : It->second.Table.find(Name)) {
6939 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6940 if (ND->getDeclName() == Name)
6941 Decls.push_back(ND);
6942 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006943
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 ++NumVisibleDeclContextsRead;
6945 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006946 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006947}
6948
Guy Benyei11169dd2012-12-18 14:30:41 +00006949void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6950 if (!DC->hasExternalVisibleStorage())
6951 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006952
6953 auto It = Lookups.find(DC);
6954 assert(It != Lookups.end() &&
6955 "have external visible storage but no lookup tables");
6956
Craig Topper79be4cd2013-07-05 04:33:53 +00006957 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958
Richard Smithd88a7f12015-09-01 20:35:42 +00006959 for (DeclID ID : It->second.Table.findAll()) {
6960 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6961 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 }
6963
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 ++NumVisibleDeclContextsRead;
6965
Craig Topper79be4cd2013-07-05 04:33:53 +00006966 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6968 }
6969 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6970}
6971
Richard Smithd88a7f12015-09-01 20:35:42 +00006972const serialization::reader::DeclContextLookupTable *
6973ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6974 auto I = Lookups.find(Primary);
6975 return I == Lookups.end() ? nullptr : &I->second;
6976}
6977
Guy Benyei11169dd2012-12-18 14:30:41 +00006978/// \brief Under non-PCH compilation the consumer receives the objc methods
6979/// before receiving the implementation, and codegen depends on this.
6980/// We simulate this by deserializing and passing to consumer the methods of the
6981/// implementation before passing the deserialized implementation decl.
6982static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6983 ASTConsumer *Consumer) {
6984 assert(ImplD && Consumer);
6985
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006986 for (auto *I : ImplD->methods())
6987 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006988
6989 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6990}
6991
6992void ASTReader::PassInterestingDeclsToConsumer() {
6993 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006994
6995 if (PassingDeclsToConsumer)
6996 return;
6997
6998 // Guard variable to avoid recursively redoing the process of passing
6999 // decls to consumer.
7000 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7001 true);
7002
Richard Smith9e2341d2015-03-23 03:25:59 +00007003 // Ensure that we've loaded all potentially-interesting declarations
7004 // that need to be eagerly loaded.
7005 for (auto ID : EagerlyDeserializedDecls)
7006 GetDecl(ID);
7007 EagerlyDeserializedDecls.clear();
7008
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 while (!InterestingDecls.empty()) {
7010 Decl *D = InterestingDecls.front();
7011 InterestingDecls.pop_front();
7012
7013 PassInterestingDeclToConsumer(D);
7014 }
7015}
7016
7017void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7018 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7019 PassObjCImplDeclToConsumer(ImplD, Consumer);
7020 else
7021 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7022}
7023
7024void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7025 this->Consumer = Consumer;
7026
Richard Smith9e2341d2015-03-23 03:25:59 +00007027 if (Consumer)
7028 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007029
7030 if (DeserializationListener)
7031 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007032}
7033
7034void ASTReader::PrintStats() {
7035 std::fprintf(stderr, "*** AST File Statistics:\n");
7036
7037 unsigned NumTypesLoaded
7038 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7039 QualType());
7040 unsigned NumDeclsLoaded
7041 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007042 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 unsigned NumIdentifiersLoaded
7044 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7045 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007046 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007047 unsigned NumMacrosLoaded
7048 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7049 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007050 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007051 unsigned NumSelectorsLoaded
7052 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7053 SelectorsLoaded.end(),
7054 Selector());
7055
7056 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7057 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7058 NumSLocEntriesRead, TotalNumSLocEntries,
7059 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7060 if (!TypesLoaded.empty())
7061 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7062 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7063 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7064 if (!DeclsLoaded.empty())
7065 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7066 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7067 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7068 if (!IdentifiersLoaded.empty())
7069 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7070 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7071 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7072 if (!MacrosLoaded.empty())
7073 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7074 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7075 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7076 if (!SelectorsLoaded.empty())
7077 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7078 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7079 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7080 if (TotalNumStatements)
7081 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7082 NumStatementsRead, TotalNumStatements,
7083 ((float)NumStatementsRead/TotalNumStatements * 100));
7084 if (TotalNumMacros)
7085 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7086 NumMacrosRead, TotalNumMacros,
7087 ((float)NumMacrosRead/TotalNumMacros * 100));
7088 if (TotalLexicalDeclContexts)
7089 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7090 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7091 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7092 * 100));
7093 if (TotalVisibleDeclContexts)
7094 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7095 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7096 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7097 * 100));
7098 if (TotalNumMethodPoolEntries) {
7099 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7100 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7101 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7102 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007104 if (NumMethodPoolLookups) {
7105 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7106 NumMethodPoolHits, NumMethodPoolLookups,
7107 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7108 }
7109 if (NumMethodPoolTableLookups) {
7110 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7111 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7112 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7113 * 100.0));
7114 }
7115
Douglas Gregor00a50f72013-01-25 00:38:33 +00007116 if (NumIdentifierLookupHits) {
7117 std::fprintf(stderr,
7118 " %u / %u identifier table lookups succeeded (%f%%)\n",
7119 NumIdentifierLookupHits, NumIdentifierLookups,
7120 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7121 }
7122
Douglas Gregore060e572013-01-25 01:03:03 +00007123 if (GlobalIndex) {
7124 std::fprintf(stderr, "\n");
7125 GlobalIndex->printStats();
7126 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007127
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 std::fprintf(stderr, "\n");
7129 dump();
7130 std::fprintf(stderr, "\n");
7131}
7132
7133template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007134static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007135dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007136 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007137 InitialCapacity> &Map) {
7138 if (Map.begin() == Map.end())
7139 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7142 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007143 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 I != IEnd; ++I) {
7145 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7146 << "\n";
7147 }
7148}
7149
Yaron Kerencdae9412016-01-29 19:38:18 +00007150LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7152 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7153 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7154 dumpModuleIDMap("Global type map", GlobalTypeMap);
7155 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7156 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7157 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7158 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7159 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007160 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007162
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007164 for (ModuleFile &M : ModuleMgr)
7165 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007166}
7167
7168/// Return the amount of memory used by memory buffers, breaking down
7169/// by heap-backed versus mmap'ed memory.
7170void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007171 for (ModuleFile &I : ModuleMgr) {
7172 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007173 size_t bytes = buf->getBufferSize();
7174 switch (buf->getBufferKind()) {
7175 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7176 sizes.malloc_bytes += bytes;
7177 break;
7178 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7179 sizes.mmap_bytes += bytes;
7180 break;
7181 }
7182 }
7183 }
7184}
7185
7186void ASTReader::InitializeSema(Sema &S) {
7187 SemaObj = &S;
7188 S.addExternalSource(this);
7189
7190 // Makes sure any declarations that were deserialized "too early"
7191 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007192 for (uint64_t ID : PreloadedDeclIDs) {
7193 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7194 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007196 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007197
Richard Smith3d8e97e2013-10-18 06:54:39 +00007198 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 if (!FPPragmaOptions.empty()) {
7200 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7201 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7202 }
7203
Yaxun Liu5b746652016-12-18 05:18:55 +00007204 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7205 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7206 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007207
7208 UpdateSema();
7209}
7210
7211void ASTReader::UpdateSema() {
7212 assert(SemaObj && "no Sema to update");
7213
7214 // Load the offsets of the declarations that Sema references.
7215 // They will be lazily deserialized when needed.
7216 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007217 assert(SemaDeclRefs.size() % 3 == 0);
7218 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007219 if (!SemaObj->StdNamespace)
7220 SemaObj->StdNamespace = SemaDeclRefs[I];
7221 if (!SemaObj->StdBadAlloc)
7222 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007223 if (!SemaObj->StdAlignValT)
7224 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007225 }
7226 SemaDeclRefs.clear();
7227 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007228
Nico Weber779355f2016-03-02 23:22:00 +00007229 // Update the state of pragmas. Use the same API as if we had encountered the
7230 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007231 if(OptimizeOffPragmaLocation.isValid())
7232 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007233 if (PragmaMSStructState != -1)
7234 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007235 if (PointersToMembersPragmaLocation.isValid()) {
7236 SemaObj->ActOnPragmaMSPointersToMembers(
7237 (LangOptions::PragmaMSPointersToMembersKind)
7238 PragmaMSPointersToMembersState,
7239 PointersToMembersPragmaLocation);
7240 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007241 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242}
7243
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007244IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 // Note that we are loading an identifier.
7246 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007247
Douglas Gregor7211ac12013-01-25 23:32:03 +00007248 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007249 NumIdentifierLookups,
7250 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007251
7252 // We don't need to do identifier table lookups in C++ modules (we preload
7253 // all interesting declarations, and don't need to use the scope for name
7254 // lookups). Perform the lookup in PCH files, though, since we don't build
7255 // a complete initial identifier table if we're carrying on from a PCH.
7256 if (Context.getLangOpts().CPlusPlus) {
7257 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007258 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007259 break;
7260 } else {
7261 // If there is a global index, look there first to determine which modules
7262 // provably do not have any results for this identifier.
7263 GlobalModuleIndex::HitSet Hits;
7264 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7265 if (!loadGlobalIndex()) {
7266 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7267 HitsPtr = &Hits;
7268 }
7269 }
7270
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007271 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007272 }
7273
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 IdentifierInfo *II = Visitor.getIdentifierInfo();
7275 markIdentifierUpToDate(II);
7276 return II;
7277}
7278
7279namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007280
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 /// \brief An identifier-lookup iterator that enumerates all of the
7282 /// identifiers stored within a set of AST files.
7283 class ASTIdentifierIterator : public IdentifierIterator {
7284 /// \brief The AST reader whose identifiers are being enumerated.
7285 const ASTReader &Reader;
7286
7287 /// \brief The current index into the chain of AST files stored in
7288 /// the AST reader.
7289 unsigned Index;
7290
7291 /// \brief The current position within the identifier lookup table
7292 /// of the current AST file.
7293 ASTIdentifierLookupTable::key_iterator Current;
7294
7295 /// \brief The end position within the identifier lookup table of
7296 /// the current AST file.
7297 ASTIdentifierLookupTable::key_iterator End;
7298
Ben Langmuir537c5b52016-05-04 00:53:13 +00007299 /// \brief Whether to skip any modules in the ASTReader.
7300 bool SkipModules;
7301
Guy Benyei11169dd2012-12-18 14:30:41 +00007302 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007303 explicit ASTIdentifierIterator(const ASTReader &Reader,
7304 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007305
Craig Topper3e89dfe2014-03-13 02:13:41 +00007306 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007307 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007308
7309} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007310
Ben Langmuir537c5b52016-05-04 00:53:13 +00007311ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7312 bool SkipModules)
7313 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007314}
7315
7316StringRef ASTIdentifierIterator::Next() {
7317 while (Current == End) {
7318 // If we have exhausted all of our AST files, we're done.
7319 if (Index == 0)
7320 return StringRef();
7321
7322 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007323 ModuleFile &F = Reader.ModuleMgr[Index];
7324 if (SkipModules && F.isModule())
7325 continue;
7326
7327 ASTIdentifierLookupTable *IdTable =
7328 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007329 Current = IdTable->key_begin();
7330 End = IdTable->key_end();
7331 }
7332
7333 // We have any identifiers remaining in the current AST file; return
7334 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007335 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007337 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007338}
7339
Ben Langmuir537c5b52016-05-04 00:53:13 +00007340namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007341
Ben Langmuir537c5b52016-05-04 00:53:13 +00007342/// A utility for appending two IdentifierIterators.
7343class ChainedIdentifierIterator : public IdentifierIterator {
7344 std::unique_ptr<IdentifierIterator> Current;
7345 std::unique_ptr<IdentifierIterator> Queued;
7346
7347public:
7348 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7349 std::unique_ptr<IdentifierIterator> Second)
7350 : Current(std::move(First)), Queued(std::move(Second)) {}
7351
7352 StringRef Next() override {
7353 if (!Current)
7354 return StringRef();
7355
7356 StringRef result = Current->Next();
7357 if (!result.empty())
7358 return result;
7359
7360 // Try the queued iterator, which may itself be empty.
7361 Current.reset();
7362 std::swap(Current, Queued);
7363 return Next();
7364 }
7365};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007366
Ben Langmuir537c5b52016-05-04 00:53:13 +00007367} // end anonymous namespace.
7368
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007369IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007370 if (!loadGlobalIndex()) {
7371 std::unique_ptr<IdentifierIterator> ReaderIter(
7372 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7373 std::unique_ptr<IdentifierIterator> ModulesIter(
7374 GlobalIndex->createIdentifierIterator());
7375 return new ChainedIdentifierIterator(std::move(ReaderIter),
7376 std::move(ModulesIter));
7377 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007378
Guy Benyei11169dd2012-12-18 14:30:41 +00007379 return new ASTIdentifierIterator(*this);
7380}
7381
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007382namespace clang {
7383namespace serialization {
7384
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 class ReadMethodPoolVisitor {
7386 ASTReader &Reader;
7387 Selector Sel;
7388 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007389 unsigned InstanceBits;
7390 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007391 bool InstanceHasMoreThanOneDecl;
7392 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007393 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7394 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007395
7396 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007397 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007398 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007399 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007400 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7401 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007402
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007403 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 if (!M.SelectorLookupTable)
7405 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007406
Guy Benyei11169dd2012-12-18 14:30:41 +00007407 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007408 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 return true;
7410
Richard Smithbdf2d932015-07-30 03:37:16 +00007411 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 ASTSelectorLookupTable *PoolTable
7413 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007414 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 if (Pos == PoolTable->end())
7416 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007417
Richard Smithbdf2d932015-07-30 03:37:16 +00007418 ++Reader.NumMethodPoolTableHits;
7419 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007420 // FIXME: Not quite happy with the statistics here. We probably should
7421 // disable this tracking when called via LoadSelector.
7422 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007423 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007424 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007425 if (Reader.DeserializationListener)
7426 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007427
Richard Smithbdf2d932015-07-30 03:37:16 +00007428 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7429 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7430 InstanceBits = Data.InstanceBits;
7431 FactoryBits = Data.FactoryBits;
7432 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7433 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 return true;
7435 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007436
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007438 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7439 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007440 }
7441
7442 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007443 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 return FactoryMethods;
7445 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007446
7447 unsigned getInstanceBits() const { return InstanceBits; }
7448 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007449 bool instanceHasMoreThanOneDecl() const {
7450 return InstanceHasMoreThanOneDecl;
7451 }
7452 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007454
7455} // end namespace serialization
7456} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007457
7458/// \brief Add the given set of methods to the method list.
7459static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7460 ObjCMethodList &List) {
7461 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7462 S.addMethodToGlobalList(&List, Methods[I]);
7463 }
7464}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007465
Guy Benyei11169dd2012-12-18 14:30:41 +00007466void ASTReader::ReadMethodPool(Selector Sel) {
7467 // Get the selector generation and update it to the current generation.
7468 unsigned &Generation = SelectorGeneration[Sel];
7469 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007470 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007471 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007472
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007474 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007476 ModuleMgr.visit(Visitor);
7477
Guy Benyei11169dd2012-12-18 14:30:41 +00007478 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007479 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007481
7482 ++NumMethodPoolHits;
7483
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 if (!getSema())
7485 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 Sema &S = *getSema();
7488 Sema::GlobalMethodPool::iterator Pos
7489 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007490
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007491 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007492 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007493 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007494 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007495
7496 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7497 // when building a module we keep every method individually and may need to
7498 // update hasMoreThanOneDecl as we add the methods.
7499 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7500 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007501}
7502
Manman Rena0f31a02016-04-29 19:04:05 +00007503void ASTReader::updateOutOfDateSelector(Selector Sel) {
7504 if (SelectorOutOfDate[Sel])
7505 ReadMethodPool(Sel);
7506}
7507
Guy Benyei11169dd2012-12-18 14:30:41 +00007508void ASTReader::ReadKnownNamespaces(
7509 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7510 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007511
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007513 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7515 Namespaces.push_back(Namespace);
7516 }
7517}
7518
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007519void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007520 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007521 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7522 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007523 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007524 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007525 Undefined.insert(std::make_pair(D, Loc));
7526 }
7527}
Nick Lewycky8334af82013-01-26 00:35:08 +00007528
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007529void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7530 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7531 Exprs) {
7532 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7533 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7534 uint64_t Count = DelayedDeleteExprs[Idx++];
7535 for (uint64_t C = 0; C < Count; ++C) {
7536 SourceLocation DeleteLoc =
7537 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7538 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7539 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7540 }
7541 }
7542}
7543
Guy Benyei11169dd2012-12-18 14:30:41 +00007544void ASTReader::ReadTentativeDefinitions(
7545 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7546 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7547 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7548 if (Var)
7549 TentativeDefs.push_back(Var);
7550 }
7551 TentativeDefinitions.clear();
7552}
7553
7554void ASTReader::ReadUnusedFileScopedDecls(
7555 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7556 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7557 DeclaratorDecl *D
7558 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7559 if (D)
7560 Decls.push_back(D);
7561 }
7562 UnusedFileScopedDecls.clear();
7563}
7564
7565void ASTReader::ReadDelegatingConstructors(
7566 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7567 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7568 CXXConstructorDecl *D
7569 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7570 if (D)
7571 Decls.push_back(D);
7572 }
7573 DelegatingCtorDecls.clear();
7574}
7575
7576void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7577 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7578 TypedefNameDecl *D
7579 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7580 if (D)
7581 Decls.push_back(D);
7582 }
7583 ExtVectorDecls.clear();
7584}
7585
Nico Weber72889432014-09-06 01:25:55 +00007586void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7587 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7588 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7589 ++I) {
7590 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7591 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7592 if (D)
7593 Decls.insert(D);
7594 }
7595 UnusedLocalTypedefNameCandidates.clear();
7596}
7597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598void ASTReader::ReadReferencedSelectors(
7599 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7600 if (ReferencedSelectorsData.empty())
7601 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007602
Guy Benyei11169dd2012-12-18 14:30:41 +00007603 // If there are @selector references added them to its pool. This is for
7604 // implementation of -Wselector.
7605 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7606 unsigned I = 0;
7607 while (I < DataSize) {
7608 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7609 SourceLocation SelLoc
7610 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7611 Sels.push_back(std::make_pair(Sel, SelLoc));
7612 }
7613 ReferencedSelectorsData.clear();
7614}
7615
7616void ASTReader::ReadWeakUndeclaredIdentifiers(
7617 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7618 if (WeakUndeclaredIdentifiers.empty())
7619 return;
7620
7621 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007622 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007624 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7626 SourceLocation Loc
7627 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7628 bool Used = WeakUndeclaredIdentifiers[I++];
7629 WeakInfo WI(AliasId, Loc);
7630 WI.setUsed(Used);
7631 WeakIDs.push_back(std::make_pair(WeakId, WI));
7632 }
7633 WeakUndeclaredIdentifiers.clear();
7634}
7635
7636void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7637 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7638 ExternalVTableUse VT;
7639 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7640 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7641 VT.DefinitionRequired = VTableUses[Idx++];
7642 VTables.push_back(VT);
7643 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007644
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 VTableUses.clear();
7646}
7647
7648void ASTReader::ReadPendingInstantiations(
7649 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7650 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7651 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7652 SourceLocation Loc
7653 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7654
7655 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007656 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 PendingInstantiations.clear();
7658}
7659
Richard Smithe40f2ba2013-08-07 21:41:30 +00007660void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007661 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7662 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007663 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7664 /* In loop */) {
7665 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7666
Justin Lebar28f09c52016-10-10 16:26:08 +00007667 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007668 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7669
7670 ModuleFile *F = getOwningModuleFile(LT->D);
7671 assert(F && "No module");
7672
7673 unsigned TokN = LateParsedTemplates[Idx++];
7674 LT->Toks.reserve(TokN);
7675 for (unsigned T = 0; T < TokN; ++T)
7676 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7677
Justin Lebar28f09c52016-10-10 16:26:08 +00007678 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007679 }
7680
7681 LateParsedTemplates.clear();
7682}
7683
Guy Benyei11169dd2012-12-18 14:30:41 +00007684void ASTReader::LoadSelector(Selector Sel) {
7685 // It would be complicated to avoid reading the methods anyway. So don't.
7686 ReadMethodPool(Sel);
7687}
7688
7689void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7690 assert(ID && "Non-zero identifier ID required");
7691 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7692 IdentifiersLoaded[ID - 1] = II;
7693 if (DeserializationListener)
7694 DeserializationListener->IdentifierRead(ID, II);
7695}
7696
7697/// \brief Set the globally-visible declarations associated with the given
7698/// identifier.
7699///
7700/// If the AST reader is currently in a state where the given declaration IDs
7701/// cannot safely be resolved, they are queued until it is safe to resolve
7702/// them.
7703///
7704/// \param II an IdentifierInfo that refers to one or more globally-visible
7705/// declarations.
7706///
7707/// \param DeclIDs the set of declaration IDs with the name @p II that are
7708/// visible at global scope.
7709///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007710/// \param Decls if non-null, this vector will be populated with the set of
7711/// deserialized declarations. These declarations will not be pushed into
7712/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007713void
7714ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7715 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007716 SmallVectorImpl<Decl *> *Decls) {
7717 if (NumCurrentElementsDeserializing && !Decls) {
7718 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007719 return;
7720 }
7721
7722 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007723 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 // Queue this declaration so that it will be added to the
7725 // translation unit scope and identifier's declaration chain
7726 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007727 PreloadedDeclIDs.push_back(DeclIDs[I]);
7728 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007730
7731 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7732
7733 // If we're simply supposed to record the declarations, do so now.
7734 if (Decls) {
7735 Decls->push_back(D);
7736 continue;
7737 }
7738
7739 // Introduce this declaration into the translation-unit scope
7740 // and add it to the declaration chain for this identifier, so
7741 // that (unqualified) name lookup will find it.
7742 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 }
7744}
7745
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007746IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007748 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749
7750 if (IdentifiersLoaded.empty()) {
7751 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007752 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 }
7754
7755 ID -= 1;
7756 if (!IdentifiersLoaded[ID]) {
7757 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7758 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7759 ModuleFile *M = I->second;
7760 unsigned Index = ID - M->BaseIdentifierID;
7761 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7762
7763 // All of the strings in the AST file are preceded by a 16-bit length.
7764 // Extract that 16-bit length to avoid having to execute strlen().
7765 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7766 // unsigned integers. This is important to avoid integer overflow when
7767 // we cast them to 'unsigned'.
7768 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7769 unsigned StrLen = (((unsigned) StrLenPtr[0])
7770 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007771 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7772 IdentifiersLoaded[ID] = &II;
7773 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007775 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 }
7777
7778 return IdentifiersLoaded[ID];
7779}
7780
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007781IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7782 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007783}
7784
7785IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7786 if (LocalID < NUM_PREDEF_IDENT_IDS)
7787 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007788
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7790 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007791 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007792 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007793
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 return LocalID + I->second;
7795}
7796
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007797MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007799 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007800
7801 if (MacrosLoaded.empty()) {
7802 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007803 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 }
7805
7806 ID -= NUM_PREDEF_MACRO_IDS;
7807 if (!MacrosLoaded[ID]) {
7808 GlobalMacroMapType::iterator I
7809 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7810 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7811 ModuleFile *M = I->second;
7812 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007813 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007814
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007815 if (DeserializationListener)
7816 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7817 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 }
7819
7820 return MacrosLoaded[ID];
7821}
7822
7823MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7824 if (LocalID < NUM_PREDEF_MACRO_IDS)
7825 return LocalID;
7826
7827 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7828 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7829 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7830
7831 return LocalID + I->second;
7832}
7833
7834serialization::SubmoduleID
7835ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7836 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7837 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007838
Guy Benyei11169dd2012-12-18 14:30:41 +00007839 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7840 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007841 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007842 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007843
Guy Benyei11169dd2012-12-18 14:30:41 +00007844 return LocalID + I->second;
7845}
7846
7847Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7848 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7849 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007850 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007852
Guy Benyei11169dd2012-12-18 14:30:41 +00007853 if (GlobalID > SubmodulesLoaded.size()) {
7854 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007855 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007857
Guy Benyei11169dd2012-12-18 14:30:41 +00007858 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7859}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007860
7861Module *ASTReader::getModule(unsigned ID) {
7862 return getSubmodule(ID);
7863}
7864
Richard Smithd88a7f12015-09-01 20:35:42 +00007865ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7866 if (ID & 1) {
7867 // It's a module, look it up by submodule ID.
7868 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7869 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7870 } else {
7871 // It's a prefix (preamble, PCH, ...). Look it up by index.
7872 unsigned IndexFromEnd = ID >> 1;
7873 assert(IndexFromEnd && "got reference to unknown module file");
7874 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7875 }
7876}
7877
7878unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7879 if (!F)
7880 return 1;
7881
7882 // For a file representing a module, use the submodule ID of the top-level
7883 // module as the file ID. For any other kind of file, the number of such
7884 // files loaded beforehand will be the same on reload.
7885 // FIXME: Is this true even if we have an explicit module file and a PCH?
7886 if (F->isModule())
7887 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7888
7889 auto PCHModules = getModuleManager().pch_modules();
7890 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7891 assert(I != PCHModules.end() && "emitting reference to unknown file");
7892 return (I - PCHModules.end()) << 1;
7893}
7894
Adrian Prantl15bcf702015-06-30 17:39:43 +00007895llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7896ASTReader::getSourceDescriptor(unsigned ID) {
7897 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007898 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007899
7900 // If there is only a single PCH, return it instead.
7901 // Chained PCH are not suported.
7902 if (ModuleMgr.size() == 1) {
7903 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007904 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007905 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7906 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7907 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007908 }
7909 return None;
7910}
7911
David Blaikie9ffe5a32017-01-30 05:00:26 +00007912ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7913 const Module *M = getSubmodule(ID);
7914 if (!M || !M->WithCodegen)
7915 return EK_ReplyHazy;
7916
7917 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7918 assert(MF); // ?
7919 if (MF->Kind == ModuleKind::MK_MainFile)
7920 return EK_Never;
7921 return EK_Always;
7922}
7923
Guy Benyei11169dd2012-12-18 14:30:41 +00007924Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7925 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7926}
7927
7928Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7929 if (ID == 0)
7930 return Selector();
7931
7932 if (ID > SelectorsLoaded.size()) {
7933 Error("selector ID out of range in AST file");
7934 return Selector();
7935 }
7936
Craig Toppera13603a2014-05-22 05:54:18 +00007937 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 // Load this selector from the selector table.
7939 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7940 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7941 ModuleFile &M = *I->second;
7942 ASTSelectorLookupTrait Trait(*this, M);
7943 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7944 SelectorsLoaded[ID - 1] =
7945 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7946 if (DeserializationListener)
7947 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7948 }
7949
7950 return SelectorsLoaded[ID - 1];
7951}
7952
7953Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7954 return DecodeSelector(ID);
7955}
7956
7957uint32_t ASTReader::GetNumExternalSelectors() {
7958 // ID 0 (the null selector) is considered an external selector.
7959 return getTotalNumSelectors() + 1;
7960}
7961
7962serialization::SelectorID
7963ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7964 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7965 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007966
Guy Benyei11169dd2012-12-18 14:30:41 +00007967 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7968 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007969 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007970 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007971
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 return LocalID + I->second;
7973}
7974
7975DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007976ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 const RecordData &Record, unsigned &Idx) {
7978 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7979 switch (Kind) {
7980 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007981 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007982
7983 case DeclarationName::ObjCZeroArgSelector:
7984 case DeclarationName::ObjCOneArgSelector:
7985 case DeclarationName::ObjCMultiArgSelector:
7986 return DeclarationName(ReadSelector(F, Record, Idx));
7987
7988 case DeclarationName::CXXConstructorName:
7989 return Context.DeclarationNames.getCXXConstructorName(
7990 Context.getCanonicalType(readType(F, Record, Idx)));
7991
7992 case DeclarationName::CXXDestructorName:
7993 return Context.DeclarationNames.getCXXDestructorName(
7994 Context.getCanonicalType(readType(F, Record, Idx)));
7995
7996 case DeclarationName::CXXConversionFunctionName:
7997 return Context.DeclarationNames.getCXXConversionFunctionName(
7998 Context.getCanonicalType(readType(F, Record, Idx)));
7999
8000 case DeclarationName::CXXOperatorName:
8001 return Context.DeclarationNames.getCXXOperatorName(
8002 (OverloadedOperatorKind)Record[Idx++]);
8003
8004 case DeclarationName::CXXLiteralOperatorName:
8005 return Context.DeclarationNames.getCXXLiteralOperatorName(
8006 GetIdentifierInfo(F, Record, Idx));
8007
8008 case DeclarationName::CXXUsingDirective:
8009 return DeclarationName::getUsingDirectiveName();
8010 }
8011
8012 llvm_unreachable("Invalid NameKind!");
8013}
8014
8015void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8016 DeclarationNameLoc &DNLoc,
8017 DeclarationName Name,
8018 const RecordData &Record, unsigned &Idx) {
8019 switch (Name.getNameKind()) {
8020 case DeclarationName::CXXConstructorName:
8021 case DeclarationName::CXXDestructorName:
8022 case DeclarationName::CXXConversionFunctionName:
8023 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8024 break;
8025
8026 case DeclarationName::CXXOperatorName:
8027 DNLoc.CXXOperatorName.BeginOpNameLoc
8028 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8029 DNLoc.CXXOperatorName.EndOpNameLoc
8030 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8031 break;
8032
8033 case DeclarationName::CXXLiteralOperatorName:
8034 DNLoc.CXXLiteralOperatorName.OpNameLoc
8035 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8036 break;
8037
8038 case DeclarationName::Identifier:
8039 case DeclarationName::ObjCZeroArgSelector:
8040 case DeclarationName::ObjCOneArgSelector:
8041 case DeclarationName::ObjCMultiArgSelector:
8042 case DeclarationName::CXXUsingDirective:
8043 break;
8044 }
8045}
8046
8047void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8048 DeclarationNameInfo &NameInfo,
8049 const RecordData &Record, unsigned &Idx) {
8050 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8051 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8052 DeclarationNameLoc DNLoc;
8053 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8054 NameInfo.setInfo(DNLoc);
8055}
8056
8057void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8058 const RecordData &Record, unsigned &Idx) {
8059 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8060 unsigned NumTPLists = Record[Idx++];
8061 Info.NumTemplParamLists = NumTPLists;
8062 if (NumTPLists) {
8063 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008064 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8066 }
8067}
8068
8069TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008070ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 unsigned &Idx) {
8072 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8073 switch (Kind) {
8074 case TemplateName::Template:
8075 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8076
8077 case TemplateName::OverloadedTemplate: {
8078 unsigned size = Record[Idx++];
8079 UnresolvedSet<8> Decls;
8080 while (size--)
8081 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8082
8083 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8084 }
8085
8086 case TemplateName::QualifiedTemplate: {
8087 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8088 bool hasTemplKeyword = Record[Idx++];
8089 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8090 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8091 }
8092
8093 case TemplateName::DependentTemplate: {
8094 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8095 if (Record[Idx++]) // isIdentifier
8096 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008097 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008098 Idx));
8099 return Context.getDependentTemplateName(NNS,
8100 (OverloadedOperatorKind)Record[Idx++]);
8101 }
8102
8103 case TemplateName::SubstTemplateTemplateParm: {
8104 TemplateTemplateParmDecl *param
8105 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8106 if (!param) return TemplateName();
8107 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8108 return Context.getSubstTemplateTemplateParm(param, replacement);
8109 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008110
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008112 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8114 if (!Param)
8115 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008116
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8118 if (ArgPack.getKind() != TemplateArgument::Pack)
8119 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8122 }
8123 }
8124
8125 llvm_unreachable("Unhandled template name kind!");
8126}
8127
Richard Smith2bb3c342015-08-09 01:05:31 +00008128TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8129 const RecordData &Record,
8130 unsigned &Idx,
8131 bool Canonicalize) {
8132 if (Canonicalize) {
8133 // The caller wants a canonical template argument. Sometimes the AST only
8134 // wants template arguments in canonical form (particularly as the template
8135 // argument lists of template specializations) so ensure we preserve that
8136 // canonical form across serialization.
8137 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8138 return Context.getCanonicalTemplateArgument(Arg);
8139 }
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8142 switch (Kind) {
8143 case TemplateArgument::Null:
8144 return TemplateArgument();
8145 case TemplateArgument::Type:
8146 return TemplateArgument(readType(F, Record, Idx));
8147 case TemplateArgument::Declaration: {
8148 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008149 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 }
8151 case TemplateArgument::NullPtr:
8152 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8153 case TemplateArgument::Integral: {
8154 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8155 QualType T = readType(F, Record, Idx);
8156 return TemplateArgument(Context, Value, T);
8157 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008158 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8160 case TemplateArgument::TemplateExpansion: {
8161 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008162 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 if (unsigned NumExpansions = Record[Idx++])
8164 NumTemplateExpansions = NumExpansions - 1;
8165 return TemplateArgument(Name, NumTemplateExpansions);
8166 }
8167 case TemplateArgument::Expression:
8168 return TemplateArgument(ReadExpr(F));
8169 case TemplateArgument::Pack: {
8170 unsigned NumArgs = Record[Idx++];
8171 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8172 for (unsigned I = 0; I != NumArgs; ++I)
8173 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008174 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 }
8176 }
8177
8178 llvm_unreachable("Unhandled template argument kind!");
8179}
8180
8181TemplateParameterList *
8182ASTReader::ReadTemplateParameterList(ModuleFile &F,
8183 const RecordData &Record, unsigned &Idx) {
8184 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8185 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8186 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8187
8188 unsigned NumParams = Record[Idx++];
8189 SmallVector<NamedDecl *, 16> Params;
8190 Params.reserve(NumParams);
8191 while (NumParams--)
8192 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8193
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008194 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 TemplateParameterList* TemplateParams =
8196 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008197 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 return TemplateParams;
8199}
8200
8201void
8202ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008203ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008205 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008206 unsigned NumTemplateArgs = Record[Idx++];
8207 TemplArgs.reserve(NumTemplateArgs);
8208 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008209 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008210}
8211
8212/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008213void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 const RecordData &Record, unsigned &Idx) {
8215 unsigned NumDecls = Record[Idx++];
8216 Set.reserve(Context, NumDecls);
8217 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008218 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008220 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 }
8222}
8223
8224CXXBaseSpecifier
8225ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8226 const RecordData &Record, unsigned &Idx) {
8227 bool isVirtual = static_cast<bool>(Record[Idx++]);
8228 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8229 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8230 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8231 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8232 SourceRange Range = ReadSourceRange(F, Record, Idx);
8233 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008234 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 EllipsisLoc);
8236 Result.setInheritConstructors(inheritConstructors);
8237 return Result;
8238}
8239
Richard Smithc2bb8182015-03-24 06:36:48 +00008240CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008241ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8242 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008244 assert(NumInitializers && "wrote ctor initializers but have no inits");
8245 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8246 for (unsigned i = 0; i != NumInitializers; ++i) {
8247 TypeSourceInfo *TInfo = nullptr;
8248 bool IsBaseVirtual = false;
8249 FieldDecl *Member = nullptr;
8250 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251
Richard Smithc2bb8182015-03-24 06:36:48 +00008252 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8253 switch (Type) {
8254 case CTOR_INITIALIZER_BASE:
8255 TInfo = GetTypeSourceInfo(F, Record, Idx);
8256 IsBaseVirtual = Record[Idx++];
8257 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008258
Richard Smithc2bb8182015-03-24 06:36:48 +00008259 case CTOR_INITIALIZER_DELEGATING:
8260 TInfo = GetTypeSourceInfo(F, Record, Idx);
8261 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008262
Richard Smithc2bb8182015-03-24 06:36:48 +00008263 case CTOR_INITIALIZER_MEMBER:
8264 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8265 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008266
Richard Smithc2bb8182015-03-24 06:36:48 +00008267 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8268 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8269 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008271
8272 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8273 Expr *Init = ReadExpr(F);
8274 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8275 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008276
8277 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008278 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008279 BOMInit = new (Context)
8280 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8281 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008282 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008283 BOMInit = new (Context)
8284 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008285 else if (Member)
8286 BOMInit = new (Context)
8287 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8288 Init, RParenLoc);
8289 else
8290 BOMInit = new (Context)
8291 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8292 LParenLoc, Init, RParenLoc);
8293
Richard Smith418ed822016-12-14 19:45:03 +00008294 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008295 unsigned SourceOrder = Record[Idx++];
8296 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008297 }
8298
Richard Smithc2bb8182015-03-24 06:36:48 +00008299 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 }
8301
Richard Smithc2bb8182015-03-24 06:36:48 +00008302 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008303}
8304
8305NestedNameSpecifier *
8306ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8307 const RecordData &Record, unsigned &Idx) {
8308 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008309 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 for (unsigned I = 0; I != N; ++I) {
8311 NestedNameSpecifier::SpecifierKind Kind
8312 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8313 switch (Kind) {
8314 case NestedNameSpecifier::Identifier: {
8315 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8316 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8317 break;
8318 }
8319
8320 case NestedNameSpecifier::Namespace: {
8321 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8322 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8323 break;
8324 }
8325
8326 case NestedNameSpecifier::NamespaceAlias: {
8327 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8328 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8329 break;
8330 }
8331
8332 case NestedNameSpecifier::TypeSpec:
8333 case NestedNameSpecifier::TypeSpecWithTemplate: {
8334 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8335 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008336 return nullptr;
8337
Guy Benyei11169dd2012-12-18 14:30:41 +00008338 bool Template = Record[Idx++];
8339 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8340 break;
8341 }
8342
8343 case NestedNameSpecifier::Global: {
8344 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8345 // No associated value, and there can't be a prefix.
8346 break;
8347 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008348
8349 case NestedNameSpecifier::Super: {
8350 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8351 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8352 break;
8353 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
8355 Prev = NNS;
8356 }
8357 return NNS;
8358}
8359
8360NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008361ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008362 unsigned &Idx) {
8363 unsigned N = Record[Idx++];
8364 NestedNameSpecifierLocBuilder Builder;
8365 for (unsigned I = 0; I != N; ++I) {
8366 NestedNameSpecifier::SpecifierKind Kind
8367 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8368 switch (Kind) {
8369 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008370 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008371 SourceRange Range = ReadSourceRange(F, Record, Idx);
8372 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8373 break;
8374 }
8375
8376 case NestedNameSpecifier::Namespace: {
8377 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8378 SourceRange Range = ReadSourceRange(F, Record, Idx);
8379 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8380 break;
8381 }
8382
8383 case NestedNameSpecifier::NamespaceAlias: {
8384 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8385 SourceRange Range = ReadSourceRange(F, Record, Idx);
8386 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8387 break;
8388 }
8389
8390 case NestedNameSpecifier::TypeSpec:
8391 case NestedNameSpecifier::TypeSpecWithTemplate: {
8392 bool Template = Record[Idx++];
8393 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8394 if (!T)
8395 return NestedNameSpecifierLoc();
8396 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8397
8398 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008399 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8401 T->getTypeLoc(), ColonColonLoc);
8402 break;
8403 }
8404
8405 case NestedNameSpecifier::Global: {
8406 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8407 Builder.MakeGlobal(Context, ColonColonLoc);
8408 break;
8409 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008410
8411 case NestedNameSpecifier::Super: {
8412 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8413 SourceRange Range = ReadSourceRange(F, Record, Idx);
8414 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8415 break;
8416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 }
8418 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008419
Guy Benyei11169dd2012-12-18 14:30:41 +00008420 return Builder.getWithLocInContext(Context);
8421}
8422
8423SourceRange
8424ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8425 unsigned &Idx) {
8426 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8427 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8428 return SourceRange(beg, end);
8429}
8430
8431/// \brief Read an integral value
8432llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8433 unsigned BitWidth = Record[Idx++];
8434 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8435 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8436 Idx += NumWords;
8437 return Result;
8438}
8439
8440/// \brief Read a signed integral value
8441llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8442 bool isUnsigned = Record[Idx++];
8443 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8444}
8445
8446/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008447llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8448 const llvm::fltSemantics &Sem,
8449 unsigned &Idx) {
8450 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008451}
8452
8453// \brief Read a string
8454std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8455 unsigned Len = Record[Idx++];
8456 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8457 Idx += Len;
8458 return Result;
8459}
8460
Richard Smith7ed1bc92014-12-05 22:42:13 +00008461std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8462 unsigned &Idx) {
8463 std::string Filename = ReadString(Record, Idx);
8464 ResolveImportedPath(F, Filename);
8465 return Filename;
8466}
8467
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008468VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 unsigned &Idx) {
8470 unsigned Major = Record[Idx++];
8471 unsigned Minor = Record[Idx++];
8472 unsigned Subminor = Record[Idx++];
8473 if (Minor == 0)
8474 return VersionTuple(Major);
8475 if (Subminor == 0)
8476 return VersionTuple(Major, Minor - 1);
8477 return VersionTuple(Major, Minor - 1, Subminor - 1);
8478}
8479
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008480CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008481 const RecordData &Record,
8482 unsigned &Idx) {
8483 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8484 return CXXTemporary::Create(Context, Decl);
8485}
8486
8487DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008488 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008489}
8490
8491DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8492 return Diags.Report(Loc, DiagID);
8493}
8494
8495/// \brief Retrieve the identifier table associated with the
8496/// preprocessor.
8497IdentifierTable &ASTReader::getIdentifierTable() {
8498 return PP.getIdentifierTable();
8499}
8500
8501/// \brief Record that the given ID maps to the given switch-case
8502/// statement.
8503void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008504 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 "Already have a SwitchCase with this ID");
8506 (*CurrSwitchCaseStmts)[ID] = SC;
8507}
8508
8509/// \brief Retrieve the switch-case statement with the given ID.
8510SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008511 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 return (*CurrSwitchCaseStmts)[ID];
8513}
8514
8515void ASTReader::ClearSwitchCaseIDs() {
8516 CurrSwitchCaseStmts->clear();
8517}
8518
8519void ASTReader::ReadComments() {
8520 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008521 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008522 serialization::ModuleFile *> >::iterator
8523 I = CommentsCursors.begin(),
8524 E = CommentsCursors.end();
8525 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008526 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008527 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008528 serialization::ModuleFile &F = *I->second;
8529 SavedStreamPosition SavedPosition(Cursor);
8530
8531 RecordData Record;
8532 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008533 llvm::BitstreamEntry Entry =
8534 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008535
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008536 switch (Entry.Kind) {
8537 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8538 case llvm::BitstreamEntry::Error:
8539 Error("malformed block record in AST file");
8540 return;
8541 case llvm::BitstreamEntry::EndBlock:
8542 goto NextCursor;
8543 case llvm::BitstreamEntry::Record:
8544 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008545 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008546 }
8547
8548 // Read a record.
8549 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008550 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 case COMMENTS_RAW_COMMENT: {
8552 unsigned Idx = 0;
8553 SourceRange SR = ReadSourceRange(F, Record, Idx);
8554 RawComment::CommentKind Kind =
8555 (RawComment::CommentKind) Record[Idx++];
8556 bool IsTrailingComment = Record[Idx++];
8557 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008558 Comments.push_back(new (Context) RawComment(
8559 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8560 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008561 break;
8562 }
8563 }
8564 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008565 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008566 // De-serialized SourceLocations get negative FileIDs for other modules,
8567 // potentially invalidating the original order. Sort it again.
8568 std::sort(Comments.begin(), Comments.end(),
8569 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008570 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008572}
8573
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008574void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8575 bool IncludeSystem, bool Complain,
8576 llvm::function_ref<void(const serialization::InputFile &IF,
8577 bool isSystem)> Visitor) {
8578 unsigned NumUserInputs = MF.NumUserInputFiles;
8579 unsigned NumInputs = MF.InputFilesLoaded.size();
8580 assert(NumUserInputs <= NumInputs);
8581 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8582 for (unsigned I = 0; I < N; ++I) {
8583 bool IsSystem = I >= NumUserInputs;
8584 InputFile IF = getInputFile(MF, I+1, Complain);
8585 Visitor(IF, IsSystem);
8586 }
8587}
8588
Richard Smithcd45dbc2014-04-19 03:48:30 +00008589std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8590 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008591 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008592 return M->getFullModuleName();
8593
8594 // Otherwise, use the name of the top-level module the decl is within.
8595 if (ModuleFile *M = getOwningModuleFile(D))
8596 return M->ModuleName;
8597
8598 // Not from a module.
8599 return "";
8600}
8601
Guy Benyei11169dd2012-12-18 14:30:41 +00008602void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008603 while (!PendingIdentifierInfos.empty() ||
8604 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008605 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008606 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 // If any identifiers with corresponding top-level declarations have
8608 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008609 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8610 TopLevelDeclsMap;
8611 TopLevelDeclsMap TopLevelDecls;
8612
Guy Benyei11169dd2012-12-18 14:30:41 +00008613 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008614 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008615 SmallVector<uint32_t, 4> DeclIDs =
8616 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008617 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008618
8619 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008620 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008621
Richard Smith851072e2014-05-19 20:59:20 +00008622 // For each decl chain that we wanted to complete while deserializing, mark
8623 // it as "still needs to be completed".
8624 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8625 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8626 }
8627 PendingIncompleteDeclChains.clear();
8628
Guy Benyei11169dd2012-12-18 14:30:41 +00008629 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008630 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008631 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 PendingDeclChains.clear();
8633
Douglas Gregor6168bd22013-02-18 15:53:43 +00008634 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008635 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8636 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008637 IdentifierInfo *II = TLD->first;
8638 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008639 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008640 }
8641 }
8642
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 // Load any pending macro definitions.
8644 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008645 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8646 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8647 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8648 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008649 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008650 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008651 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008652 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008653 resolvePendingMacro(II, Info);
8654 }
8655 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008656 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008657 ++IDIdx) {
8658 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008659 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008660 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008661 }
8662 }
8663 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008664
8665 // Wire up the DeclContexts for Decls that we delayed setting until
8666 // recursive loading is completed.
8667 while (!PendingDeclContextInfos.empty()) {
8668 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8669 PendingDeclContextInfos.pop_front();
8670 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8671 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8672 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8673 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008674
Richard Smithd1c46742014-04-30 02:24:17 +00008675 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008676 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008677 auto Update = PendingUpdateRecords.pop_back_val();
8678 ReadingKindTracker ReadingKind(Read_Decl, *this);
8679 loadDeclUpdateRecords(Update.first, Update.second);
8680 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 }
Richard Smith8a639892015-01-24 01:07:20 +00008682
8683 // At this point, all update records for loaded decls are in place, so any
8684 // fake class definitions should have become real.
8685 assert(PendingFakeDefinitionData.empty() &&
8686 "faked up a class definition but never saw the real one");
8687
Guy Benyei11169dd2012-12-18 14:30:41 +00008688 // If we deserialized any C++ or Objective-C class definitions, any
8689 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008690 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008691 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008692 for (Decl *D : PendingDefinitions) {
8693 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008694 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008695 // Make sure that the TagType points at the definition.
8696 const_cast<TagType*>(TagT)->decl = TD;
8697 }
Richard Smith8ce51082015-03-11 01:44:51 +00008698
Craig Topperc6914d02014-08-25 04:15:02 +00008699 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008700 for (auto *R = getMostRecentExistingDecl(RD); R;
8701 R = R->getPreviousDecl()) {
8702 assert((R == D) ==
8703 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008704 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008705 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008707 }
8708
8709 continue;
8710 }
Richard Smith8ce51082015-03-11 01:44:51 +00008711
Craig Topperc6914d02014-08-25 04:15:02 +00008712 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 // Make sure that the ObjCInterfaceType points at the definition.
8714 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8715 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008716
8717 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8718 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8719
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 continue;
8721 }
Richard Smith8ce51082015-03-11 01:44:51 +00008722
Craig Topperc6914d02014-08-25 04:15:02 +00008723 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008724 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8725 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8726
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 continue;
8728 }
Richard Smith8ce51082015-03-11 01:44:51 +00008729
Craig Topperc6914d02014-08-25 04:15:02 +00008730 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008731 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8732 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008733 }
8734 PendingDefinitions.clear();
8735
8736 // Load the bodies of any functions or methods we've encountered. We do
8737 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008738 // have been fully wired up (hasBody relies on this).
8739 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8741 PBEnd = PendingBodies.end();
8742 PB != PBEnd; ++PB) {
8743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8744 // FIXME: Check for =delete/=default?
8745 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008746 const FunctionDecl *Defn = nullptr;
8747 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008748 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008749 else
Richard Smith6561f922016-09-12 21:06:40 +00008750 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008751 continue;
8752 }
8753
8754 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8755 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8756 MD->setLazyBody(PB->second);
8757 }
8758 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008759
8760 // Do some cleanup.
8761 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8762 getContext().deduplicateMergedDefinitonsFor(ND);
8763 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008764}
8765
8766void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008767 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8768 return;
8769
Richard Smitha0ce9c42014-07-29 23:23:27 +00008770 // Trigger the import of the full definition of each class that had any
8771 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008772 // These updates may in turn find and diagnose some ODR failures, so take
8773 // ownership of the set first.
8774 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8775 PendingOdrMergeFailures.clear();
8776 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008777 Merge.first->buildLookup();
8778 Merge.first->decls_begin();
8779 Merge.first->bases_begin();
8780 Merge.first->vbases_begin();
8781 for (auto *RD : Merge.second) {
8782 RD->decls_begin();
8783 RD->bases_begin();
8784 RD->vbases_begin();
8785 }
8786 }
8787
8788 // For each declaration from a merged context, check that the canonical
8789 // definition of that context also contains a declaration of the same
8790 // entity.
8791 //
8792 // Caution: this loop does things that might invalidate iterators into
8793 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8794 while (!PendingOdrMergeChecks.empty()) {
8795 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8796
8797 // FIXME: Skip over implicit declarations for now. This matters for things
8798 // like implicitly-declared special member functions. This isn't entirely
8799 // correct; we can end up with multiple unmerged declarations of the same
8800 // implicit entity.
8801 if (D->isImplicit())
8802 continue;
8803
8804 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008805
8806 bool Found = false;
8807 const Decl *DCanon = D->getCanonicalDecl();
8808
Richard Smith01bdb7a2014-08-28 05:44:07 +00008809 for (auto RI : D->redecls()) {
8810 if (RI->getLexicalDeclContext() == CanonDef) {
8811 Found = true;
8812 break;
8813 }
8814 }
8815 if (Found)
8816 continue;
8817
Richard Smith0f4e2c42015-08-06 04:23:48 +00008818 // Quick check failed, time to do the slow thing. Note, we can't just
8819 // look up the name of D in CanonDef here, because the member that is
8820 // in CanonDef might not be found by name lookup (it might have been
8821 // replaced by a more recent declaration in the lookup table), and we
8822 // can't necessarily find it in the redeclaration chain because it might
8823 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008824 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008825 for (auto *CanonMember : CanonDef->decls()) {
8826 if (CanonMember->getCanonicalDecl() == DCanon) {
8827 // This can happen if the declaration is merely mergeable and not
8828 // actually redeclarable (we looked for redeclarations earlier).
8829 //
8830 // FIXME: We should be able to detect this more efficiently, without
8831 // pulling in all of the members of CanonDef.
8832 Found = true;
8833 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008834 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008835 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8836 if (ND->getDeclName() == D->getDeclName())
8837 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008838 }
8839
8840 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008841 // The AST doesn't like TagDecls becoming invalid after they've been
8842 // completed. We only really need to mark FieldDecls as invalid here.
8843 if (!isa<TagDecl>(D))
8844 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008845
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008846 // Ensure we don't accidentally recursively enter deserialization while
8847 // we're producing our diagnostic.
8848 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008849
8850 std::string CanonDefModule =
8851 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8852 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8853 << D << getOwningModuleNameForDiagnostic(D)
8854 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8855
8856 if (Candidates.empty())
8857 Diag(cast<Decl>(CanonDef)->getLocation(),
8858 diag::note_module_odr_violation_no_possible_decls) << D;
8859 else {
8860 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8861 Diag(Candidates[I]->getLocation(),
8862 diag::note_module_odr_violation_possible_decl)
8863 << Candidates[I];
8864 }
8865
8866 DiagnosedOdrMergeFailures.insert(CanonDef);
8867 }
8868 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008869
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008870 if (OdrMergeFailures.empty())
8871 return;
8872
8873 // Ensure we don't accidentally recursively enter deserialization while
8874 // we're producing our diagnostics.
8875 Deserializing RecursionGuard(this);
8876
Richard Smithcd45dbc2014-04-19 03:48:30 +00008877 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008878 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008879 // If we've already pointed out a specific problem with this class, don't
8880 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008881 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008882 continue;
8883
8884 bool Diagnosed = false;
8885 for (auto *RD : Merge.second) {
8886 // Multiple different declarations got merged together; tell the user
8887 // where they came from.
Richard Trieufa3d93a2017-01-31 01:44:15 +00008888 if (Merge.first == RD)
8889 continue;
8890
8891 llvm::SmallVector<std::pair<Decl *, unsigned>, 4> FirstHashes;
8892 llvm::SmallVector<std::pair<Decl *, unsigned>, 4> SecondHashes;
8893 ODRHash Hash;
8894 for (auto D : Merge.first->decls()) {
8895 if (D->isImplicit())
8896 continue;
8897 Hash.clear();
8898 Hash.AddDecl(D);
8899 FirstHashes.emplace_back(D, Hash.CalculateHash());
8900 }
8901 for (auto D : RD->decls()) {
8902 if (D->isImplicit())
8903 continue;
8904 Hash.clear();
8905 Hash.AddDecl(D);
8906 SecondHashes.emplace_back(D, Hash.CalculateHash());
8907 }
8908
8909 // Used with err_module_odr_violation_mismatch_decl and
8910 // note_module_odr_violation_mismatch_decl
8911 enum {
8912 EndOfClass,
8913 PublicSpecifer,
8914 PrivateSpecifer,
8915 ProtectedSpecifer,
8916 Friend,
8917 Enum,
8918 StaticAssert,
8919 Typedef,
8920 TypeAlias,
8921 CXXMethod,
8922 CXXConstructor,
8923 CXXDestructor,
8924 CXXConversion,
8925 Field,
8926 Other
8927 } FirstDiffType = Other,
8928 SecondDiffType = Other;
8929
8930 auto DifferenceSelector = [](Decl *D) {
8931 assert(D && "valid Decl required");
8932 switch (D->getKind()) {
8933 default:
8934 return Other;
8935 case Decl::AccessSpec:
8936 switch (D->getAccess()) {
8937 case AS_public:
8938 return PublicSpecifer;
8939 case AS_private:
8940 return PrivateSpecifer;
8941 case AS_protected:
8942 return ProtectedSpecifer;
8943 case AS_none:
8944 llvm_unreachable("Invalid access specifier");
8945 }
8946 case Decl::Friend:
8947 return Friend;
8948 case Decl::Enum:
8949 return Enum;
8950 case Decl::StaticAssert:
8951 return StaticAssert;
8952 case Decl::Typedef:
8953 return Typedef;
8954 case Decl::TypeAlias:
8955 return TypeAlias;
8956 case Decl::CXXMethod:
8957 return CXXMethod;
8958 case Decl::CXXConstructor:
8959 return CXXConstructor;
8960 case Decl::CXXDestructor:
8961 return CXXDestructor;
8962 case Decl::CXXConversion:
8963 return CXXConversion;
8964 case Decl::Field:
8965 return Field;
Richard Smithcd45dbc2014-04-19 03:48:30 +00008966 }
Richard Trieufa3d93a2017-01-31 01:44:15 +00008967 };
8968 Decl *FirstDecl = nullptr;
8969 Decl *SecondDecl = nullptr;
8970 auto FirstIt = FirstHashes.begin();
8971 auto SecondIt = SecondHashes.begin();
8972
8973 // If there is a diagnoseable difference, FirstDiffType and
8974 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
8975 // filled in if not EndOfClass.
8976 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
8977 if (FirstIt->second == SecondIt->second) {
8978 ++FirstIt;
8979 ++SecondIt;
8980 continue;
8981 }
8982
8983 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
8984 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
8985
8986 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
8987 SecondDiffType =
8988 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
8989
8990 break;
8991 }
8992
8993 if (FirstDiffType == Other || SecondDiffType == Other) {
8994 // Reaching this point means an unexpected Decl was encountered
8995 // or no difference was detected. This causes a generic error
8996 // message to be emitted.
8997 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8998 Diag(Merge.first->getLocation(),
8999 diag::err_module_odr_violation_different_definitions)
9000 << Merge.first << Module.empty() << Module;
9001
9002
Richard Smithcd45dbc2014-04-19 03:48:30 +00009003
9004 Diag(RD->getLocation(),
9005 diag::note_module_odr_violation_different_definitions)
Richard Trieufa3d93a2017-01-31 01:44:15 +00009006 << getOwningModuleNameForDiagnostic(RD);
9007 Diagnosed = true;
9008 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009009 }
Richard Trieufa3d93a2017-01-31 01:44:15 +00009010
9011 std::string FirstModule = getOwningModuleNameForDiagnostic(Merge.first);
9012 std::string SecondModule = getOwningModuleNameForDiagnostic(RD);
9013
9014 if (FirstDiffType != SecondDiffType) {
9015 SourceLocation FirstLoc;
9016 SourceRange FirstRange;
9017 if (FirstDiffType == EndOfClass) {
9018 FirstLoc = Merge.first->getBraceRange().getEnd();
9019 } else {
9020 FirstLoc = FirstIt->first->getLocation();
9021 FirstRange = FirstIt->first->getSourceRange();
9022 }
9023 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9024 << Merge.first << FirstModule.empty() << FirstModule << FirstRange
9025 << FirstDiffType;
9026
9027 SourceLocation SecondLoc;
9028 SourceRange SecondRange;
9029 if (SecondDiffType == EndOfClass) {
9030 SecondLoc = RD->getBraceRange().getEnd();
9031 } else {
9032 SecondLoc = SecondDecl->getLocation();
9033 SecondRange = SecondDecl->getSourceRange();
9034 }
9035 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9036 << SecondModule << SecondRange << SecondDiffType;
9037 Diagnosed = true;
9038 break;
9039 }
9040
9041 // Used with err_module_odr_violation_mismatch_decl_diff and
9042 // note_module_odr_violation_mismatch_decl_diff
9043 enum ODRDeclDifference{
9044 FriendName,
9045 EnumName,
9046 EnumConstantName,
9047 EnumConstantInit,
9048 EnumConstantNoInit,
9049 EnumConstantDiffInit,
9050 EnumNumberOfConstants,
9051 StaticAssertCondition,
9052 StaticAssertMessage,
9053 StaticAssertOnlyMessage,
9054 TypedefName,
9055 MethodName,
9056 MethodStatic,
9057 MethodInline,
9058 MethodConst,
9059 MethodNumParams,
9060 MethodParamName,
9061 MethodParamType,
9062 MethodDefaultArg,
9063 MethodOnlyDefaultArg,
9064 MethodOnlyBody,
9065 MethodBody,
9066 FieldName,
9067 FieldSingleBitField,
9068 FieldMutable,
9069 };
9070
9071 // These lambdas have the common portions of the ODR diagnostics. This
9072 // has the same return as Diag(), so addition parameters can be passed
9073 // in with operator<<
9074 auto ODRDiagError = [&Merge, &FirstModule, this](
9075 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9076 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9077 << Merge.first << FirstModule.empty() << FirstModule << Range
9078 << DiffType;
9079 };
9080 auto ODRDiagNote = [&SecondModule, this](
9081 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9082 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9083 << SecondModule << Range << DiffType;
9084 };
9085
9086 auto ComputeODRHash = [&Hash](const Stmt* S) {
9087 assert(S);
9088 Hash.clear();
9089 Hash.AddStmt(S);
9090 return Hash.CalculateHash();
9091 };
9092
9093 // At this point, both decls are of the same type. Dive down deeper into
9094 // the Decl to determine where the first difference is located.
9095 switch (FirstDiffType) {
9096 case Friend: {
9097 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
9098 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
9099 {
9100 auto D = ODRDiagError(FirstFriend->getFriendLoc(),
9101 FirstFriend->getSourceRange(), FriendName);
9102 if (TypeSourceInfo *FirstTSI = FirstFriend->getFriendType())
9103 D << FirstTSI->getType();
9104 else
9105 D << FirstFriend->getFriendDecl();
9106 }
9107 {
9108 auto D = ODRDiagNote(SecondFriend->getFriendLoc(),
9109 SecondFriend->getSourceRange(), FriendName);
9110 if (TypeSourceInfo *SecondTSI = SecondFriend->getFriendType())
9111 D << SecondTSI->getType();
9112 else
9113 D << SecondFriend->getFriendDecl();
9114 }
9115 Diagnosed = true;
9116 break;
9117 }
9118 case Enum: {
9119 EnumDecl *FirstEnum = cast<EnumDecl>(FirstDecl);
9120 EnumDecl *SecondEnum = cast<EnumDecl>(SecondDecl);
9121 if (FirstEnum->getName() != SecondEnum->getName()) {
9122 ODRDiagError(FirstEnum->getLocStart(), FirstEnum->getSourceRange(),
9123 EnumName)
9124 << FirstEnum;
9125 ODRDiagNote(SecondEnum->getLocStart(), SecondEnum->getSourceRange(),
9126 EnumName)
9127 << SecondEnum;
9128 Diagnosed = true;
9129 break;
9130 }
9131
9132 // Don't use EnumDecl::enumerator_{begin,end}. Decl merging can
9133 // cause the iterators from them to be the same for both Decl's.
9134 EnumDecl::enumerator_iterator FirstEnumIt(FirstEnum->decls_begin());
9135 EnumDecl::enumerator_iterator FirstEnumEnd(FirstEnum->decls_end());
9136 EnumDecl::enumerator_iterator SecondEnumIt(SecondEnum->decls_begin());
9137 EnumDecl::enumerator_iterator SecondEnumEnd(SecondEnum->decls_end());
9138 int NumElements = 0;
9139 for (; FirstEnumIt != FirstEnumEnd && SecondEnumIt != SecondEnumEnd;
9140 ++FirstEnumIt, ++SecondEnumIt, ++NumElements) {
9141 if (FirstEnumIt->getName() != SecondEnumIt->getName()) {
9142 ODRDiagError(FirstEnumIt->getLocStart(),
9143 FirstEnumIt->getSourceRange(), EnumConstantName)
9144 << *FirstEnumIt << FirstEnum;
9145 ODRDiagNote(SecondEnumIt->getLocStart(),
9146 SecondEnumIt->getSourceRange(), EnumConstantName)
9147 << *SecondEnumIt << SecondEnum;
9148 Diagnosed = true;
9149 break;
9150 }
9151 Expr *FirstInit = FirstEnumIt->getInitExpr();
9152 Expr *SecondInit = SecondEnumIt->getInitExpr();
9153
9154 if (FirstInit && !SecondInit) {
9155 ODRDiagError(FirstEnumIt->getLocStart(),
9156 FirstEnumIt->getSourceRange(), EnumConstantInit)
9157 << *FirstEnumIt << FirstEnum;
9158
9159 ODRDiagNote(SecondEnumIt->getLocStart(),
9160 SecondEnumIt->getSourceRange(), EnumConstantNoInit)
9161 << *SecondEnumIt << SecondEnum;
9162 Diagnosed = true;
9163 break;
9164 }
9165
9166 if (!FirstInit && SecondInit) {
9167 ODRDiagError(FirstEnumIt->getLocStart(),
9168 FirstEnumIt->getSourceRange(), EnumConstantNoInit)
9169 << *FirstEnumIt << FirstEnum;
9170 ODRDiagNote(SecondEnumIt->getLocStart(),
9171 SecondEnumIt->getSourceRange(), EnumConstantInit)
9172 << *SecondEnumIt << SecondEnum;
9173 Diagnosed = true;
9174 break;
9175 }
9176
9177 if (FirstInit == SecondInit)
9178 continue;
9179
9180 unsigned FirstODRHash = ComputeODRHash(FirstInit);
9181 unsigned SecondODRHash = ComputeODRHash(SecondInit);
9182
9183 if (FirstODRHash != SecondODRHash) {
9184 ODRDiagError(FirstEnumIt->getLocStart(),
9185 FirstEnumIt->getSourceRange(), EnumConstantDiffInit)
9186 << *FirstEnumIt << FirstEnum;
9187 ODRDiagNote(SecondEnumIt->getLocStart(),
9188 SecondEnumIt->getSourceRange(), EnumConstantDiffInit)
9189 << *SecondEnumIt << SecondEnum;
9190 Diagnosed = true;
9191 break;
9192 }
9193 }
9194
9195 if (FirstEnumIt == FirstEnumEnd && SecondEnumIt != SecondEnumEnd) {
9196 unsigned FirstEnumSize = NumElements;
9197 unsigned SecondEnumSize = NumElements;
9198 for (; SecondEnumIt != SecondEnumEnd; ++SecondEnumIt)
9199 ++SecondEnumSize;
9200 ODRDiagError(FirstEnum->getLocStart(), FirstEnum->getSourceRange(),
9201 EnumNumberOfConstants)
9202 << FirstEnum << FirstEnumSize;
9203 ODRDiagNote(SecondEnum->getLocStart(), SecondEnum->getSourceRange(),
9204 EnumNumberOfConstants)
9205 << SecondEnum << SecondEnumSize;
9206 Diagnosed = true;
9207 break;
9208 }
9209
9210 if (FirstEnumIt != FirstEnumEnd && SecondEnumIt == SecondEnumEnd) {
9211 unsigned FirstEnumSize = NumElements;
9212 unsigned SecondEnumSize = NumElements;
9213 for (; FirstEnumIt != FirstEnumEnd; ++FirstEnumIt)
9214 ++FirstEnumSize;
9215 ODRDiagError(FirstEnum->getLocStart(), FirstEnum->getSourceRange(),
9216 EnumNumberOfConstants)
9217 << FirstEnum << FirstEnumSize;
9218 ODRDiagNote(SecondEnum->getLocStart(), SecondEnum->getSourceRange(),
9219 EnumNumberOfConstants)
9220 << SecondEnum << SecondEnumSize;
9221 Diagnosed = true;
9222 break;
9223 }
9224
9225 break;
9226 }
9227 case StaticAssert: {
9228 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9229 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9230
9231 Expr *FirstExpr = FirstSA->getAssertExpr();
9232 Expr *SecondExpr = SecondSA->getAssertExpr();
9233 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9234 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9235 if (FirstODRHash != SecondODRHash) {
9236 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9237 StaticAssertCondition);
9238 ODRDiagNote(SecondExpr->getLocStart(),
9239 SecondExpr->getSourceRange(), StaticAssertCondition);
9240 Diagnosed = true;
9241 break;
9242 }
9243
9244 StringLiteral *FirstStr = FirstSA->getMessage();
9245 StringLiteral *SecondStr = SecondSA->getMessage();
9246 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9247 SourceLocation FirstLoc, SecondLoc;
9248 SourceRange FirstRange, SecondRange;
9249 if (FirstStr) {
9250 FirstLoc = FirstStr->getLocStart();
9251 FirstRange = FirstStr->getSourceRange();
9252 } else {
9253 FirstLoc = FirstSA->getLocStart();
9254 FirstRange = FirstSA->getSourceRange();
9255 }
9256 if (SecondStr) {
9257 SecondLoc = SecondStr->getLocStart();
9258 SecondRange = SecondStr->getSourceRange();
9259 } else {
9260 SecondLoc = SecondSA->getLocStart();
9261 SecondRange = SecondSA->getSourceRange();
9262 }
9263 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9264 << (FirstStr == nullptr);
9265 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9266 << (SecondStr == nullptr);
9267 Diagnosed = true;
9268 break;
9269 }
9270
9271 if (FirstStr && SecondStr &&
9272 FirstStr->getString() != SecondStr->getString()) {
9273 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9274 StaticAssertMessage);
9275 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9276 StaticAssertMessage);
9277 Diagnosed = true;
9278 break;
9279 }
9280 break;
9281 }
9282 case Typedef:
9283 case TypeAlias: {
9284 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
9285 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
9286 IdentifierInfo *FirstII = FirstTD->getIdentifier();
9287 IdentifierInfo *SecondII = SecondTD->getIdentifier();
9288 if (FirstII && SecondII && FirstII->getName() != SecondII->getName()) {
9289 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
9290 TypedefName)
9291 << (FirstDiffType == TypeAlias) << FirstII;
9292 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
9293 TypedefName)
9294 << (FirstDiffType == TypeAlias) << SecondII;
9295 Diagnosed = true;
9296 break;
9297 }
9298 break;
9299 }
9300 case CXXMethod:
9301 case CXXConstructor:
9302 case CXXConversion:
9303 case CXXDestructor: {
9304 // TODO: Merge with existing method diff logic.
9305 CXXMethodDecl *FirstMD = cast<CXXMethodDecl>(FirstDecl);
9306 CXXMethodDecl *SecondMD = cast<CXXMethodDecl>(SecondDecl);
9307 IdentifierInfo *FirstII = FirstMD->getIdentifier();
9308 IdentifierInfo *SecondII = SecondMD->getIdentifier();
9309 if (FirstII && SecondII && FirstII->getName() != SecondII->getName()) {
9310 ODRDiagError(FirstMD->getLocation(), FirstMD->getSourceRange(),
9311 MethodName)
9312 << FirstII;
9313 ODRDiagNote(SecondMD->getLocation(), SecondMD->getSourceRange(),
9314 MethodName)
9315 << SecondII;
9316 Diagnosed = true;
9317 break;
9318 }
9319
9320 bool FirstStatic = FirstMD->getStorageClass() == SC_Static;
9321 bool SecondStatic = SecondMD->getStorageClass() == SC_Static;
9322 if (FirstStatic != SecondStatic) {
9323 ODRDiagError(FirstMD->getLocation(), FirstMD->getSourceRange(),
9324 MethodStatic)
9325 << FirstMD << FirstStatic;
9326 ODRDiagNote(SecondMD->getLocation(), SecondMD->getSourceRange(),
9327 MethodStatic)
9328 << SecondMD << SecondStatic;
9329 Diagnosed = true;
9330 break;
9331 }
9332
9333 bool FirstInline = FirstMD->isInlineSpecified();
9334 bool SecondInline = SecondMD->isInlineSpecified();
9335 if (FirstInline != SecondInline) {
9336 ODRDiagError(FirstMD->getLocation(), FirstMD->getSourceRange(),
9337 MethodInline)
9338 << FirstMD << FirstInline;
9339 ODRDiagNote(SecondMD->getLocation(), SecondMD->getSourceRange(),
9340 MethodInline)
9341 << SecondMD << SecondInline;
9342 Diagnosed = true;
9343 break;
9344 }
9345
9346 bool FirstConst = FirstMD->isConst();
9347 bool SecondConst = SecondMD->isConst();
9348 if (FirstConst != SecondConst) {
9349 ODRDiagError(FirstMD->getLocation(), FirstMD->getSourceRange(),
9350 MethodConst)
9351 << FirstMD << FirstInline;
9352 ODRDiagNote(SecondMD->getLocation(), SecondMD->getSourceRange(),
9353 MethodConst)
9354 << SecondMD << SecondInline;
9355 Diagnosed = true;
9356 break;
9357 }
9358
9359 if (FirstMD->getNumParams() != SecondMD->getNumParams()) {
9360 ODRDiagError(FirstMD->getLocation(), FirstMD->getSourceRange(),
9361 MethodNumParams)
9362 << SecondMD << FirstMD->getNumParams();
9363 ODRDiagNote(SecondMD->getLocation(), SecondMD->getSourceRange(),
9364 MethodNumParams)
9365 << SecondMD << SecondMD->getNumParams();
9366 Diagnosed = true;
9367 break;
9368 }
9369
9370 for (unsigned i = 0, e = FirstMD->getNumParams(); i < e; ++i) {
9371 ParmVarDecl *FirstParam = FirstMD->getParamDecl(i);
9372 ParmVarDecl *SecondParam = SecondMD->getParamDecl(i);
9373 IdentifierInfo *FirstII = FirstParam->getIdentifier();
9374 IdentifierInfo *SecondII = SecondParam->getIdentifier();
9375 if ((!FirstII && SecondII) || (FirstII && !SecondII) ||
9376 (FirstII && SecondII &&
9377 FirstII->getName() != SecondII->getName())) {
9378 ODRDiagError(FirstParam->getLocation(),
9379 FirstParam->getSourceRange(), MethodParamName)
9380 << SecondMD << i + 1 << (FirstII == nullptr) << FirstII;
9381 ODRDiagNote(SecondParam->getLocation(),
9382 SecondParam->getSourceRange(), MethodParamName)
9383 << SecondMD << i + 1 << (SecondII == nullptr) << SecondII;
9384 Diagnosed = true;
9385 break;
9386 }
9387
9388 if (FirstParam->getType() != SecondParam->getType()) {
9389 ODRDiagError(FirstParam->getLocation(),
9390 FirstParam->getSourceRange(), MethodParamType)
9391 << SecondMD << i + 1 << FirstParam->getType();
9392 ODRDiagNote(SecondParam->getLocation(),
9393 SecondParam->getSourceRange(), MethodParamType)
9394 << SecondMD << i + 1 << SecondParam->getType();
9395 Diagnosed = true;
9396 break;
9397 }
9398
9399 Expr *FirstDefaultArg = FirstParam->getDefaultArg();
9400 Expr *SecondDefaultArg = SecondParam->getDefaultArg();
9401 if ((!FirstDefaultArg && SecondDefaultArg) ||
9402 (FirstDefaultArg && !SecondDefaultArg)) {
9403 ODRDiagError(FirstParam->getLocation(),
9404 FirstParam->getSourceRange(), MethodOnlyDefaultArg)
9405 << SecondMD << i + 1 << (FirstDefaultArg != nullptr);
9406 ODRDiagNote(SecondParam->getLocation(),
9407 SecondParam->getSourceRange(), MethodOnlyDefaultArg)
9408 << SecondMD << i + 1 << (SecondDefaultArg != nullptr);
9409 Diagnosed = true;
9410 break;
9411 }
9412
9413 if (FirstDefaultArg && SecondDefaultArg) {
9414 unsigned FirstODRHash = ComputeODRHash(FirstDefaultArg);
9415 unsigned SecondODRHash = ComputeODRHash(SecondDefaultArg);
9416 if (FirstODRHash != SecondODRHash) {
9417 ODRDiagError(FirstParam->getLocation(),
9418 FirstParam->getSourceRange(), MethodDefaultArg)
9419 << SecondMD << i + 1;
9420 ODRDiagNote(SecondParam->getLocation(),
9421 SecondParam->getSourceRange(), MethodDefaultArg)
9422 << SecondMD << i + 1;
9423 Diagnosed = true;
9424 break;
9425 }
9426 }
9427 }
9428
9429 // TODO: Figure out how to diagnose different function bodies.
9430 // Deserialization does not import the second function body.
9431
9432 break;
9433 }
9434 case Field: {
9435 // TODO: Merge with exising field diff logic.
9436 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9437 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9438 IdentifierInfo *FirstII = FirstField->getIdentifier();
9439 IdentifierInfo *SecondII = SecondField->getIdentifier();
9440 if (FirstII->getName() != SecondII->getName()) {
9441 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9442 FieldName)
9443 << FirstII;
9444 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9445 FieldName)
9446 << SecondII;
9447 Diagnosed = true;
9448 break;
9449 }
9450
9451 // This case is handled elsewhere.
9452 if (FirstField->getType() != SecondField->getType()) {
9453 break;
9454 }
9455
9456 bool FirstBitField = FirstField->isBitField();
9457 bool SecondBitField = SecondField->isBitField();
9458 if (FirstBitField != SecondBitField) {
9459 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9460 FieldSingleBitField)
9461 << FirstII << FirstBitField;
9462 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9463 FieldSingleBitField)
9464 << SecondII << SecondBitField;
9465 Diagnosed = true;
9466 break;
9467 }
9468
9469 if (FirstBitField && SecondBitField) {
9470 Expr* FirstWidth = FirstField->getBitWidth();
9471 Expr *SecondWidth = SecondField->getBitWidth();
9472 unsigned FirstODRHash = ComputeODRHash(FirstWidth);
9473 unsigned SecondODRHash = ComputeODRHash(SecondWidth);
9474 if (FirstODRHash != SecondODRHash) {
9475 ODRDiagError(FirstField->getLocation(),
9476 FirstField->getSourceRange(), FieldSingleBitField)
9477 << FirstII << FirstBitField;
9478 ODRDiagNote(SecondField->getLocation(),
9479 SecondField->getSourceRange(), FieldSingleBitField)
9480 << SecondII << SecondBitField;
9481 Diagnosed = true;
9482 break;
9483 }
9484 }
9485
9486 bool FirstMutable = FirstField->isMutable();
9487 bool SecondMutable = SecondField->isMutable();
9488 if (FirstMutable != SecondMutable) {
9489 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9490 FieldMutable)
9491 << FirstII << FirstMutable;
9492 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9493 FieldMutable)
9494 << SecondII << SecondMutable;
9495 Diagnosed = true;
9496 break;
9497 }
9498 break;
9499 }
9500 case Other:
9501 case EndOfClass:
9502 case PublicSpecifer:
9503 case PrivateSpecifer:
9504 case ProtectedSpecifer:
9505 llvm_unreachable("Invalid diff type");
9506 }
9507
9508 if (Diagnosed == true)
9509 continue;
9510
9511 // Unable to find difference in Decl's, print simple different
9512 // definitions diagnostic.
9513 Diag(Merge.first->getLocation(),
9514 diag::err_module_odr_violation_different_definitions)
9515 << Merge.first << FirstModule.empty() << FirstModule;
9516 Diag(RD->getLocation(),
9517 diag::note_module_odr_violation_different_definitions)
9518 << SecondModule;
9519 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009520 }
9521
9522 if (!Diagnosed) {
9523 // All definitions are updates to the same declaration. This happens if a
9524 // module instantiates the declaration of a class template specialization
9525 // and two or more other modules instantiate its definition.
9526 //
9527 // FIXME: Indicate which modules had instantiations of this definition.
9528 // FIXME: How can this even happen?
9529 Diag(Merge.first->getLocation(),
9530 diag::err_module_odr_violation_different_instantiations)
9531 << Merge.first;
9532 }
9533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009534}
9535
Richard Smithce18a182015-07-14 00:26:00 +00009536void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009537 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009538 ReadTimer->startTimer();
9539}
9540
Guy Benyei11169dd2012-12-18 14:30:41 +00009541void ASTReader::FinishedDeserializing() {
9542 assert(NumCurrentElementsDeserializing &&
9543 "FinishedDeserializing not paired with StartedDeserializing");
9544 if (NumCurrentElementsDeserializing == 1) {
9545 // We decrease NumCurrentElementsDeserializing only after pending actions
9546 // are finished, to avoid recursively re-calling finishPendingActions().
9547 finishPendingActions();
9548 }
9549 --NumCurrentElementsDeserializing;
9550
Richard Smitha0ce9c42014-07-29 23:23:27 +00009551 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009552 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009553 while (!PendingExceptionSpecUpdates.empty()) {
9554 auto Updates = std::move(PendingExceptionSpecUpdates);
9555 PendingExceptionSpecUpdates.clear();
9556 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009557 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009558 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009559 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009560 if (auto *Listener = Context.getASTMutationListener())
9561 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009562 for (auto *Redecl : Update.second->redecls())
9563 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009564 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009565 }
9566
Richard Smithce18a182015-07-14 00:26:00 +00009567 if (ReadTimer)
9568 ReadTimer->stopTimer();
9569
Richard Smith0f4e2c42015-08-06 04:23:48 +00009570 diagnoseOdrViolations();
9571
Richard Smith04d05b52014-03-23 00:27:18 +00009572 // We are not in recursive loading, so it's safe to pass the "interesting"
9573 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009574 if (Consumer)
9575 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009576 }
9577}
9578
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009579void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009580 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9581 // Remove any fake results before adding any real ones.
9582 auto It = PendingFakeLookupResults.find(II);
9583 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009584 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009585 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009586 // FIXME: this works around module+PCH performance issue.
9587 // Rather than erase the result from the map, which is O(n), just clear
9588 // the vector of NamedDecls.
9589 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009590 }
9591 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009592
9593 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9594 SemaObj->TUScope->AddDecl(D);
9595 } else if (SemaObj->TUScope) {
9596 // Adding the decl to IdResolver may have failed because it was already in
9597 // (even though it was not added in scope). If it is already in, make sure
9598 // it gets in the scope as well.
9599 if (std::find(SemaObj->IdResolver.begin(Name),
9600 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9601 SemaObj->TUScope->AddDecl(D);
9602 }
9603}
9604
David Blaikie61137e12017-01-05 18:23:18 +00009605ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9606 const PCHContainerReader &PCHContainerRdr,
9607 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9608 StringRef isysroot, bool DisableValidation,
9609 bool AllowASTWithCompilerErrors,
9610 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9611 bool UseGlobalIndex,
9612 std::unique_ptr<llvm::Timer> ReadTimer)
9613 : Listener(DisableValidation
9614 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9615 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009616 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009617 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9618 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9619 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009620 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009621 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9622 AllowConfigurationMismatch(AllowConfigurationMismatch),
9623 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009624 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009625 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009626
9627 for (const auto &Ext : Extensions) {
9628 auto BlockName = Ext->getExtensionMetadata().BlockName;
9629 auto Known = ModuleFileExtensions.find(BlockName);
9630 if (Known != ModuleFileExtensions.end()) {
9631 Diags.Report(diag::warn_duplicate_module_file_extension)
9632 << BlockName;
9633 continue;
9634 }
9635
9636 ModuleFileExtensions.insert({BlockName, Ext});
9637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009638}
9639
9640ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009641 if (OwnsDeserializationListener)
9642 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009643}
Richard Smith10379092016-05-06 23:14:07 +00009644
9645IdentifierResolver &ASTReader::getIdResolver() {
9646 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9647}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009648
9649unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9650 unsigned AbbrevID) {
9651 Idx = 0;
9652 Record.clear();
9653 return Cursor.readRecord(AbbrevID, Record);
9654}