blob: be0cc9ab1a8f399d9ed71d944584c9b74fabd2c7 [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001//===-- ASTReader.cpp - AST File Reader -----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000029#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/Type.h"
32#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/UnresolvedSet.h"
34#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000035#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "clang/Basic/FileSystemOptions.h"
39#include "clang/Basic/LangOptions.h"
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;
Richard Smith35845152017-02-07 01:37:30 +0000948 case DeclarationName::CXXDeductionGuideName:
949 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
950 ->getDeclName().getAsIdentifierInfo();
951 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 case DeclarationName::CXXConstructorName:
953 case DeclarationName::CXXDestructorName:
954 case DeclarationName::CXXConversionFunctionName:
955 case DeclarationName::CXXUsingDirective:
956 Data = 0;
957 break;
958 }
959}
960
961unsigned DeclarationNameKey::getHash() const {
962 llvm::FoldingSetNodeID ID;
963 ID.AddInteger(Kind);
964
965 switch (Kind) {
966 case DeclarationName::Identifier:
967 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000968 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000969 ID.AddString(((IdentifierInfo*)Data)->getName());
970 break;
971 case DeclarationName::ObjCZeroArgSelector:
972 case DeclarationName::ObjCOneArgSelector:
973 case DeclarationName::ObjCMultiArgSelector:
974 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
975 break;
976 case DeclarationName::CXXOperatorName:
977 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 break;
979 case DeclarationName::CXXConstructorName:
980 case DeclarationName::CXXDestructorName:
981 case DeclarationName::CXXConversionFunctionName:
982 case DeclarationName::CXXUsingDirective:
983 break;
984 }
985
986 return ID.ComputeHash();
987}
988
Richard Smithd88a7f12015-09-01 20:35:42 +0000989ModuleFile *
990ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
991 using namespace llvm::support;
992 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
993 return Reader.getLocalModuleFile(F, ModuleFileID);
994}
995
Guy Benyei11169dd2012-12-18 14:30:41 +0000996std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000997ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000998 using namespace llvm::support;
999 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1000 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 return std::make_pair(KeyLen, DataLen);
1002}
1003
Richard Smitha06c7e62015-08-26 23:55:49 +00001004ASTDeclContextNameLookupTrait::internal_key_type
1005ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001006 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001007
Richard Smitha06c7e62015-08-26 23:55:49 +00001008 auto Kind = (DeclarationName::NameKind)*d++;
1009 uint64_t Data;
1010 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001012 case DeclarationName::CXXLiteralOperatorName:
1013 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001014 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001015 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::ObjCZeroArgSelector:
1018 case DeclarationName::ObjCOneArgSelector:
1019 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001021 (uint64_t)Reader.getLocalSelector(
1022 F, endian::readNext<uint32_t, little, unaligned>(
1023 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 break;
1025 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001026 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 case DeclarationName::CXXConstructorName:
1029 case DeclarationName::CXXDestructorName:
1030 case DeclarationName::CXXConversionFunctionName:
1031 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 break;
1034 }
1035
Richard Smitha06c7e62015-08-26 23:55:49 +00001036 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001037}
1038
Richard Smithd88a7f12015-09-01 20:35:42 +00001039void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1040 const unsigned char *d,
1041 unsigned DataLen,
1042 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001043 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001044 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1045 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1046 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
Richard Smith0f4e2c42015-08-06 04:23:48 +00001050bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1051 BitstreamCursor &Cursor,
1052 uint64_t Offset,
1053 DeclContext *DC) {
1054 assert(Offset != 0);
1055
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001057 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058
Richard Smith0f4e2c42015-08-06 04:23:48 +00001059 RecordData Record;
1060 StringRef Blob;
1061 unsigned Code = Cursor.ReadCode();
1062 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1063 if (RecCode != DECL_CONTEXT_LEXICAL) {
1064 Error("Expected lexical block");
1065 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 }
1067
Richard Smith82f8fcd2015-08-06 22:07:25 +00001068 assert(!isa<TranslationUnitDecl>(DC) &&
1069 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001070 // If we are handling a C++ class template instantiation, we can see multiple
1071 // lexical updates for the same record. It's important that we select only one
1072 // of them, so that field numbering works properly. Just pick the first one we
1073 // see.
1074 auto &Lex = LexicalDecls[DC];
1075 if (!Lex.first) {
1076 Lex = std::make_pair(
1077 &M, llvm::makeArrayRef(
1078 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1079 Blob.data()),
1080 Blob.size() / 4));
1081 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001082 DC->setHasExternalLexicalStorage(true);
1083 return false;
1084}
Guy Benyei11169dd2012-12-18 14:30:41 +00001085
Richard Smith0f4e2c42015-08-06 04:23:48 +00001086bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1087 BitstreamCursor &Cursor,
1088 uint64_t Offset,
1089 DeclID ID) {
1090 assert(Offset != 0);
1091
1092 SavedStreamPosition SavedPosition(Cursor);
1093 Cursor.JumpToBit(Offset);
1094
1095 RecordData Record;
1096 StringRef Blob;
1097 unsigned Code = Cursor.ReadCode();
1098 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1099 if (RecCode != DECL_CONTEXT_VISIBLE) {
1100 Error("Expected visible lookup table block");
1101 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 }
1103
Richard Smith0f4e2c42015-08-06 04:23:48 +00001104 // We can't safely determine the primary context yet, so delay attaching the
1105 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001106 auto *Data = (const unsigned char*)Blob.data();
1107 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 return false;
1109}
1110
Richard Smith37a93df2017-02-18 00:32:02 +00001111void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001113 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1114 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001115 Diag(diag::note_module_cache_path)
1116 << PP.getHeaderSearchInfo().getModuleCachePath();
1117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001118}
1119
1120void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001121 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 if (Diags.isDiagnosticInFlight())
1123 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1124 else
1125 Diag(DiagID) << Arg1 << Arg2;
1126}
1127
1128//===----------------------------------------------------------------------===//
1129// Source Manager Deserialization
1130//===----------------------------------------------------------------------===//
1131
1132/// \brief Read the line table in the source manager block.
1133/// \returns true if there was an error.
1134bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001135 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 unsigned Idx = 0;
1137 LineTableInfo &LineTable = SourceMgr.getLineTable();
1138
1139 // Parse the file names
1140 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001141 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001143 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1145 }
Richard Smith63078492015-09-01 07:41:55 +00001146 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001147
1148 // Parse the line entries
1149 std::vector<LineEntry> Entries;
1150 while (Idx < Record.size()) {
1151 int FID = Record[Idx++];
1152 assert(FID >= 0 && "Serialized line entries for non-local file.");
1153 // Remap FileID from 1-based old view.
1154 FID += F.SLocEntryBaseID - 1;
1155
1156 // Extract the line entries
1157 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001158 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 Entries.clear();
1160 Entries.reserve(NumEntries);
1161 for (unsigned I = 0; I != NumEntries; ++I) {
1162 unsigned FileOffset = Record[Idx++];
1163 unsigned LineNo = Record[Idx++];
1164 int FilenameID = FileIDs[Record[Idx++]];
1165 SrcMgr::CharacteristicKind FileKind
1166 = (SrcMgr::CharacteristicKind)Record[Idx++];
1167 unsigned IncludeOffset = Record[Idx++];
1168 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1169 FileKind, IncludeOffset));
1170 }
1171 LineTable.AddEntry(FileID::get(FID), Entries);
1172 }
1173
1174 return false;
1175}
1176
1177/// \brief Read a source manager block
1178bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1179 using namespace SrcMgr;
1180
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001181 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001182
1183 // Set the source-location entry cursor to the current position in
1184 // the stream. This cursor will be used to read the contents of the
1185 // source manager block initially, and then lazily read
1186 // source-location entries as needed.
1187 SLocEntryCursor = F.Stream;
1188
1189 // The stream itself is going to skip over the source manager block.
1190 if (F.Stream.SkipBlock()) {
1191 Error("malformed block record in AST file");
1192 return true;
1193 }
1194
1195 // Enter the source manager block.
1196 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1197 Error("malformed source manager block record in AST file");
1198 return true;
1199 }
1200
1201 RecordData Record;
1202 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001203 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001204
Chris Lattnere7b154b2013-01-19 21:39:22 +00001205 switch (E.Kind) {
1206 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1207 case llvm::BitstreamEntry::Error:
1208 Error("malformed block record in AST file");
1209 return true;
1210 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001212 case llvm::BitstreamEntry::Record:
1213 // The interesting case.
1214 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001216
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001219 StringRef Blob;
1220 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 default: // Default behavior: ignore.
1222 break;
1223
1224 case SM_SLOC_FILE_ENTRY:
1225 case SM_SLOC_BUFFER_ENTRY:
1226 case SM_SLOC_EXPANSION_ENTRY:
1227 // Once we hit one of the source location entries, we're done.
1228 return false;
1229 }
1230 }
1231}
1232
1233/// \brief If a header file is not found at the path that we expect it to be
1234/// and the PCH file was moved from its original location, try to resolve the
1235/// file by assuming that header+PCH were moved together and the header is in
1236/// the same place relative to the PCH.
1237static std::string
1238resolveFileRelativeToOriginalDir(const std::string &Filename,
1239 const std::string &OriginalDir,
1240 const std::string &CurrDir) {
1241 assert(OriginalDir != CurrDir &&
1242 "No point trying to resolve the file if the PCH dir didn't change");
1243 using namespace llvm::sys;
1244 SmallString<128> filePath(Filename);
1245 fs::make_absolute(filePath);
1246 assert(path::is_absolute(OriginalDir));
1247 SmallString<128> currPCHPath(CurrDir);
1248
1249 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1250 fileDirE = path::end(path::parent_path(filePath));
1251 path::const_iterator origDirI = path::begin(OriginalDir),
1252 origDirE = path::end(OriginalDir);
1253 // Skip the common path components from filePath and OriginalDir.
1254 while (fileDirI != fileDirE && origDirI != origDirE &&
1255 *fileDirI == *origDirI) {
1256 ++fileDirI;
1257 ++origDirI;
1258 }
1259 for (; origDirI != origDirE; ++origDirI)
1260 path::append(currPCHPath, "..");
1261 path::append(currPCHPath, fileDirI, fileDirE);
1262 path::append(currPCHPath, path::filename(Filename));
1263 return currPCHPath.str();
1264}
1265
1266bool ASTReader::ReadSLocEntry(int ID) {
1267 if (ID == 0)
1268 return false;
1269
1270 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1271 Error("source location entry ID out-of-range for AST file");
1272 return true;
1273 }
1274
Richard Smithaada85c2016-02-06 02:06:43 +00001275 // Local helper to read the (possibly-compressed) buffer data following the
1276 // entry record.
1277 auto ReadBuffer = [this](
1278 BitstreamCursor &SLocEntryCursor,
1279 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1280 RecordData Record;
1281 StringRef Blob;
1282 unsigned Code = SLocEntryCursor.ReadCode();
1283 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1284
1285 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001286 if (!llvm::zlib::isAvailable()) {
1287 Error("zlib is not available");
1288 return nullptr;
1289 }
Richard Smithaada85c2016-02-06 02:06:43 +00001290 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001291 if (llvm::Error E =
1292 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1293 Error("could not decompress embedded file contents: " +
1294 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001295 return nullptr;
1296 }
1297 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1298 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1299 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1300 } else {
1301 Error("AST record has invalid code");
1302 return nullptr;
1303 }
1304 };
1305
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1307 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 unsigned BaseOffset = F->SLocEntryBaseOffset;
1310
1311 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001312 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1313 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 Error("incorrectly-formatted source location entry in AST file");
1315 return true;
1316 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001317
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001319 StringRef Blob;
1320 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 default:
1322 Error("incorrectly-formatted source location entry in AST file");
1323 return true;
1324
1325 case SM_SLOC_FILE_ENTRY: {
1326 // We will detect whether a file changed and return 'Failure' for it, but
1327 // we will also try to fail gracefully by setting up the SLocEntry.
1328 unsigned InputID = Record[4];
1329 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001330 const FileEntry *File = IF.getFile();
1331 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001332
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001333 // Note that we only check if a File was returned. If it was out-of-date
1334 // we have complained but we will continue creating a FileID to recover
1335 // gracefully.
1336 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 return true;
1338
1339 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1340 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1341 // This is the module's main file.
1342 IncludeLoc = getImportLocation(F);
1343 }
1344 SrcMgr::CharacteristicKind
1345 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1346 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1347 ID, BaseOffset + Record[0]);
1348 SrcMgr::FileInfo &FileInfo =
1349 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1350 FileInfo.NumCreatedFIDs = Record[5];
1351 if (Record[3])
1352 FileInfo.setHasLineDirectives();
1353
1354 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1355 unsigned NumFileDecls = Record[7];
1356 if (NumFileDecls) {
1357 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1358 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1359 NumFileDecls));
1360 }
Richard Smithaada85c2016-02-06 02:06:43 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 const SrcMgr::ContentCache *ContentCache
1363 = SourceMgr.getOrCreateContentCache(File,
1364 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1365 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001366 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1367 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001368 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1369 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001371 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 }
1373
1374 break;
1375 }
1376
1377 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001378 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 unsigned Offset = Record[0];
1380 SrcMgr::CharacteristicKind
1381 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1382 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001383 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 IncludeLoc = getImportLocation(F);
1385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001386
Richard Smithaada85c2016-02-06 02:06:43 +00001387 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1388 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001390 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001391 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 break;
1393 }
1394
1395 case SM_SLOC_EXPANSION_ENTRY: {
1396 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1397 SourceMgr.createExpansionLoc(SpellingLoc,
1398 ReadSourceLocation(*F, Record[2]),
1399 ReadSourceLocation(*F, Record[3]),
1400 Record[4],
1401 ID,
1402 BaseOffset + Record[0]);
1403 break;
1404 }
1405 }
1406
1407 return false;
1408}
1409
1410std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1411 if (ID == 0)
1412 return std::make_pair(SourceLocation(), "");
1413
1414 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1415 Error("source location entry ID out-of-range for AST file");
1416 return std::make_pair(SourceLocation(), "");
1417 }
1418
1419 // Find which module file this entry lands in.
1420 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001421 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 return std::make_pair(SourceLocation(), "");
1423
1424 // FIXME: Can we map this down to a particular submodule? That would be
1425 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001426 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001427}
1428
1429/// \brief Find the location where the module F is imported.
1430SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1431 if (F->ImportLoc.isValid())
1432 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001433
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 // Otherwise we have a PCH. It's considered to be "imported" at the first
1435 // location of its includer.
1436 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001437 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001438 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001439 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 return F->ImportedBy[0]->FirstLoc;
1442}
1443
1444/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1445/// specified cursor. Read the abbreviations that are at the top of the block
1446/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001447bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001448 if (Cursor.EnterSubBlock(BlockID))
1449 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001450
1451 while (true) {
1452 uint64_t Offset = Cursor.GetCurrentBitNo();
1453 unsigned Code = Cursor.ReadCode();
1454
1455 // We expect all abbrevs to be at the start of the block.
1456 if (Code != llvm::bitc::DEFINE_ABBREV) {
1457 Cursor.JumpToBit(Offset);
1458 return false;
1459 }
1460 Cursor.ReadAbbrevRecord();
1461 }
1462}
1463
Richard Smithe40f2ba2013-08-07 21:41:30 +00001464Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001465 unsigned &Idx) {
1466 Token Tok;
1467 Tok.startToken();
1468 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1469 Tok.setLength(Record[Idx++]);
1470 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1471 Tok.setIdentifierInfo(II);
1472 Tok.setKind((tok::TokenKind)Record[Idx++]);
1473 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1474 return Tok;
1475}
1476
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001477MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001478 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001479
1480 // Keep track of where we are in the stream, then jump back there
1481 // after reading this macro.
1482 SavedStreamPosition SavedPosition(Stream);
1483
1484 Stream.JumpToBit(Offset);
1485 RecordData Record;
1486 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001487 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001490 // Advance to the next record, but if we get to the end of the block, don't
1491 // pop it (removing all the abbreviations from the cursor) since we want to
1492 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001493 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001494 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001495
Chris Lattnerefa77172013-01-20 00:00:22 +00001496 switch (Entry.Kind) {
1497 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1498 case llvm::BitstreamEntry::Error:
1499 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001500 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001501 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001502 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001503 case llvm::BitstreamEntry::Record:
1504 // The interesting case.
1505 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 }
1507
1508 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 Record.clear();
1510 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001511 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001513 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001514 case PP_MACRO_DIRECTIVE_HISTORY:
1515 return Macro;
1516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 case PP_MACRO_OBJECT_LIKE:
1518 case PP_MACRO_FUNCTION_LIKE: {
1519 // If we already have a macro, that means that we've hit the end
1520 // of the definition of the macro we were looking for. We're
1521 // done.
1522 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001523 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001524
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001525 unsigned NextIndex = 1; // Skip identifier ID.
1526 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001528 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001529 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001531 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1534 // Decode function-like macro info.
1535 bool isC99VarArgs = Record[NextIndex++];
1536 bool isGNUVarArgs = Record[NextIndex++];
1537 bool hasCommaPasting = Record[NextIndex++];
1538 MacroArgs.clear();
1539 unsigned NumArgs = Record[NextIndex++];
1540 for (unsigned i = 0; i != NumArgs; ++i)
1541 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1542
1543 // Install function-like macro info.
1544 MI->setIsFunctionLike();
1545 if (isC99VarArgs) MI->setIsC99Varargs();
1546 if (isGNUVarArgs) MI->setIsGNUVarargs();
1547 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001548 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 }
1550
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 // Remember that we saw this macro last so that we add the tokens that
1552 // form its body to it.
1553 Macro = MI;
1554
1555 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1556 Record[NextIndex]) {
1557 // We have a macro definition. Register the association
1558 PreprocessedEntityID
1559 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1560 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001561 PreprocessingRecord::PPEntityID PPID =
1562 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1563 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1564 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001565 if (PPDef)
1566 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001567 }
1568
1569 ++NumMacrosRead;
1570 break;
1571 }
1572
1573 case PP_TOKEN: {
1574 // If we see a TOKEN before a PP_MACRO_*, then the file is
1575 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001576 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001577
John McCallf413f5e2013-05-03 00:10:13 +00001578 unsigned Idx = 0;
1579 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 Macro->AddTokenToBody(Tok);
1581 break;
1582 }
1583 }
1584 }
1585}
1586
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001587PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001588ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1589 unsigned LocalID) const {
1590 if (!M.ModuleOffsetMap.empty())
1591 ReadModuleOffsetMap(M);
1592
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001593 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001595 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001597
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 return LocalID + I->second;
1599}
1600
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001601unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1602 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001603}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001604
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001605HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001606HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001607 internal_key_type ikey = {FE->getSize(),
1608 M.HasTimestamps ? FE->getModificationTime() : 0,
1609 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001610 return ikey;
1611}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001612
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001613bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001614 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 return false;
1616
Mehdi Amini004b9c72016-10-10 22:52:47 +00001617 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001618 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001619
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001621 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001622 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1623 if (!Key.Imported)
1624 return FileMgr.getFile(Key.Filename);
1625
1626 std::string Resolved = Key.Filename;
1627 Reader.ResolveImportedPath(M, Resolved);
1628 return FileMgr.getFile(Resolved);
1629 };
1630
1631 const FileEntry *FEA = GetFile(a);
1632 const FileEntry *FEB = GetFile(b);
1633 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001635
Guy Benyei11169dd2012-12-18 14:30:41 +00001636std::pair<unsigned, unsigned>
1637HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001638 using namespace llvm::support;
1639 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001641 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001642}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001643
1644HeaderFileInfoTrait::internal_key_type
1645HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001646 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001647 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001648 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1649 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001650 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001651 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001652 return ikey;
1653}
1654
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001655HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001656HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 unsigned DataLen) {
1658 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001659 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 HeaderFileInfo HFI;
1661 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001662 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1663 HFI.isImport |= (Flags >> 4) & 0x01;
1664 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1665 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001667 // FIXME: Find a better way to handle this. Maybe just store a
1668 // "has been included" flag?
1669 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1670 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001671 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1672 M, endian::readNext<uint32_t, little, unaligned>(d));
1673 if (unsigned FrameworkOffset =
1674 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001675 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 // since 0 is used as an indicator for "no framework name".
1677 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1678 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1679 }
Richard Smith386bb072015-08-18 23:42:23 +00001680
1681 assert((End - d) % 4 == 0 &&
1682 "Wrong data length in HeaderFileInfo deserialization");
1683 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001684 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001685 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1686 LocalSMID >>= 2;
1687
1688 // This header is part of a module. Associate it with the module to enable
1689 // implicit module import.
1690 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1691 Module *Mod = Reader.getSubmodule(GlobalSMID);
1692 FileManager &FileMgr = Reader.getFileManager();
1693 ModuleMap &ModMap =
1694 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1695
1696 std::string Filename = key.Filename;
1697 if (key.Imported)
1698 Reader.ResolveImportedPath(M, Filename);
1699 // FIXME: This is not always the right filename-as-written, but we're not
1700 // going to use this information to rebuild the module, so it doesn't make
1701 // a lot of difference.
1702 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001703 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1704 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001705 }
1706
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 // This HeaderFileInfo was externally loaded.
1708 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001709 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 return HFI;
1711}
1712
Richard Smithd7329392015-04-21 21:46:32 +00001713void ASTReader::addPendingMacro(IdentifierInfo *II,
1714 ModuleFile *M,
1715 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001716 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1717 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001718}
1719
1720void ASTReader::ReadDefinedMacros() {
1721 // Note that we are loading defined macros.
1722 Deserializing Macros(this);
1723
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001724 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1725 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001726
1727 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001728 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 continue;
1730
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001731 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001732 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001733
1734 RecordData Record;
1735 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001736 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001737
Chris Lattnere7b154b2013-01-19 21:39:22 +00001738 switch (E.Kind) {
1739 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1740 case llvm::BitstreamEntry::Error:
1741 Error("malformed block record in AST file");
1742 return;
1743 case llvm::BitstreamEntry::EndBlock:
1744 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001745
Chris Lattnere7b154b2013-01-19 21:39:22 +00001746 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001748 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 default: // Default behavior: ignore.
1750 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001751
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001753 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001754 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001755 if (II->isOutOfDate())
1756 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001757 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001758 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001759
Chris Lattnere7b154b2013-01-19 21:39:22 +00001760 case PP_TOKEN:
1761 // Ignore tokens.
1762 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 break;
1765 }
1766 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001767 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 }
1769}
1770
1771namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001772
Guy Benyei11169dd2012-12-18 14:30:41 +00001773 /// \brief Visitor class used to look up identifirs in an AST file.
1774 class IdentifierLookupVisitor {
1775 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001776 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001778 unsigned &NumIdentifierLookups;
1779 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001781
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001783 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1784 unsigned &NumIdentifierLookups,
1785 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001786 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1787 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001788 NumIdentifierLookups(NumIdentifierLookups),
1789 NumIdentifierLookupHits(NumIdentifierLookupHits),
1790 Found()
1791 {
1792 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001793
1794 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001796 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001798
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 ASTIdentifierLookupTable *IdTable
1800 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1801 if (!IdTable)
1802 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001803
1804 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001805 Found);
1806 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001807 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001808 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 if (Pos == IdTable->end())
1810 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001811
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 // Dereferencing the iterator has the effect of building the
1813 // IdentifierInfo node and populating it with the various
1814 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001815 ++NumIdentifierLookupHits;
1816 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 return true;
1818 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001819
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 // \brief Retrieve the identifier info found within the module
1821 // files.
1822 IdentifierInfo *getIdentifierInfo() const { return Found; }
1823 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001824
1825} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001826
1827void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1828 // Note that we are loading an identifier.
1829 Deserializing AnIdentifier(this);
1830
1831 unsigned PriorGeneration = 0;
1832 if (getContext().getLangOpts().Modules)
1833 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001834
1835 // If there is a global index, look there first to determine which modules
1836 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001837 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001838 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001839 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001840 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1841 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001842 }
1843 }
1844
Douglas Gregor7211ac12013-01-25 23:32:03 +00001845 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001846 NumIdentifierLookups,
1847 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001848 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 markIdentifierUpToDate(&II);
1850}
1851
1852void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1853 if (!II)
1854 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001855
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 II->setOutOfDate(false);
1857
1858 // Update the generation for this identifier.
1859 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001860 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001861}
1862
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1864 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001865 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001866
1867 BitstreamCursor &Cursor = M.MacroCursor;
1868 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001869 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001870
Richard Smith713369b2015-04-23 20:40:50 +00001871 struct ModuleMacroRecord {
1872 SubmoduleID SubModID;
1873 MacroInfo *MI;
1874 SmallVector<SubmoduleID, 8> Overrides;
1875 };
1876 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
Richard Smithd7329392015-04-21 21:46:32 +00001878 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1879 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1880 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001881 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001882 while (true) {
1883 llvm::BitstreamEntry Entry =
1884 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1885 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1886 Error("malformed block record in AST file");
1887 return;
1888 }
1889
1890 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001891 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001892 case PP_MACRO_DIRECTIVE_HISTORY:
1893 break;
1894
1895 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001896 ModuleMacros.push_back(ModuleMacroRecord());
1897 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001898 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1899 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001900 for (int I = 2, N = Record.size(); I != N; ++I)
1901 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001902 continue;
1903 }
1904
1905 default:
1906 Error("malformed block record in AST file");
1907 return;
1908 }
1909
1910 // We found the macro directive history; that's the last record
1911 // for this macro.
1912 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001913 }
1914
Richard Smithd7329392015-04-21 21:46:32 +00001915 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001916 {
1917 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001918 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001919 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001920 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001921 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001922 Module *Mod = getSubmodule(ModID);
1923 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001924 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001925 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001926 }
1927
1928 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001929 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001930 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001931 }
1932 }
1933
1934 // Don't read the directive history for a module; we don't have anywhere
1935 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001936 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001937 return;
1938
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001939 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001940 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001941 unsigned Idx = 0, N = Record.size();
1942 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001943 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001944 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1946 switch (K) {
1947 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001948 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001949 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001950 break;
1951 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001952 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001953 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001954 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001955 }
1956 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001957 bool isPublic = Record[Idx++];
1958 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1959 break;
1960 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001961
1962 if (!Latest)
1963 Latest = MD;
1964 if (Earliest)
1965 Earliest->setPrevious(MD);
1966 Earliest = MD;
1967 }
1968
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001969 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001970 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001971}
1972
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001973ASTReader::InputFileInfo
1974ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 // Go find this input file.
1976 BitstreamCursor &Cursor = F.InputFilesCursor;
1977 SavedStreamPosition SavedPosition(Cursor);
1978 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1979
1980 unsigned Code = Cursor.ReadCode();
1981 RecordData Record;
1982 StringRef Blob;
1983
1984 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1985 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1986 "invalid record type for input file");
1987 (void)Result;
1988
1989 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001990 InputFileInfo R;
1991 R.StoredSize = static_cast<off_t>(Record[1]);
1992 R.StoredTime = static_cast<time_t>(Record[2]);
1993 R.Overridden = static_cast<bool>(Record[3]);
1994 R.Transient = static_cast<bool>(Record[4]);
1995 R.Filename = Blob;
1996 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001997 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001998}
1999
Manman Renc8c94152016-10-21 23:35:03 +00002000static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002001InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 // If this ID is bogus, just return an empty input file.
2003 if (ID == 0 || ID > F.InputFilesLoaded.size())
2004 return InputFile();
2005
2006 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002007 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 return F.InputFilesLoaded[ID-1];
2009
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002010 if (F.InputFilesLoaded[ID-1].isNotFound())
2011 return InputFile();
2012
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002014 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 SavedStreamPosition SavedPosition(Cursor);
2016 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002017
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002018 InputFileInfo FI = readInputFileInfo(F, ID);
2019 off_t StoredSize = FI.StoredSize;
2020 time_t StoredTime = FI.StoredTime;
2021 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002022 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002023 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002024
Richard Smitha8cfffa2015-11-26 02:04:16 +00002025 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002026
2027 // If we didn't find the file, resolve it relative to the
2028 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002029 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002030 F.OriginalDir != CurrentDir) {
2031 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2032 F.OriginalDir,
2033 CurrentDir);
2034 if (!Resolved.empty())
2035 File = FileMgr.getFile(Resolved);
2036 }
2037
2038 // For an overridden file, create a virtual file with the stored
2039 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002040 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002042
Craig Toppera13603a2014-05-22 05:54:18 +00002043 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002044 if (Complain) {
2045 std::string ErrorStr = "could not find file '";
2046 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002047 ErrorStr += "' referenced by AST file '";
2048 ErrorStr += F.FileName;
2049 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002050 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 // Record that we didn't find the file.
2053 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2054 return InputFile();
2055 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002056
Ben Langmuir198c1682014-03-07 07:27:49 +00002057 // Check if there was a request to override the contents of the file
2058 // that was part of the precompiled header. Overridding such a file
2059 // can lead to problems when lexing using the source locations from the
2060 // PCH.
2061 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002062 // FIXME: Reject if the overrides are different.
2063 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002064 if (Complain)
2065 Error(diag::err_fe_pch_file_overridden, Filename);
2066 // After emitting the diagnostic, recover by disabling the override so
2067 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002068 //
2069 // FIXME: This recovery is just as broken as the original state; there may
2070 // be another precompiled module that's using the overridden contents, or
2071 // we might be half way through parsing it. Instead, we should treat the
2072 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 SM.disableFileContentsOverride(File);
2074 // The FileEntry is a virtual file entry with the size of the contents
2075 // that would override the original contents. Set it to the original's
2076 // size/time.
2077 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2078 StoredSize, StoredTime);
2079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002080
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 bool IsOutOfDate = false;
2082
2083 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002084 if (!Overridden && //
2085 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002086 (StoredTime && StoredTime != File->getModificationTime() &&
2087 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002088 )) {
2089 if (Complain) {
2090 // Build a list of the PCH imports that got us here (in reverse).
2091 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2092 while (ImportStack.back()->ImportedBy.size() > 0)
2093 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002094
Ben Langmuir198c1682014-03-07 07:27:49 +00002095 // The top-level PCH is stale.
2096 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002097 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2098 if (DiagnosticKind == 0)
2099 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2100 else if (DiagnosticKind == 1)
2101 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2102 else
2103 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002104
Ben Langmuir198c1682014-03-07 07:27:49 +00002105 // Print the import stack.
2106 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2107 Diag(diag::note_pch_required_by)
2108 << Filename << ImportStack[0]->FileName;
2109 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002110 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002111 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002112 }
2113
Ben Langmuir198c1682014-03-07 07:27:49 +00002114 if (!Diags.isDiagnosticInFlight())
2115 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
2117
Ben Langmuir198c1682014-03-07 07:27:49 +00002118 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002120 // FIXME: If the file is overridden and we've already opened it,
2121 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002122
Richard Smitha8cfffa2015-11-26 02:04:16 +00002123 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002124
2125 // Note that we've loaded this input file.
2126 F.InputFilesLoaded[ID-1] = IF;
2127 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002128}
2129
Richard Smith7ed1bc92014-12-05 22:42:13 +00002130/// \brief If we are loading a relocatable PCH or module file, and the filename
2131/// is not an absolute path, add the system or module root to the beginning of
2132/// the file name.
2133void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2134 // Resolve relative to the base directory, if we have one.
2135 if (!M.BaseDirectory.empty())
2136 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002137}
2138
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002140 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2141 return;
2142
Richard Smith7ed1bc92014-12-05 22:42:13 +00002143 SmallString<128> Buffer;
2144 llvm::sys::path::append(Buffer, Prefix, Filename);
2145 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002146}
2147
Richard Smith0f99d6a2015-08-09 08:48:41 +00002148static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2149 switch (ARR) {
2150 case ASTReader::Failure: return true;
2151 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2152 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2153 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2154 case ASTReader::ConfigurationMismatch:
2155 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2156 case ASTReader::HadErrors: return true;
2157 case ASTReader::Success: return false;
2158 }
2159
2160 llvm_unreachable("unknown ASTReadResult");
2161}
2162
Richard Smith0516b182015-09-08 19:40:14 +00002163ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2164 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2165 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002166 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002167 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2168 return Failure;
2169
2170 // Read all of the records in the options block.
2171 RecordData Record;
2172 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002173 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002174 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002175
Richard Smith0516b182015-09-08 19:40:14 +00002176 switch (Entry.Kind) {
2177 case llvm::BitstreamEntry::Error:
2178 case llvm::BitstreamEntry::SubBlock:
2179 return Failure;
2180
2181 case llvm::BitstreamEntry::EndBlock:
2182 return Result;
2183
2184 case llvm::BitstreamEntry::Record:
2185 // The interesting case.
2186 break;
2187 }
2188
2189 // Read and process a record.
2190 Record.clear();
2191 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2192 case LANGUAGE_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2194 if (ParseLanguageOptions(Record, Complain, Listener,
2195 AllowCompatibleConfigurationMismatch))
2196 Result = ConfigurationMismatch;
2197 break;
2198 }
2199
2200 case TARGET_OPTIONS: {
2201 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2202 if (ParseTargetOptions(Record, Complain, Listener,
2203 AllowCompatibleConfigurationMismatch))
2204 Result = ConfigurationMismatch;
2205 break;
2206 }
2207
Richard Smith0516b182015-09-08 19:40:14 +00002208 case FILE_SYSTEM_OPTIONS: {
2209 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2210 if (!AllowCompatibleConfigurationMismatch &&
2211 ParseFileSystemOptions(Record, Complain, Listener))
2212 Result = ConfigurationMismatch;
2213 break;
2214 }
2215
2216 case HEADER_SEARCH_OPTIONS: {
2217 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2218 if (!AllowCompatibleConfigurationMismatch &&
2219 ParseHeaderSearchOptions(Record, Complain, Listener))
2220 Result = ConfigurationMismatch;
2221 break;
2222 }
2223
2224 case PREPROCESSOR_OPTIONS:
2225 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2226 if (!AllowCompatibleConfigurationMismatch &&
2227 ParsePreprocessorOptions(Record, Complain, Listener,
2228 SuggestedPredefines))
2229 Result = ConfigurationMismatch;
2230 break;
2231 }
2232 }
2233}
2234
Guy Benyei11169dd2012-12-18 14:30:41 +00002235ASTReader::ASTReadResult
2236ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002237 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002238 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002240 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002241 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
2243 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2244 Error("malformed block record in AST file");
2245 return Failure;
2246 }
2247
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002248 // Lambda to read the unhashed control block the first time it's called.
2249 //
2250 // For PCM files, the unhashed control block cannot be read until after the
2251 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2252 // need to look ahead before reading the IMPORTS record. For consistency,
2253 // this block is always read somehow (see BitstreamEntry::EndBlock).
2254 bool HasReadUnhashedControlBlock = false;
2255 auto readUnhashedControlBlockOnce = [&]() {
2256 if (!HasReadUnhashedControlBlock) {
2257 HasReadUnhashedControlBlock = true;
2258 if (ASTReadResult Result =
2259 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2260 return Result;
2261 }
2262 return Success;
2263 };
2264
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 // Read all of the records and blocks in the control block.
2266 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002267 unsigned NumInputs = 0;
2268 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002269 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002270 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002271
Chris Lattnere7b154b2013-01-19 21:39:22 +00002272 switch (Entry.Kind) {
2273 case llvm::BitstreamEntry::Error:
2274 Error("malformed block record in AST file");
2275 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002276 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002277 // Validate the module before returning. This call catches an AST with
2278 // no module name and no imports.
2279 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2280 return Result;
2281
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002282 // Validate input files.
2283 const HeaderSearchOptions &HSOpts =
2284 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002285
Richard Smitha1825302014-10-23 22:18:29 +00002286 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002287 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2288 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002289 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2290 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002292
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002293 // If we are reading a module, we will create a verification timestamp,
2294 // so we verify all input files. Otherwise, verify only user input
2295 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002296
2297 unsigned N = NumUserInputs;
2298 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002299 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002300 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002301 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002302 N = NumInputs;
2303
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002304 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002305 InputFile IF = getInputFile(F, I+1, Complain);
2306 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002307 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002308 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002310
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002311 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002312 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002313
Ben Langmuircb69b572014-03-07 06:40:32 +00002314 if (Listener && Listener->needsInputFileVisitation()) {
2315 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2316 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002317 for (unsigned I = 0; I < N; ++I) {
2318 bool IsSystem = I >= NumUserInputs;
2319 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002320 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002321 F.Kind == MK_ExplicitModule ||
2322 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002323 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002324 }
2325
Richard Smith8a308ec2015-11-05 00:54:55 +00002326 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002327 }
2328
Chris Lattnere7b154b2013-01-19 21:39:22 +00002329 case llvm::BitstreamEntry::SubBlock:
2330 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 case INPUT_FILES_BLOCK_ID:
2332 F.InputFilesCursor = Stream;
2333 if (Stream.SkipBlock() || // Skip with the main cursor
2334 // Read the abbreviations
2335 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2336 Error("malformed block record in AST file");
2337 return Failure;
2338 }
2339 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002340
2341 case OPTIONS_BLOCK_ID:
2342 // If we're reading the first module for this group, check its options
2343 // are compatible with ours. For modules it imports, no further checking
2344 // is required, because we checked them when we built it.
2345 if (Listener && !ImportedBy) {
2346 // Should we allow the configuration of the module file to differ from
2347 // the configuration of the current translation unit in a compatible
2348 // way?
2349 //
2350 // FIXME: Allow this for files explicitly specified with -include-pch.
2351 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002352 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002353
Richard Smith8a308ec2015-11-05 00:54:55 +00002354 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2355 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002356 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002357 if (Result == Failure) {
2358 Error("malformed block record in AST file");
2359 return Result;
2360 }
2361
Richard Smith8a308ec2015-11-05 00:54:55 +00002362 if (DisableValidation ||
2363 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2364 Result = Success;
2365
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002366 // If we can't load the module, exit early since we likely
2367 // will rebuild the module anyway. The stream may be in the
2368 // middle of a block.
2369 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002370 return Result;
2371 } else if (Stream.SkipBlock()) {
2372 Error("malformed block record in AST file");
2373 return Failure;
2374 }
2375 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002376
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002378 if (Stream.SkipBlock()) {
2379 Error("malformed block record in AST file");
2380 return Failure;
2381 }
2382 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002384
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 case llvm::BitstreamEntry::Record:
2386 // The interesting case.
2387 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 }
2389
2390 // Read and process a record.
2391 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002392 StringRef Blob;
2393 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 case METADATA: {
2395 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2396 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002397 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2398 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 return VersionMismatch;
2400 }
2401
Richard Smithe75ee0f2015-08-17 07:13:32 +00002402 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2404 Diag(diag::err_pch_with_compiler_errors);
2405 return HadErrors;
2406 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002407 if (hasErrors) {
2408 Diags.ErrorOccurred = true;
2409 Diags.UncompilableErrorOccurred = true;
2410 Diags.UnrecoverableErrorOccurred = true;
2411 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002412
2413 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002414 // Relative paths in a relocatable PCH are relative to our sysroot.
2415 if (F.RelocatablePCH)
2416 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002417
Richard Smithe75ee0f2015-08-17 07:13:32 +00002418 F.HasTimestamps = Record[5];
2419
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002421 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2423 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002424 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 return VersionMismatch;
2426 }
2427 break;
2428 }
2429
2430 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002431 // Validate the AST before processing any imports (otherwise, untangling
2432 // them can be error-prone and expensive). A module will have a name and
2433 // will already have been validated, but this catches the PCH case.
2434 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2435 return Result;
2436
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002437 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 unsigned Idx = 0, N = Record.size();
2439 while (Idx < N) {
2440 // Read information about the AST file.
2441 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2442 // The import location will be the local one for now; we will adjust
2443 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002444 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002446 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002447 off_t StoredSize = (off_t)Record[Idx++];
2448 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002449 ASTFileSignature StoredSignature = {
2450 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2451 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2452 (uint32_t)Record[Idx++]}}};
Richard Smith7ed1bc92014-12-05 22:42:13 +00002453 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002454
Richard Smith0f99d6a2015-08-09 08:48:41 +00002455 // If our client can't cope with us being out of date, we can't cope with
2456 // our dependency being missing.
2457 unsigned Capabilities = ClientLoadCapabilities;
2458 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2459 Capabilities &= ~ARR_Missing;
2460
Guy Benyei11169dd2012-12-18 14:30:41 +00002461 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002462 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2463 Loaded, StoredSize, StoredModTime,
2464 StoredSignature, Capabilities);
2465
2466 // If we diagnosed a problem, produce a backtrace.
2467 if (isDiagnosedResult(Result, Capabilities))
2468 Diag(diag::note_module_file_imported_by)
2469 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2470
2471 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 case Failure: return Failure;
2473 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002474 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 case OutOfDate: return OutOfDate;
2476 case VersionMismatch: return VersionMismatch;
2477 case ConfigurationMismatch: return ConfigurationMismatch;
2478 case HadErrors: return HadErrors;
2479 case Success: break;
2480 }
2481 }
2482 break;
2483 }
2484
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 case ORIGINAL_FILE:
2486 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002487 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002489 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 break;
2491
2492 case ORIGINAL_FILE_ID:
2493 F.OriginalSourceFileID = FileID::get(Record[0]);
2494 break;
2495
2496 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002497 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 break;
2499
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002500 case MODULE_NAME:
2501 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002502 if (Listener)
2503 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002504
2505 // Validate the AST as soon as we have a name so we can exit early on
2506 // failure.
2507 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2508 return Result;
2509
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002510 break;
2511
Richard Smith223d3f22014-12-06 03:21:08 +00002512 case MODULE_DIRECTORY: {
2513 assert(!F.ModuleName.empty() &&
2514 "MODULE_DIRECTORY found before MODULE_NAME");
2515 // If we've already loaded a module map file covering this module, we may
2516 // have a better path for it (relative to the current build).
2517 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2518 if (M && M->Directory) {
2519 // If we're implicitly loading a module, the base directory can't
2520 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002521 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002522 const DirectoryEntry *BuildDir =
2523 PP.getFileManager().getDirectory(Blob);
2524 if (!BuildDir || BuildDir != M->Directory) {
2525 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2526 Diag(diag::err_imported_module_relocated)
2527 << F.ModuleName << Blob << M->Directory->getName();
2528 return OutOfDate;
2529 }
2530 }
2531 F.BaseDirectory = M->Directory->getName();
2532 } else {
2533 F.BaseDirectory = Blob;
2534 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002535 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002536 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002537
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002538 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002539 if (ASTReadResult Result =
2540 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2541 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002542 break;
2543
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002544 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002545 NumInputs = Record[0];
2546 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002547 F.InputFileOffsets =
2548 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002549 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002550 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 break;
2552 }
2553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002554}
2555
Ben Langmuir2c9af442014-04-10 17:57:43 +00002556ASTReader::ASTReadResult
2557ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002558 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002559
2560 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2561 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002562 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 }
2564
2565 // Read all of the records and blocks for the AST file.
2566 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002567 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002568 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002569
Chris Lattnere7b154b2013-01-19 21:39:22 +00002570 switch (Entry.Kind) {
2571 case llvm::BitstreamEntry::Error:
2572 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002574 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002575 // Outside of C++, we do not store a lookup map for the translation unit.
2576 // Instead, mark it as needing a lookup map to be built if this module
2577 // contains any declarations lexically within it (which it always does!).
2578 // This usually has no cost, since we very rarely need the lookup map for
2579 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002581 if (DC->hasExternalLexicalStorage() &&
2582 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002584
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587 case llvm::BitstreamEntry::SubBlock:
2588 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 case DECLTYPES_BLOCK_ID:
2590 // We lazily load the decls block, but we want to set up the
2591 // DeclsCursor cursor to point into it. Clone our current bitcode
2592 // cursor to it, enter the block and read the abbrevs in that block.
2593 // With the main cursor, we just skip over it.
2594 F.DeclsCursor = Stream;
2595 if (Stream.SkipBlock() || // Skip with the main cursor.
2596 // Read the abbrevs.
2597 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2598 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002599 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002602
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 case PREPROCESSOR_BLOCK_ID:
2604 F.MacroCursor = Stream;
2605 if (!PP.getExternalSource())
2606 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002607
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 if (Stream.SkipBlock() ||
2609 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2610 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002611 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 }
2613 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2614 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002615
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 case PREPROCESSOR_DETAIL_BLOCK_ID:
2617 F.PreprocessorDetailCursor = Stream;
2618 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002619 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002621 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002625 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002626
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 if (!PP.getPreprocessingRecord())
2628 PP.createPreprocessingRecord();
2629 if (!PP.getPreprocessingRecord()->getExternalSource())
2630 PP.getPreprocessingRecord()->SetExternalSource(*this);
2631 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002632
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 case SOURCE_MANAGER_BLOCK_ID:
2634 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002635 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002639 if (ASTReadResult Result =
2640 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002641 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002643
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002645 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 if (Stream.SkipBlock() ||
2647 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2648 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002649 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 }
2651 CommentsCursors.push_back(std::make_pair(C, &F));
2652 break;
2653 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002654
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002656 if (Stream.SkipBlock()) {
2657 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002659 }
2660 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 }
2662 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002663
Chris Lattnere7b154b2013-01-19 21:39:22 +00002664 case llvm::BitstreamEntry::Record:
2665 // The interesting case.
2666 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 }
2668
2669 // Read and process a record.
2670 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002671 StringRef Blob;
2672 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 default: // Default behavior: ignore.
2674 break;
2675
2676 case TYPE_OFFSET: {
2677 if (F.LocalNumTypes != 0) {
2678 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002679 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002681 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 F.LocalNumTypes = Record[0];
2683 unsigned LocalBaseTypeIndex = Record[1];
2684 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002685
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 if (F.LocalNumTypes > 0) {
2687 // Introduce the global -> local mapping for types within this module.
2688 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002689
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 // Introduce the local -> global mapping for types within this module.
2691 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002692 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002694
2695 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 }
2697 break;
2698 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002699
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 case DECL_OFFSET: {
2701 if (F.LocalNumDecls != 0) {
2702 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002703 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002705 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 F.LocalNumDecls = Record[0];
2707 unsigned LocalBaseDeclID = Record[1];
2708 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002709
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002711 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 // module.
2713 GlobalDeclMap.insert(
2714 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002715
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // Introduce the local -> global mapping for declarations within this
2717 // module.
2718 F.DeclRemap.insertOrReplace(
2719 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002720
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 // Introduce the global -> local mapping for declarations within this
2722 // module.
2723 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002724
Ben Langmuir52ca6782014-10-20 16:27:32 +00002725 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 break;
2728 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002729
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 case TU_UPDATE_LEXICAL: {
2731 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002732 LexicalContents Contents(
2733 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2734 Blob.data()),
2735 static_cast<unsigned int>(Blob.size() / 4));
2736 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 TU->setHasExternalLexicalStorage(true);
2738 break;
2739 }
2740
2741 case UPDATE_VISIBLE: {
2742 unsigned Idx = 0;
2743 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002744 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002745 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002746 // If we've already loaded the decl, perform the updates when we finish
2747 // loading this block.
2748 if (Decl *D = GetExistingDecl(ID))
2749 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 break;
2751 }
2752
2753 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002754 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002756 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2757 (const unsigned char *)F.IdentifierTableData + Record[0],
2758 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2759 (const unsigned char *)F.IdentifierTableData,
2760 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2763 }
2764 break;
2765
2766 case IDENTIFIER_OFFSET: {
2767 if (F.LocalNumIdentifiers != 0) {
2768 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002769 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002771 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 F.LocalNumIdentifiers = Record[0];
2773 unsigned LocalBaseIdentifierID = Record[1];
2774 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002775
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 if (F.LocalNumIdentifiers > 0) {
2777 // Introduce the global -> local mapping for identifiers within this
2778 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002779 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002781
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 // Introduce the local -> global mapping for identifiers within this
2783 // module.
2784 F.IdentifierRemap.insertOrReplace(
2785 std::make_pair(LocalBaseIdentifierID,
2786 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002787
Ben Langmuir52ca6782014-10-20 16:27:32 +00002788 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2789 + F.LocalNumIdentifiers);
2790 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 break;
2792 }
2793
Richard Smith33e0f7e2015-07-22 02:08:40 +00002794 case INTERESTING_IDENTIFIERS:
2795 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2796 break;
2797
Ben Langmuir332aafe2014-01-31 01:06:56 +00002798 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002799 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2800 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002802 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 break;
2804
David Blaikie9ffe5a32017-01-30 05:00:26 +00002805 case MODULAR_CODEGEN_DECLS:
2806 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2807 // them (ie: if we're not codegenerating this module).
2808 if (F.Kind == MK_MainFile)
2809 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2810 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2811 break;
2812
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002814 if (SpecialTypes.empty()) {
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2817 break;
2818 }
2819
2820 if (SpecialTypes.size() != Record.size()) {
2821 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002822 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002823 }
2824
2825 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2826 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2827 if (!SpecialTypes[I])
2828 SpecialTypes[I] = ID;
2829 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2830 // merge step?
2831 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 break;
2833
2834 case STATISTICS:
2835 TotalNumStatements += Record[0];
2836 TotalNumMacros += Record[1];
2837 TotalLexicalDeclContexts += Record[2];
2838 TotalVisibleDeclContexts += Record[3];
2839 break;
2840
2841 case UNUSED_FILESCOPED_DECLS:
2842 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2843 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2844 break;
2845
2846 case DELEGATING_CTORS:
2847 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2848 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2849 break;
2850
2851 case WEAK_UNDECLARED_IDENTIFIERS:
2852 if (Record.size() % 4 != 0) {
2853 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002854 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002856
2857 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 // files. This isn't the way to do it :)
2859 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 // Translate the weak, undeclared identifiers into global IDs.
2862 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2863 WeakUndeclaredIdentifiers.push_back(
2864 getGlobalIdentifierID(F, Record[I++]));
2865 WeakUndeclaredIdentifiers.push_back(
2866 getGlobalIdentifierID(F, Record[I++]));
2867 WeakUndeclaredIdentifiers.push_back(
2868 ReadSourceLocation(F, Record, I).getRawEncoding());
2869 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2870 }
2871 break;
2872
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002874 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 F.LocalNumSelectors = Record[0];
2876 unsigned LocalBaseSelectorID = Record[1];
2877 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002878
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002880 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 // module.
2882 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002883
2884 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 // module.
2886 F.SelectorRemap.insertOrReplace(
2887 std::make_pair(LocalBaseSelectorID,
2888 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002889
2890 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 }
2892 break;
2893 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002894
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002896 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 if (Record[0])
2898 F.SelectorLookupTable
2899 = ASTSelectorLookupTable::Create(
2900 F.SelectorLookupTableData + Record[0],
2901 F.SelectorLookupTableData,
2902 ASTSelectorLookupTrait(*this, F));
2903 TotalNumMethodPoolEntries += Record[1];
2904 break;
2905
2906 case REFERENCED_SELECTOR_POOL:
2907 if (!Record.empty()) {
2908 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002909 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 Record[Idx++]));
2911 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2912 getRawEncoding());
2913 }
2914 }
2915 break;
2916
2917 case PP_COUNTER_VALUE:
2918 if (!Record.empty() && Listener)
2919 Listener->ReadCounter(F, Record[0]);
2920 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002921
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002923 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 F.NumFileSortedDecls = Record[0];
2925 break;
2926
2927 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002928 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 F.LocalNumSLocEntries = Record[0];
2930 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002931 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002932 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002934 if (!F.SLocEntryBaseID) {
2935 Error("ran out of source locations");
2936 break;
2937 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 // Make our entry in the range map. BaseID is negative and growing, so
2939 // we invert it. Because we invert it, though, we need the other end of
2940 // the range.
2941 unsigned RangeStart =
2942 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2943 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2944 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2945
2946 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2947 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2948 GlobalSLocOffsetMap.insert(
2949 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2950 - SLocSpaceSize,&F));
2951
2952 // Initialize the remapping table.
2953 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002954 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002956 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002958
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 TotalNumSLocEntries += F.LocalNumSLocEntries;
2960 break;
2961 }
2962
Richard Smith37a93df2017-02-18 00:32:02 +00002963 case MODULE_OFFSET_MAP:
2964 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002966
2967 case SOURCE_MANAGER_LINE_TABLE:
2968 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002969 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 break;
2971
2972 case SOURCE_LOCATION_PRELOADS: {
2973 // Need to transform from the local view (1-based IDs) to the global view,
2974 // which is based off F.SLocEntryBaseID.
2975 if (!F.PreloadSLocEntries.empty()) {
2976 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002977 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002979
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 F.PreloadSLocEntries.swap(Record);
2981 break;
2982 }
2983
2984 case EXT_VECTOR_DECLS:
2985 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2986 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2987 break;
2988
2989 case VTABLE_USES:
2990 if (Record.size() % 3 != 0) {
2991 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002992 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002994
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 // Later tables overwrite earlier ones.
2996 // FIXME: Modules will have some trouble with this. This is clearly not
2997 // the right way to do this.
2998 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002999
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3001 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3002 VTableUses.push_back(
3003 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3004 VTableUses.push_back(Record[Idx++]);
3005 }
3006 break;
3007
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 case PENDING_IMPLICIT_INSTANTIATIONS:
3009 if (PendingInstantiations.size() % 2 != 0) {
3010 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003011 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 }
3013
3014 if (Record.size() % 2 != 0) {
3015 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003016 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 }
3018
3019 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3020 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3021 PendingInstantiations.push_back(
3022 ReadSourceLocation(F, Record, I).getRawEncoding());
3023 }
3024 break;
3025
3026 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003027 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003028 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003029 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3032 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3033 break;
3034
3035 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003036 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3037 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3038 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003039
3040 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003041
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 unsigned StartingID;
3043 if (!PP.getPreprocessingRecord())
3044 PP.createPreprocessingRecord();
3045 if (!PP.getPreprocessingRecord()->getExternalSource())
3046 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003047 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003049 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 F.BasePreprocessedEntityID = StartingID;
3051
3052 if (F.NumPreprocessedEntities > 0) {
3053 // Introduce the global -> local mapping for preprocessed entities in
3054 // this module.
3055 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003056
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 // Introduce the local -> global mapping for preprocessed entities in
3058 // this module.
3059 F.PreprocessedEntityRemap.insertOrReplace(
3060 std::make_pair(LocalBasePreprocessedEntityID,
3061 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3062 }
3063
3064 break;
3065 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003066
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 case DECL_UPDATE_OFFSETS: {
3068 if (Record.size() % 2 != 0) {
3069 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003072 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3073 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3074 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3075
3076 // If we've already loaded the decl, perform the updates when we finish
3077 // loading this block.
3078 if (Decl *D = GetExistingDecl(ID))
3079 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3080 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 break;
3082 }
3083
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 case OBJC_CATEGORIES_MAP: {
3085 if (F.LocalNumObjCCategoriesInMap != 0) {
3086 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003087 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003089
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003091 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 break;
3093 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003094
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 case OBJC_CATEGORIES:
3096 F.ObjCCategories.swap(Record);
3097 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003098
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 case CUDA_SPECIAL_DECL_REFS:
3100 // Later tables overwrite earlier ones.
3101 // FIXME: Modules will have trouble with this.
3102 CUDASpecialDeclRefs.clear();
3103 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3104 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3105 break;
3106
3107 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003108 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 if (Record[0]) {
3111 F.HeaderFileInfoTable
3112 = HeaderFileInfoLookupTable::Create(
3113 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3114 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003115 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003117 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 PP.getHeaderSearchInfo().SetExternalSource(this);
3120 if (!PP.getHeaderSearchInfo().getExternalLookup())
3121 PP.getHeaderSearchInfo().SetExternalLookup(this);
3122 }
3123 break;
3124 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003125
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 case FP_PRAGMA_OPTIONS:
3127 // Later tables overwrite earlier ones.
3128 FPPragmaOptions.swap(Record);
3129 break;
3130
3131 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003132 for (unsigned I = 0, E = Record.size(); I != E; ) {
3133 auto Name = ReadString(Record, I);
3134 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003135 Opt.Supported = Record[I++] != 0;
3136 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003137 Opt.Avail = Record[I++];
3138 Opt.Core = Record[I++];
3139 }
3140 break;
3141
3142 case OPENCL_EXTENSION_TYPES:
3143 for (unsigned I = 0, E = Record.size(); I != E;) {
3144 auto TypeID = static_cast<::TypeID>(Record[I++]);
3145 auto *Type = GetType(TypeID).getTypePtr();
3146 auto NumExt = static_cast<unsigned>(Record[I++]);
3147 for (unsigned II = 0; II != NumExt; ++II) {
3148 auto Ext = ReadString(Record, I);
3149 OpenCLTypeExtMap[Type].insert(Ext);
3150 }
3151 }
3152 break;
3153
3154 case OPENCL_EXTENSION_DECLS:
3155 for (unsigned I = 0, E = Record.size(); I != E;) {
3156 auto DeclID = static_cast<::DeclID>(Record[I++]);
3157 auto *Decl = GetDecl(DeclID);
3158 auto NumExt = static_cast<unsigned>(Record[I++]);
3159 for (unsigned II = 0; II != NumExt; ++II) {
3160 auto Ext = ReadString(Record, I);
3161 OpenCLDeclExtMap[Decl].insert(Ext);
3162 }
3163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 break;
3165
3166 case TENTATIVE_DEFINITIONS:
3167 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3168 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3169 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003170
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 case KNOWN_NAMESPACES:
3172 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3173 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3174 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003175
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003176 case UNDEFINED_BUT_USED:
3177 if (UndefinedButUsed.size() % 2 != 0) {
3178 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003179 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003180 }
3181
3182 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003183 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003184 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003185 }
3186 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003187 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3188 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003189 ReadSourceLocation(F, Record, I).getRawEncoding());
3190 }
3191 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003192 case DELETE_EXPRS_TO_ANALYZE:
3193 for (unsigned I = 0, N = Record.size(); I != N;) {
3194 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3195 const uint64_t Count = Record[I++];
3196 DelayedDeleteExprs.push_back(Count);
3197 for (uint64_t C = 0; C < Count; ++C) {
3198 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3199 bool IsArrayForm = Record[I++] == 1;
3200 DelayedDeleteExprs.push_back(IsArrayForm);
3201 }
3202 }
3203 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003204
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003206 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 // If we aren't loading a module (which has its own exports), make
3208 // all of the imported modules visible.
3209 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003210 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3211 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3212 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003213 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003214 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003215 if (DeserializationListener)
3216 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 }
3219 }
3220 break;
3221 }
3222
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 case MACRO_OFFSET: {
3224 if (F.LocalNumMacros != 0) {
3225 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003226 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003228 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 F.LocalNumMacros = Record[0];
3230 unsigned LocalBaseMacroID = Record[1];
3231 F.BaseMacroID = getTotalNumMacros();
3232
3233 if (F.LocalNumMacros > 0) {
3234 // Introduce the global -> local mapping for macros within this module.
3235 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3236
3237 // Introduce the local -> global mapping for macros within this module.
3238 F.MacroRemap.insertOrReplace(
3239 std::make_pair(LocalBaseMacroID,
3240 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003241
3242 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003243 }
3244 break;
3245 }
3246
Richard Smithe40f2ba2013-08-07 21:41:30 +00003247 case LATE_PARSED_TEMPLATE: {
3248 LateParsedTemplates.append(Record.begin(), Record.end());
3249 break;
3250 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003251
3252 case OPTIMIZE_PRAGMA_OPTIONS:
3253 if (Record.size() != 1) {
3254 Error("invalid pragma optimize record");
3255 return Failure;
3256 }
3257 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3258 break;
Nico Weber72889432014-09-06 01:25:55 +00003259
Nico Weber779355f2016-03-02 23:22:00 +00003260 case MSSTRUCT_PRAGMA_OPTIONS:
3261 if (Record.size() != 1) {
3262 Error("invalid pragma ms_struct record");
3263 return Failure;
3264 }
3265 PragmaMSStructState = Record[0];
3266 break;
3267
Nico Weber42932312016-03-03 00:17:35 +00003268 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3269 if (Record.size() != 2) {
3270 Error("invalid pragma ms_struct record");
3271 return Failure;
3272 }
3273 PragmaMSPointersToMembersState = Record[0];
3274 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3275 break;
3276
Nico Weber72889432014-09-06 01:25:55 +00003277 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3278 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3279 UnusedLocalTypedefNameCandidates.push_back(
3280 getGlobalDeclID(F, Record[I]));
3281 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003282
3283 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3284 if (Record.size() != 1) {
3285 Error("invalid cuda pragma options record");
3286 return Failure;
3287 }
3288 ForceCUDAHostDeviceDepth = Record[0];
3289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 }
3291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003292}
3293
Richard Smith37a93df2017-02-18 00:32:02 +00003294void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3295 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3296
3297 // Additional remapping information.
3298 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3299 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3300 F.ModuleOffsetMap = StringRef();
3301
3302 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3303 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3304 F.SLocRemap.insert(std::make_pair(0U, 0));
3305 F.SLocRemap.insert(std::make_pair(2U, 1));
3306 }
3307
3308 // Continuous range maps we may be updating in our module.
3309 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3310 RemapBuilder;
3311 RemapBuilder SLocRemap(F.SLocRemap);
3312 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3313 RemapBuilder MacroRemap(F.MacroRemap);
3314 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3315 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3316 RemapBuilder SelectorRemap(F.SelectorRemap);
3317 RemapBuilder DeclRemap(F.DeclRemap);
3318 RemapBuilder TypeRemap(F.TypeRemap);
3319
3320 while (Data < DataEnd) {
3321 // FIXME: Looking up dependency modules by filename is horrible.
3322 using namespace llvm::support;
3323 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3324 StringRef Name = StringRef((const char*)Data, Len);
3325 Data += Len;
3326 ModuleFile *OM = ModuleMgr.lookup(Name);
3327 if (!OM) {
3328 std::string Msg =
3329 "SourceLocation remap refers to unknown module, cannot find ";
3330 Msg.append(Name);
3331 Error(Msg);
3332 return;
3333 }
3334
3335 uint32_t SLocOffset =
3336 endian::readNext<uint32_t, little, unaligned>(Data);
3337 uint32_t IdentifierIDOffset =
3338 endian::readNext<uint32_t, little, unaligned>(Data);
3339 uint32_t MacroIDOffset =
3340 endian::readNext<uint32_t, little, unaligned>(Data);
3341 uint32_t PreprocessedEntityIDOffset =
3342 endian::readNext<uint32_t, little, unaligned>(Data);
3343 uint32_t SubmoduleIDOffset =
3344 endian::readNext<uint32_t, little, unaligned>(Data);
3345 uint32_t SelectorIDOffset =
3346 endian::readNext<uint32_t, little, unaligned>(Data);
3347 uint32_t DeclIDOffset =
3348 endian::readNext<uint32_t, little, unaligned>(Data);
3349 uint32_t TypeIndexOffset =
3350 endian::readNext<uint32_t, little, unaligned>(Data);
3351
3352 uint32_t None = std::numeric_limits<uint32_t>::max();
3353
3354 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3355 RemapBuilder &Remap) {
3356 if (Offset != None)
3357 Remap.insert(std::make_pair(Offset,
3358 static_cast<int>(BaseOffset - Offset)));
3359 };
3360 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3361 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3362 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3363 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3364 PreprocessedEntityRemap);
3365 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3366 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3367 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3368 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3369
3370 // Global -> local mappings.
3371 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3372 }
3373}
3374
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375ASTReader::ASTReadResult
3376ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3377 const ModuleFile *ImportedBy,
3378 unsigned ClientLoadCapabilities) {
3379 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003380 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003381
Manman Ren11f2a472016-08-18 17:42:15 +00003382 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003383 // For an explicitly-loaded module, we don't care whether the original
3384 // module map file exists or matches.
3385 return Success;
3386 }
3387
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003388 // Try to resolve ModuleName in the current header search context and
3389 // verify that it is found in the same module map file as we saved. If the
3390 // top-level AST file is a main file, skip this check because there is no
3391 // usable header search context.
3392 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003393 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003394 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003395 // An implicitly-loaded module file should have its module listed in some
3396 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003397 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003398 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3399 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3400 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003401 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003402 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3403 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3404 // This module was defined by an imported (explicit) module.
3405 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3406 << ASTFE->getName();
3407 else
3408 // This module was built with a different module map.
3409 Diag(diag::err_imported_module_not_found)
3410 << F.ModuleName << F.FileName << ImportedBy->FileName
3411 << F.ModuleMapPath;
3412 }
3413 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003414 }
3415
Richard Smithe842a472014-10-22 02:05:46 +00003416 assert(M->Name == F.ModuleName && "found module with different name");
3417
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003418 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003419 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003420 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3421 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003422 assert(ImportedBy && "top-level import should be verified");
3423 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3424 Diag(diag::err_imported_module_modmap_changed)
3425 << F.ModuleName << ImportedBy->FileName
3426 << ModMap->getName() << F.ModuleMapPath;
3427 return OutOfDate;
3428 }
3429
3430 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3431 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3432 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003433 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003434 const FileEntry *F =
3435 FileMgr.getFile(Filename, false, false);
3436 if (F == nullptr) {
3437 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3438 Error("could not find file '" + Filename +"' referenced by AST file");
3439 return OutOfDate;
3440 }
3441 AdditionalStoredMaps.insert(F);
3442 }
3443
3444 // Check any additional module map files (e.g. module.private.modulemap)
3445 // that are not in the pcm.
3446 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3447 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3448 // Remove files that match
3449 // Note: SmallPtrSet::erase is really remove
3450 if (!AdditionalStoredMaps.erase(ModMap)) {
3451 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3452 Diag(diag::err_module_different_modmap)
3453 << F.ModuleName << /*new*/0 << ModMap->getName();
3454 return OutOfDate;
3455 }
3456 }
3457 }
3458
3459 // Check any additional module map files that are in the pcm, but not
3460 // found in header search. Cases that match are already removed.
3461 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3462 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3463 Diag(diag::err_module_different_modmap)
3464 << F.ModuleName << /*not new*/1 << ModMap->getName();
3465 return OutOfDate;
3466 }
3467 }
3468
3469 if (Listener)
3470 Listener->ReadModuleMapFile(F.ModuleMapPath);
3471 return Success;
3472}
3473
3474
Douglas Gregorc1489562013-02-12 23:36:21 +00003475/// \brief Move the given method to the back of the global list of methods.
3476static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3477 // Find the entry for this selector in the method pool.
3478 Sema::GlobalMethodPool::iterator Known
3479 = S.MethodPool.find(Method->getSelector());
3480 if (Known == S.MethodPool.end())
3481 return;
3482
3483 // Retrieve the appropriate method list.
3484 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3485 : Known->second.second;
3486 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003487 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003488 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003489 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003490 Found = true;
3491 } else {
3492 // Keep searching.
3493 continue;
3494 }
3495 }
3496
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003497 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003498 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003499 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003500 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003501 }
3502}
3503
Richard Smithde711422015-04-23 21:20:19 +00003504void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003505 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003506 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003507 bool wasHidden = D->Hidden;
3508 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003509
Richard Smith49f906a2014-03-01 00:08:04 +00003510 if (wasHidden && SemaObj) {
3511 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3512 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 }
3515 }
3516}
3517
Richard Smith49f906a2014-03-01 00:08:04 +00003518void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003519 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003520 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003522 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003523 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003525 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003526
3527 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003528 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 // there is nothing more to do.
3530 continue;
3531 }
Richard Smith49f906a2014-03-01 00:08:04 +00003532
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 if (!Mod->isAvailable()) {
3534 // Modules that aren't available cannot be made visible.
3535 continue;
3536 }
3537
3538 // Update the module's name visibility.
3539 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003540
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 // If we've already deserialized any names from this module,
3542 // mark them as visible.
3543 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3544 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003545 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003547 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003548 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3549 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003551
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003553 SmallVector<Module *, 16> Exports;
3554 Mod->getExportedModules(Exports);
3555 for (SmallVectorImpl<Module *>::iterator
3556 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3557 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003558 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003559 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 }
3561 }
3562}
3563
Richard Smith6561f922016-09-12 21:06:40 +00003564/// We've merged the definition \p MergedDef into the existing definition
3565/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3566/// visible.
3567void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3568 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003569 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3570 // in modules other than its owning module. We should instead give the
3571 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003572 if (Def->isHidden()) {
3573 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003574 if (!MergedDef->isHidden())
3575 Def->Hidden = false;
3576 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3577 getContext().mergeDefinitionIntoModule(
3578 Def, MergedDef->getImportedOwningModule(),
3579 /*NotifyListeners*/ false);
3580 PendingMergedDefinitionsToDeduplicate.insert(Def);
3581 } else {
3582 auto SubmoduleID = MergedDef->getOwningModuleID();
3583 assert(SubmoduleID && "hidden definition in no module");
3584 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3585 }
Richard Smith6561f922016-09-12 21:06:40 +00003586 }
3587}
3588
Douglas Gregore060e572013-01-25 01:03:03 +00003589bool ASTReader::loadGlobalIndex() {
3590 if (GlobalIndex)
3591 return false;
3592
3593 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3594 !Context.getLangOpts().Modules)
3595 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003596
Douglas Gregore060e572013-01-25 01:03:03 +00003597 // Try to load the global index.
3598 TriedLoadingGlobalIndex = true;
3599 StringRef ModuleCachePath
3600 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3601 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003602 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003603 if (!Result.first)
3604 return true;
3605
3606 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003607 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003608 return false;
3609}
3610
3611bool ASTReader::isGlobalIndexUnavailable() const {
3612 return Context.getLangOpts().Modules && UseGlobalIndex &&
3613 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3614}
3615
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003616static void updateModuleTimestamp(ModuleFile &MF) {
3617 // Overwrite the timestamp file contents so that file's mtime changes.
3618 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003619 std::error_code EC;
3620 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3621 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003622 return;
3623 OS << "Timestamp file\n";
3624}
3625
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003626/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3627/// cursor into the start of the given block ID, returning false on success and
3628/// true on failure.
3629static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003630 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003631 llvm::BitstreamEntry Entry = Cursor.advance();
3632 switch (Entry.Kind) {
3633 case llvm::BitstreamEntry::Error:
3634 case llvm::BitstreamEntry::EndBlock:
3635 return true;
3636
3637 case llvm::BitstreamEntry::Record:
3638 // Ignore top-level records.
3639 Cursor.skipRecord(Entry.ID);
3640 break;
3641
3642 case llvm::BitstreamEntry::SubBlock:
3643 if (Entry.ID == BlockID) {
3644 if (Cursor.EnterSubBlock(BlockID))
3645 return true;
3646 // Found it!
3647 return false;
3648 }
3649
3650 if (Cursor.SkipBlock())
3651 return true;
3652 }
3653 }
3654}
3655
Benjamin Kramer0772c422016-02-13 13:42:54 +00003656ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 ModuleKind Type,
3658 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003659 unsigned ClientLoadCapabilities,
3660 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003661 llvm::SaveAndRestore<SourceLocation>
3662 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3663
Richard Smithd1c46742014-04-30 02:24:17 +00003664 // Defer any pending actions until we get to the end of reading the AST file.
3665 Deserializing AnASTFile(this);
3666
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003668 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003669
3670 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003671 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003672 switch (ASTReadResult ReadResult =
3673 ReadASTCore(FileName, Type, ImportLoc,
3674 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3675 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003677 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 case OutOfDate:
3679 case VersionMismatch:
3680 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003681 case HadErrors: {
3682 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3683 for (const ImportedModule &IM : Loaded)
3684 LoadedSet.insert(IM.Mod);
3685
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003686 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003687 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003688 ? &PP.getHeaderSearchInfo().getModuleMap()
3689 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003690
3691 // If we find that any modules are unusable, the global index is going
3692 // to be out-of-date. Just remove it.
3693 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003694 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003696 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 case Success:
3698 break;
3699 }
3700
3701 // Here comes stuff that we only do once the entire chain is loaded.
3702
3703 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003704 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3705 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 M != MEnd; ++M) {
3707 ModuleFile &F = *M->Mod;
3708
3709 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003710 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3711 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003712
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003713 // Read the extension blocks.
3714 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3715 if (ASTReadResult Result = ReadExtensionBlock(F))
3716 return Result;
3717 }
3718
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003719 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 // bits of all files we've seen.
3721 F.GlobalBitOffset = TotalModulesSizeInBits;
3722 TotalModulesSizeInBits += F.SizeInBits;
3723 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003724
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 // Preload SLocEntries.
3726 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3727 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3728 // Load it through the SourceManager and don't call ReadSLocEntry()
3729 // directly because the entry may have already been loaded in which case
3730 // calling ReadSLocEntry() directly would trigger an assertion in
3731 // SourceManager.
3732 SourceMgr.getLoadedSLocEntryByID(Index);
3733 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003734
3735 // Preload all the pending interesting identifiers by marking them out of
3736 // date.
3737 for (auto Offset : F.PreloadIdentifierOffsets) {
3738 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3739 F.IdentifierTableData + Offset);
3740
3741 ASTIdentifierLookupTrait Trait(*this, F);
3742 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3743 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003744 auto &II = PP.getIdentifierTable().getOwn(Key);
3745 II.setOutOfDate(true);
3746
3747 // Mark this identifier as being from an AST file so that we can track
3748 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003749 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003750
3751 // Associate the ID with the identifier so that the writer can reuse it.
3752 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3753 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003754 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 }
3756
Douglas Gregor603cd862013-03-22 18:50:14 +00003757 // Setup the import locations and notify the module manager that we've
3758 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003759 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3760 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 M != MEnd; ++M) {
3762 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003763
3764 ModuleMgr.moduleFileAccepted(&F);
3765
3766 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003767 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003768 // FIXME: We assume that locations from PCH / preamble do not need
3769 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 if (!M->ImportedBy)
3771 F.ImportLoc = M->ImportLoc;
3772 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003773 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 }
3775
Richard Smith33e0f7e2015-07-22 02:08:40 +00003776 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003777 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3778 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003779 // Mark all of the identifiers in the identifier table as being out of date,
3780 // so that various accessors know to check the loaded modules when the
3781 // identifier is used.
3782 //
3783 // For C++ modules, we don't need information on many identifiers (just
3784 // those that provide macros or are poisoned), so we mark all of
3785 // the interesting ones via PreloadIdentifierOffsets.
3786 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3787 IdEnd = PP.getIdentifierTable().end();
3788 Id != IdEnd; ++Id)
3789 Id->second->setOutOfDate(true);
3790 }
Manman Rena0f31a02016-04-29 19:04:05 +00003791 // Mark selectors as out of date.
3792 for (auto Sel : SelectorGeneration)
3793 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003794
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003796 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3797 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3799 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003800
3801 switch (Unresolved.Kind) {
3802 case UnresolvedModuleRef::Conflict:
3803 if (ResolvedMod) {
3804 Module::Conflict Conflict;
3805 Conflict.Other = ResolvedMod;
3806 Conflict.Message = Unresolved.String.str();
3807 Unresolved.Mod->Conflicts.push_back(Conflict);
3808 }
3809 continue;
3810
3811 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003813 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003815
Douglas Gregorfb912652013-03-20 21:10:35 +00003816 case UnresolvedModuleRef::Export:
3817 if (ResolvedMod || Unresolved.IsWildcard)
3818 Unresolved.Mod->Exports.push_back(
3819 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3820 continue;
3821 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003823 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003824
Graydon Hoaree7196af2016-12-09 21:45:49 +00003825 if (Imported)
3826 Imported->append(ImportedModules.begin(),
3827 ImportedModules.end());
3828
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003829 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3830 // Might be unnecessary as use declarations are only used to build the
3831 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003832
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 InitializeContext();
3834
Richard Smith3d8e97e2013-10-18 06:54:39 +00003835 if (SemaObj)
3836 UpdateSema();
3837
Guy Benyei11169dd2012-12-18 14:30:41 +00003838 if (DeserializationListener)
3839 DeserializationListener->ReaderInitialized(this);
3840
3841 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003842 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003843 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 = FileID::get(PrimaryModule.SLocEntryBaseID
3845 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3846
3847 // If this AST file is a precompiled preamble, then set the
3848 // preamble file ID of the source manager to the file source file
3849 // from which the preamble was built.
3850 if (Type == MK_Preamble) {
3851 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3852 } else if (Type == MK_MainFile) {
3853 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3854 }
3855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003856
Guy Benyei11169dd2012-12-18 14:30:41 +00003857 // For any Objective-C class definitions we have already loaded, make sure
3858 // that we load any additional categories.
3859 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003860 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003861 ObjCClassesLoaded[I],
3862 PreviousGeneration);
3863 }
Douglas Gregore060e572013-01-25 01:03:03 +00003864
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003865 if (PP.getHeaderSearchInfo()
3866 .getHeaderSearchOpts()
3867 .ModulesValidateOncePerBuildSession) {
3868 // Now we are certain that the module and all modules it depends on are
3869 // up to date. Create or update timestamp files for modules that are
3870 // located in the module cache (not for PCH files that could be anywhere
3871 // in the filesystem).
3872 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3873 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003874 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003875 updateModuleTimestamp(*M.Mod);
3876 }
3877 }
3878 }
3879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 return Success;
3881}
3882
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003883static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003884
Ben Langmuir70a1b812015-03-24 04:43:52 +00003885/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3886static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003887 return Stream.canSkipToPos(4) &&
3888 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003889 Stream.Read(8) == 'P' &&
3890 Stream.Read(8) == 'C' &&
3891 Stream.Read(8) == 'H';
3892}
3893
Richard Smith0f99d6a2015-08-09 08:48:41 +00003894static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3895 switch (Kind) {
3896 case MK_PCH:
3897 return 0; // PCH
3898 case MK_ImplicitModule:
3899 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003900 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003901 return 1; // module
3902 case MK_MainFile:
3903 case MK_Preamble:
3904 return 2; // main source file
3905 }
3906 llvm_unreachable("unknown module kind");
3907}
3908
Guy Benyei11169dd2012-12-18 14:30:41 +00003909ASTReader::ASTReadResult
3910ASTReader::ReadASTCore(StringRef FileName,
3911 ModuleKind Type,
3912 SourceLocation ImportLoc,
3913 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003914 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003915 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003916 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 unsigned ClientLoadCapabilities) {
3918 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003920 ModuleManager::AddModuleResult AddResult
3921 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003922 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003923 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003924 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003925
Douglas Gregor7029ce12013-03-19 00:28:20 +00003926 switch (AddResult) {
3927 case ModuleManager::AlreadyLoaded:
3928 return Success;
3929
3930 case ModuleManager::NewlyLoaded:
3931 // Load module file below.
3932 break;
3933
3934 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003935 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003936 // it.
3937 if (ClientLoadCapabilities & ARR_Missing)
3938 return Missing;
3939
3940 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003941 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003942 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003943 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003944 return Failure;
3945
3946 case ModuleManager::OutOfDate:
3947 // We couldn't load the module file because it is out-of-date. If the
3948 // client can handle out-of-date, return it.
3949 if (ClientLoadCapabilities & ARR_OutOfDate)
3950 return OutOfDate;
3951
3952 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003953 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003954 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003955 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 return Failure;
3957 }
3958
Douglas Gregor7029ce12013-03-19 00:28:20 +00003959 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003960
3961 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3962 // module?
3963 if (FileName != "-") {
3964 CurrentDir = llvm::sys::path::parent_path(FileName);
3965 if (CurrentDir.empty()) CurrentDir = ".";
3966 }
3967
3968 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003969 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003970 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003971 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003972
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003974 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003975 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3976 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 return Failure;
3978 }
3979
3980 // This is used for compatibility with older PCH formats.
3981 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003982 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003983 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003984
Chris Lattnerefa77172013-01-20 00:00:22 +00003985 switch (Entry.Kind) {
3986 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003987 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003988 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 Error("invalid record at top-level of AST file");
3990 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003991
Chris Lattnerefa77172013-01-20 00:00:22 +00003992 case llvm::BitstreamEntry::SubBlock:
3993 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 }
3995
Chris Lattnerefa77172013-01-20 00:00:22 +00003996 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 case CONTROL_BLOCK_ID:
3998 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003999 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004001 // Check that we didn't try to load a non-module AST file as a module.
4002 //
4003 // FIXME: Should we also perform the converse check? Loading a module as
4004 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004005 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4006 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004007 F.ModuleName.empty()) {
4008 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4009 if (Result != OutOfDate ||
4010 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4011 Diag(diag::err_module_file_not_module) << FileName;
4012 return Result;
4013 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 break;
4015
4016 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004017 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 case OutOfDate: return OutOfDate;
4019 case VersionMismatch: return VersionMismatch;
4020 case ConfigurationMismatch: return ConfigurationMismatch;
4021 case HadErrors: return HadErrors;
4022 }
4023 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004024
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 case AST_BLOCK_ID:
4026 if (!HaveReadControlBlock) {
4027 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004028 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 return VersionMismatch;
4030 }
4031
4032 // Record that we've loaded this module.
4033 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4034 return Success;
4035
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004036 case UNHASHED_CONTROL_BLOCK_ID:
4037 // This block is handled using look-ahead during ReadControlBlock. We
4038 // shouldn't get here!
4039 Error("malformed block record in AST file");
4040 return Failure;
4041
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 default:
4043 if (Stream.SkipBlock()) {
4044 Error("malformed block record in AST file");
4045 return Failure;
4046 }
4047 break;
4048 }
4049 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004050
4051 return Success;
4052}
4053
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004054ASTReader::ASTReadResult
4055ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4056 unsigned ClientLoadCapabilities) {
4057 const HeaderSearchOptions &HSOpts =
4058 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4059 bool AllowCompatibleConfigurationMismatch =
4060 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4061
4062 ASTReadResult Result = readUnhashedControlBlockImpl(
4063 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4064 Listener.get(),
4065 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4066
4067 if (DisableValidation || WasImportedBy ||
4068 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4069 return Success;
4070
4071 if (Result == Failure)
4072 Error("malformed block record in AST file");
4073
4074 return Result;
4075}
4076
4077ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4078 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4079 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4080 bool ValidateDiagnosticOptions) {
4081 // Initialize a stream.
4082 BitstreamCursor Stream(StreamData);
4083
4084 // Sniff for the signature.
4085 if (!startsWithASTFileMagic(Stream))
4086 return Failure;
4087
4088 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4089 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4090 return Failure;
4091
4092 // Read all of the records in the options block.
4093 RecordData Record;
4094 ASTReadResult Result = Success;
4095 while (1) {
4096 llvm::BitstreamEntry Entry = Stream.advance();
4097
4098 switch (Entry.Kind) {
4099 case llvm::BitstreamEntry::Error:
4100 case llvm::BitstreamEntry::SubBlock:
4101 return Failure;
4102
4103 case llvm::BitstreamEntry::EndBlock:
4104 return Result;
4105
4106 case llvm::BitstreamEntry::Record:
4107 // The interesting case.
4108 break;
4109 }
4110
4111 // Read and process a record.
4112 Record.clear();
4113 switch (
4114 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4115 case SIGNATURE: {
4116 if (F)
4117 std::copy(Record.begin(), Record.end(), F->Signature.data());
4118 break;
4119 }
4120 case DIAGNOSTIC_OPTIONS: {
4121 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4122 if (Listener && ValidateDiagnosticOptions &&
4123 !AllowCompatibleConfigurationMismatch &&
4124 ParseDiagnosticOptions(Record, Complain, *Listener))
4125 return OutOfDate;
4126 break;
4127 }
4128 case DIAG_PRAGMA_MAPPINGS:
4129 if (!F)
4130 break;
4131 if (F->PragmaDiagMappings.empty())
4132 F->PragmaDiagMappings.swap(Record);
4133 else
4134 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4135 Record.begin(), Record.end());
4136 break;
4137 }
4138 }
4139}
4140
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004141/// Parse a record and blob containing module file extension metadata.
4142static bool parseModuleFileExtensionMetadata(
4143 const SmallVectorImpl<uint64_t> &Record,
4144 StringRef Blob,
4145 ModuleFileExtensionMetadata &Metadata) {
4146 if (Record.size() < 4) return true;
4147
4148 Metadata.MajorVersion = Record[0];
4149 Metadata.MinorVersion = Record[1];
4150
4151 unsigned BlockNameLen = Record[2];
4152 unsigned UserInfoLen = Record[3];
4153
4154 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4155
4156 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4157 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4158 Blob.data() + BlockNameLen + UserInfoLen);
4159 return false;
4160}
4161
4162ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4163 BitstreamCursor &Stream = F.Stream;
4164
4165 RecordData Record;
4166 while (true) {
4167 llvm::BitstreamEntry Entry = Stream.advance();
4168 switch (Entry.Kind) {
4169 case llvm::BitstreamEntry::SubBlock:
4170 if (Stream.SkipBlock())
4171 return Failure;
4172
4173 continue;
4174
4175 case llvm::BitstreamEntry::EndBlock:
4176 return Success;
4177
4178 case llvm::BitstreamEntry::Error:
4179 return HadErrors;
4180
4181 case llvm::BitstreamEntry::Record:
4182 break;
4183 }
4184
4185 Record.clear();
4186 StringRef Blob;
4187 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4188 switch (RecCode) {
4189 case EXTENSION_METADATA: {
4190 ModuleFileExtensionMetadata Metadata;
4191 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4192 return Failure;
4193
4194 // Find a module file extension with this block name.
4195 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4196 if (Known == ModuleFileExtensions.end()) break;
4197
4198 // Form a reader.
4199 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4200 F, Stream)) {
4201 F.ExtensionReaders.push_back(std::move(Reader));
4202 }
4203
4204 break;
4205 }
4206 }
4207 }
4208
4209 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004210}
4211
Richard Smitha7e2cc62015-05-01 01:53:09 +00004212void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 // If there's a listener, notify them that we "read" the translation unit.
4214 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004215 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 Context.getTranslationUnitDecl());
4217
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 // FIXME: Find a better way to deal with collisions between these
4219 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004220
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 // Load the special types.
4222 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4223 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4224 if (!Context.CFConstantStringTypeDecl)
4225 Context.setCFConstantStringType(GetType(String));
4226 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004227
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4229 QualType FileType = GetType(File);
4230 if (FileType.isNull()) {
4231 Error("FILE type is NULL");
4232 return;
4233 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004234
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 if (!Context.FILEDecl) {
4236 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4237 Context.setFILEDecl(Typedef->getDecl());
4238 else {
4239 const TagType *Tag = FileType->getAs<TagType>();
4240 if (!Tag) {
4241 Error("Invalid FILE type in AST file");
4242 return;
4243 }
4244 Context.setFILEDecl(Tag->getDecl());
4245 }
4246 }
4247 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004248
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4250 QualType Jmp_bufType = GetType(Jmp_buf);
4251 if (Jmp_bufType.isNull()) {
4252 Error("jmp_buf type is NULL");
4253 return;
4254 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004255
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 if (!Context.jmp_bufDecl) {
4257 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4258 Context.setjmp_bufDecl(Typedef->getDecl());
4259 else {
4260 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4261 if (!Tag) {
4262 Error("Invalid jmp_buf type in AST file");
4263 return;
4264 }
4265 Context.setjmp_bufDecl(Tag->getDecl());
4266 }
4267 }
4268 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004269
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4271 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4272 if (Sigjmp_bufType.isNull()) {
4273 Error("sigjmp_buf type is NULL");
4274 return;
4275 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 if (!Context.sigjmp_bufDecl) {
4278 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4279 Context.setsigjmp_bufDecl(Typedef->getDecl());
4280 else {
4281 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4282 assert(Tag && "Invalid sigjmp_buf type in AST file");
4283 Context.setsigjmp_bufDecl(Tag->getDecl());
4284 }
4285 }
4286 }
4287
4288 if (unsigned ObjCIdRedef
4289 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4290 if (Context.ObjCIdRedefinitionType.isNull())
4291 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4292 }
4293
4294 if (unsigned ObjCClassRedef
4295 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4296 if (Context.ObjCClassRedefinitionType.isNull())
4297 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4298 }
4299
4300 if (unsigned ObjCSelRedef
4301 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4302 if (Context.ObjCSelRedefinitionType.isNull())
4303 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4304 }
4305
4306 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4307 QualType Ucontext_tType = GetType(Ucontext_t);
4308 if (Ucontext_tType.isNull()) {
4309 Error("ucontext_t type is NULL");
4310 return;
4311 }
4312
4313 if (!Context.ucontext_tDecl) {
4314 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4315 Context.setucontext_tDecl(Typedef->getDecl());
4316 else {
4317 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4318 assert(Tag && "Invalid ucontext_t type in AST file");
4319 Context.setucontext_tDecl(Tag->getDecl());
4320 }
4321 }
4322 }
4323 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004324
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4326
4327 // If there were any CUDA special declarations, deserialize them.
4328 if (!CUDASpecialDeclRefs.empty()) {
4329 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4330 Context.setcudaConfigureCallDecl(
4331 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4332 }
Richard Smith56be7542014-03-21 00:33:59 +00004333
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004335 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004336 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004337 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004338 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004339 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004340 if (Import.ImportLoc.isValid())
4341 PP.makeModuleVisible(Imported, Import.ImportLoc);
4342 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 }
4345 ImportedModules.clear();
4346}
4347
4348void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004349 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004350}
4351
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004352/// \brief Reads and return the signature record from \p PCH's control block, or
4353/// else returns 0.
4354static ASTFileSignature readASTFileSignature(StringRef PCH) {
4355 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004356 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004357 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004358
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004359 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4360 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4361 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004362
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004363 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004364 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004365 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004366 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004367 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004368 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004369
4370 Record.clear();
4371 StringRef Blob;
4372 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004373 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4374 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004375 }
4376}
4377
Guy Benyei11169dd2012-12-18 14:30:41 +00004378/// \brief Retrieve the name of the original source file name
4379/// directly from the AST file, without actually loading the AST
4380/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004381std::string ASTReader::getOriginalSourceFile(
4382 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004383 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004385 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004387 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4388 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 return std::string();
4390 }
4391
4392 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004393 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004394
4395 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004396 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4398 return std::string();
4399 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004400
Chris Lattnere7b154b2013-01-19 21:39:22 +00004401 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004402 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004403 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4404 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004405 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004406
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004407 // Scan for ORIGINAL_FILE inside the control block.
4408 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004409 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004410 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004411 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4412 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004413
Chris Lattnere7b154b2013-01-19 21:39:22 +00004414 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4415 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4416 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004418
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004420 StringRef Blob;
4421 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4422 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004424}
4425
4426namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004427
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 class SimplePCHValidator : public ASTReaderListener {
4429 const LangOptions &ExistingLangOpts;
4430 const TargetOptions &ExistingTargetOpts;
4431 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004432 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004434
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 public:
4436 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4437 const TargetOptions &ExistingTargetOpts,
4438 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004439 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 FileManager &FileMgr)
4441 : ExistingLangOpts(ExistingLangOpts),
4442 ExistingTargetOpts(ExistingTargetOpts),
4443 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004444 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 FileMgr(FileMgr)
4446 {
4447 }
4448
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004449 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4450 bool AllowCompatibleDifferences) override {
4451 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4452 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004454
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004455 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4456 bool AllowCompatibleDifferences) override {
4457 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4458 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004460
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004461 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4462 StringRef SpecificModuleCachePath,
4463 bool Complain) override {
4464 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4465 ExistingModuleCachePath,
4466 nullptr, ExistingLangOpts);
4467 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004468
Craig Topper3e89dfe2014-03-13 02:13:41 +00004469 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4470 bool Complain,
4471 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004472 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004473 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
4475 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004476
4477} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004478
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004479bool ASTReader::readASTFileControlBlock(
4480 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004481 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004482 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004483 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004485 // FIXME: This allows use of the VFS; we do not allow use of the
4486 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004487 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 if (!Buffer) {
4489 return true;
4490 }
4491
4492 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004493 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4494 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004495
4496 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004497 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004500 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004501 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004502 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004503
4504 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004505 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004506 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004507 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004508
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004510 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004511 bool DoneWithControlBlock = false;
4512 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004513 llvm::BitstreamEntry Entry = Stream.advance();
4514
4515 switch (Entry.Kind) {
4516 case llvm::BitstreamEntry::SubBlock: {
4517 switch (Entry.ID) {
4518 case OPTIONS_BLOCK_ID: {
4519 std::string IgnoredSuggestedPredefines;
4520 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4521 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004522 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004523 return true;
4524 break;
4525 }
4526
4527 case INPUT_FILES_BLOCK_ID:
4528 InputFilesCursor = Stream;
4529 if (Stream.SkipBlock() ||
4530 (NeedsInputFiles &&
4531 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4532 return true;
4533 break;
4534
4535 default:
4536 if (Stream.SkipBlock())
4537 return true;
4538 break;
4539 }
4540
4541 continue;
4542 }
4543
4544 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004545 DoneWithControlBlock = true;
4546 break;
Richard Smith0516b182015-09-08 19:40:14 +00004547
4548 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004549 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004550
4551 case llvm::BitstreamEntry::Record:
4552 break;
4553 }
4554
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004555 if (DoneWithControlBlock) break;
4556
Guy Benyei11169dd2012-12-18 14:30:41 +00004557 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004558 StringRef Blob;
4559 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004560 switch ((ControlRecordTypes)RecCode) {
4561 case METADATA: {
4562 if (Record[0] != VERSION_MAJOR)
4563 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004564
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004565 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004566 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004567
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004568 break;
4569 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004570 case MODULE_NAME:
4571 Listener.ReadModuleName(Blob);
4572 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004573 case MODULE_DIRECTORY:
4574 ModuleDir = Blob;
4575 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004576 case MODULE_MAP_FILE: {
4577 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004578 auto Path = ReadString(Record, Idx);
4579 ResolveImportedPath(Path, ModuleDir);
4580 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004581 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004582 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004583 case INPUT_FILE_OFFSETS: {
4584 if (!NeedsInputFiles)
4585 break;
4586
4587 unsigned NumInputFiles = Record[0];
4588 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004589 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004590 for (unsigned I = 0; I != NumInputFiles; ++I) {
4591 // Go find this input file.
4592 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004593
4594 if (isSystemFile && !NeedsSystemInputFiles)
4595 break; // the rest are system input files
4596
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004597 BitstreamCursor &Cursor = InputFilesCursor;
4598 SavedStreamPosition SavedPosition(Cursor);
4599 Cursor.JumpToBit(InputFileOffs[I]);
4600
4601 unsigned Code = Cursor.ReadCode();
4602 RecordData Record;
4603 StringRef Blob;
4604 bool shouldContinue = false;
4605 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4606 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004607 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004608 std::string Filename = Blob;
4609 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004610 shouldContinue = Listener.visitInputFile(
4611 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004612 break;
4613 }
4614 if (!shouldContinue)
4615 break;
4616 }
4617 break;
4618 }
4619
Richard Smithd4b230b2014-10-27 23:01:16 +00004620 case IMPORTS: {
4621 if (!NeedsImports)
4622 break;
4623
4624 unsigned Idx = 0, N = Record.size();
4625 while (Idx < N) {
4626 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004627 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004628 std::string Filename = ReadString(Record, Idx);
4629 ResolveImportedPath(Filename, ModuleDir);
4630 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004631 }
4632 break;
4633 }
4634
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004635 default:
4636 // No other validation to perform.
4637 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 }
4639 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004640
4641 // Look for module file extension blocks, if requested.
4642 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004643 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004644 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4645 bool DoneWithExtensionBlock = false;
4646 while (!DoneWithExtensionBlock) {
4647 llvm::BitstreamEntry Entry = Stream.advance();
4648
4649 switch (Entry.Kind) {
4650 case llvm::BitstreamEntry::SubBlock:
4651 if (Stream.SkipBlock())
4652 return true;
4653
4654 continue;
4655
4656 case llvm::BitstreamEntry::EndBlock:
4657 DoneWithExtensionBlock = true;
4658 continue;
4659
4660 case llvm::BitstreamEntry::Error:
4661 return true;
4662
4663 case llvm::BitstreamEntry::Record:
4664 break;
4665 }
4666
4667 Record.clear();
4668 StringRef Blob;
4669 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4670 switch (RecCode) {
4671 case EXTENSION_METADATA: {
4672 ModuleFileExtensionMetadata Metadata;
4673 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4674 return true;
4675
4676 Listener.readModuleFileExtension(Metadata);
4677 break;
4678 }
4679 }
4680 }
4681 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004682 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004683 }
4684
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004685 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4686 if (readUnhashedControlBlockImpl(
4687 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4688 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4689 ValidateDiagnosticOptions) != Success)
4690 return true;
4691
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004692 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004693}
4694
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004695bool ASTReader::isAcceptableASTFile(
4696 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004697 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004698 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4699 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004700 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4701 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004702 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004703 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004704 validator,
4705 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004706}
4707
Ben Langmuir2c9af442014-04-10 17:57:43 +00004708ASTReader::ASTReadResult
4709ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 // Enter the submodule block.
4711 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4712 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004713 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 }
4715
4716 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4717 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004718 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 RecordData Record;
4720 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004721 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004722
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004723 switch (Entry.Kind) {
4724 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4725 case llvm::BitstreamEntry::Error:
4726 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004727 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004728 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004729 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004730 case llvm::BitstreamEntry::Record:
4731 // The interesting case.
4732 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004734
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004736 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004738 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4739
4740 if ((Kind == SUBMODULE_METADATA) != First) {
4741 Error("submodule metadata record should be at beginning of block");
4742 return Failure;
4743 }
4744 First = false;
4745
4746 // Submodule information is only valid if we have a current module.
4747 // FIXME: Should we error on these cases?
4748 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4749 Kind != SUBMODULE_DEFINITION)
4750 continue;
4751
4752 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 default: // Default behavior: ignore.
4754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004755
Richard Smith03478d92014-10-23 22:12:14 +00004756 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004757 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004759 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 }
Richard Smith03478d92014-10-23 22:12:14 +00004761
Chris Lattner0e6c9402013-01-20 02:38:54 +00004762 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004763 unsigned Idx = 0;
4764 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4765 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4766 bool IsFramework = Record[Idx++];
4767 bool IsExplicit = Record[Idx++];
4768 bool IsSystem = Record[Idx++];
4769 bool IsExternC = Record[Idx++];
4770 bool InferSubmodules = Record[Idx++];
4771 bool InferExplicitSubmodules = Record[Idx++];
4772 bool InferExportWildcard = Record[Idx++];
4773 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004774 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004775
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004776 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004777 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004779
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 // Retrieve this (sub)module from the module map, creating it if
4781 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004782 CurrentModule =
4783 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4784 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004785
4786 // FIXME: set the definition loc for CurrentModule, or call
4787 // ModMap.setInferredModuleAllowedBy()
4788
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4790 if (GlobalIndex >= SubmodulesLoaded.size() ||
4791 SubmodulesLoaded[GlobalIndex]) {
4792 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004793 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004795
Douglas Gregor7029ce12013-03-19 00:28:20 +00004796 if (!ParentModule) {
4797 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4798 if (CurFile != F.File) {
4799 if (!Diags.isDiagnosticInFlight()) {
4800 Diag(diag::err_module_file_conflict)
4801 << CurrentModule->getTopLevelModuleName()
4802 << CurFile->getName()
4803 << F.File->getName();
4804 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004805 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004806 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004807 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004808
4809 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004810 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004811
Adrian Prantl15bcf702015-06-30 17:39:43 +00004812 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 CurrentModule->IsFromModuleFile = true;
4814 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004815 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 CurrentModule->InferSubmodules = InferSubmodules;
4817 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4818 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004819 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004820 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 if (DeserializationListener)
4822 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004823
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004825
Richard Smith8a3e39a2016-03-28 21:31:09 +00004826 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004827 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004828 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004829 CurrentModule->UnresolvedConflicts.clear();
4830 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004831
4832 // The module is available unless it's missing a requirement; relevant
4833 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4834 // Missing headers that were present when the module was built do not
4835 // make it unavailable -- if we got this far, this must be an explicitly
4836 // imported module file.
4837 CurrentModule->Requirements.clear();
4838 CurrentModule->MissingHeaders.clear();
4839 CurrentModule->IsMissingRequirement =
4840 ParentModule && ParentModule->IsMissingRequirement;
4841 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 break;
4843 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004844
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004846 std::string Filename = Blob;
4847 ResolveImportedPath(F, Filename);
4848 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004850 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4851 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004852 // This can be a spurious difference caused by changing the VFS to
4853 // point to a different copy of the file, and it is too late to
4854 // to rebuild safely.
4855 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4856 // after input file validation only real problems would remain and we
4857 // could just error. For now, assume it's okay.
4858 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 }
4860 }
4861 break;
4862 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004863
Richard Smith202210b2014-10-24 20:23:01 +00004864 case SUBMODULE_HEADER:
4865 case SUBMODULE_EXCLUDED_HEADER:
4866 case SUBMODULE_PRIVATE_HEADER:
4867 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004868 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4869 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004870 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004871
Richard Smith202210b2014-10-24 20:23:01 +00004872 case SUBMODULE_TEXTUAL_HEADER:
4873 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4874 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4875 // them here.
4876 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004877
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004879 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 break;
4881 }
4882
4883 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004884 std::string Dirname = Blob;
4885 ResolveImportedPath(F, Dirname);
4886 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004888 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4889 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004890 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4891 Error("mismatched umbrella directories in submodule");
4892 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 }
4894 }
4895 break;
4896 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004897
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 F.BaseSubmoduleID = getTotalNumSubmodules();
4900 F.LocalNumSubmodules = Record[0];
4901 unsigned LocalBaseSubmoduleID = Record[1];
4902 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004903 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 // module.
4905 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004906
4907 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 // module.
4909 F.SubmoduleRemap.insertOrReplace(
4910 std::make_pair(LocalBaseSubmoduleID,
4911 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004912
Ben Langmuir52ca6782014-10-20 16:27:32 +00004913 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4914 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 break;
4916 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004917
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004920 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 Unresolved.File = &F;
4922 Unresolved.Mod = CurrentModule;
4923 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004924 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004926 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004927 }
4928 break;
4929 }
4930
4931 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004933 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 Unresolved.File = &F;
4935 Unresolved.Mod = CurrentModule;
4936 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004937 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004939 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004941
4942 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 // the parsed, unresolved exports around.
4944 CurrentModule->UnresolvedExports.clear();
4945 break;
4946 }
4947 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004948 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 Context.getTargetInfo());
4950 break;
4951 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004952
4953 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004954 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004955 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004956 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004957
4958 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004959 CurrentModule->ConfigMacros.push_back(Blob.str());
4960 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004961
4962 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004963 UnresolvedModuleRef Unresolved;
4964 Unresolved.File = &F;
4965 Unresolved.Mod = CurrentModule;
4966 Unresolved.ID = Record[0];
4967 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4968 Unresolved.IsWildcard = false;
4969 Unresolved.String = Blob;
4970 UnresolvedModuleRefs.push_back(Unresolved);
4971 break;
4972 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004973
4974 case SUBMODULE_INITIALIZERS:
4975 SmallVector<uint32_t, 16> Inits;
4976 for (auto &ID : Record)
4977 Inits.push_back(getGlobalDeclID(F, ID));
4978 Context.addLazyModuleInitializers(CurrentModule, Inits);
4979 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 }
4981 }
4982}
4983
4984/// \brief Parse the record that corresponds to a LangOptions data
4985/// structure.
4986///
4987/// This routine parses the language options from the AST file and then gives
4988/// them to the AST listener if one is set.
4989///
4990/// \returns true if the listener deems the file unacceptable, false otherwise.
4991bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4992 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004993 ASTReaderListener &Listener,
4994 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 LangOptions LangOpts;
4996 unsigned Idx = 0;
4997#define LANGOPT(Name, Bits, Default, Description) \
4998 LangOpts.Name = Record[Idx++];
4999#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5000 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5001#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005002#define SANITIZER(NAME, ID) \
5003 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005004#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005005
Ben Langmuircd98cb72015-06-23 18:20:18 +00005006 for (unsigned N = Record[Idx++]; N; --N)
5007 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5008
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5010 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5011 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005012
Ben Langmuird4a667a2015-06-23 18:20:23 +00005013 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005014
5015 // Comment options.
5016 for (unsigned N = Record[Idx++]; N; --N) {
5017 LangOpts.CommentOpts.BlockCommandNames.push_back(
5018 ReadString(Record, Idx));
5019 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005020 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005021
Samuel Antaoee8fb302016-01-06 13:42:12 +00005022 // OpenMP offloading options.
5023 for (unsigned N = Record[Idx++]; N; --N) {
5024 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5025 }
5026
5027 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5028
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005029 return Listener.ReadLanguageOptions(LangOpts, Complain,
5030 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005031}
5032
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005033bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5034 ASTReaderListener &Listener,
5035 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 unsigned Idx = 0;
5037 TargetOptions TargetOpts;
5038 TargetOpts.Triple = ReadString(Record, Idx);
5039 TargetOpts.CPU = ReadString(Record, Idx);
5040 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 for (unsigned N = Record[Idx++]; N; --N) {
5042 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5043 }
5044 for (unsigned N = Record[Idx++]; N; --N) {
5045 TargetOpts.Features.push_back(ReadString(Record, Idx));
5046 }
5047
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005048 return Listener.ReadTargetOptions(TargetOpts, Complain,
5049 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005050}
5051
5052bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5053 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005054 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005056#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005057#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005058 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005059#include "clang/Basic/DiagnosticOptions.def"
5060
Richard Smith3be1cb22014-08-07 00:24:21 +00005061 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005062 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005063 for (unsigned N = Record[Idx++]; N; --N)
5064 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005065
5066 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5067}
5068
5069bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5070 ASTReaderListener &Listener) {
5071 FileSystemOptions FSOpts;
5072 unsigned Idx = 0;
5073 FSOpts.WorkingDir = ReadString(Record, Idx);
5074 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5075}
5076
5077bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5078 bool Complain,
5079 ASTReaderListener &Listener) {
5080 HeaderSearchOptions HSOpts;
5081 unsigned Idx = 0;
5082 HSOpts.Sysroot = ReadString(Record, Idx);
5083
5084 // Include entries.
5085 for (unsigned N = Record[Idx++]; N; --N) {
5086 std::string Path = ReadString(Record, Idx);
5087 frontend::IncludeDirGroup Group
5088 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 bool IsFramework = Record[Idx++];
5090 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005091 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5092 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 }
5094
5095 // System header prefixes.
5096 for (unsigned N = Record[Idx++]; N; --N) {
5097 std::string Prefix = ReadString(Record, Idx);
5098 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005099 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 }
5101
5102 HSOpts.ResourceDir = ReadString(Record, Idx);
5103 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005104 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 HSOpts.DisableModuleHash = Record[Idx++];
5106 HSOpts.UseBuiltinIncludes = Record[Idx++];
5107 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5108 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5109 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005110 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005111
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005112 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5113 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005114}
5115
5116bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5117 bool Complain,
5118 ASTReaderListener &Listener,
5119 std::string &SuggestedPredefines) {
5120 PreprocessorOptions PPOpts;
5121 unsigned Idx = 0;
5122
5123 // Macro definitions/undefs
5124 for (unsigned N = Record[Idx++]; N; --N) {
5125 std::string Macro = ReadString(Record, Idx);
5126 bool IsUndef = Record[Idx++];
5127 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5128 }
5129
5130 // Includes
5131 for (unsigned N = Record[Idx++]; N; --N) {
5132 PPOpts.Includes.push_back(ReadString(Record, Idx));
5133 }
5134
5135 // Macro Includes
5136 for (unsigned N = Record[Idx++]; N; --N) {
5137 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5138 }
5139
5140 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005141 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5143 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5144 PPOpts.ObjCXXARCStandardLibrary =
5145 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5146 SuggestedPredefines.clear();
5147 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5148 SuggestedPredefines);
5149}
5150
5151std::pair<ModuleFile *, unsigned>
5152ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5153 GlobalPreprocessedEntityMapType::iterator
5154 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005155 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005156 "Corrupted global preprocessed entity map");
5157 ModuleFile *M = I->second;
5158 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5159 return std::make_pair(M, LocalIndex);
5160}
5161
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005162llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005163ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5164 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5165 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5166 Mod.NumPreprocessedEntities);
5167
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005168 return llvm::make_range(PreprocessingRecord::iterator(),
5169 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005170}
5171
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005172llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005173ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005174 return llvm::make_range(
5175 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5176 ModuleDeclIterator(this, &Mod,
5177 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005178}
5179
5180PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5181 PreprocessedEntityID PPID = Index+1;
5182 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5183 ModuleFile &M = *PPInfo.first;
5184 unsigned LocalIndex = PPInfo.second;
5185 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5186
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 if (!PP.getPreprocessingRecord()) {
5188 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005189 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005191
5192 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005193 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5194
5195 llvm::BitstreamEntry Entry =
5196 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5197 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005198 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005199
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005201 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5202 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005204 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 RecordData Record;
5206 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005207 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5208 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 switch (RecType) {
5210 case PPD_MACRO_EXPANSION: {
5211 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005212 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005213 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 if (isBuiltin)
5215 Name = getLocalIdentifier(M, Record[1]);
5216 else {
Richard Smith66a81862015-05-04 02:25:31 +00005217 PreprocessedEntityID GlobalID =
5218 getGlobalPreprocessedEntityID(M, Record[1]);
5219 Def = cast<MacroDefinitionRecord>(
5220 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 }
5222
5223 MacroExpansion *ME;
5224 if (isBuiltin)
5225 ME = new (PPRec) MacroExpansion(Name, Range);
5226 else
5227 ME = new (PPRec) MacroExpansion(Def, Range);
5228
5229 return ME;
5230 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005231
Guy Benyei11169dd2012-12-18 14:30:41 +00005232 case PPD_MACRO_DEFINITION: {
5233 // Decode the identifier info and then check again; if the macro is
5234 // still defined and associated with the identifier,
5235 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005236 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005237
5238 if (DeserializationListener)
5239 DeserializationListener->MacroDefinitionRead(PPID, MD);
5240
5241 return MD;
5242 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005243
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005245 const char *FullFileNameStart = Blob.data() + Record[0];
5246 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005247 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 if (!FullFileName.empty())
5249 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005250
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 // FIXME: Stable encoding
5252 InclusionDirective::InclusionKind Kind
5253 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5254 InclusionDirective *ID
5255 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005256 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005257 Record[1], Record[3],
5258 File,
5259 Range);
5260 return ID;
5261 }
5262 }
5263
5264 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5265}
5266
5267/// \brief \arg SLocMapI points at a chunk of a module that contains no
5268/// preprocessed entities or the entities it contains are not the ones we are
5269/// looking for. Find the next module that contains entities and return the ID
5270/// of the first entry.
5271PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5272 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5273 ++SLocMapI;
5274 for (GlobalSLocOffsetMapType::const_iterator
5275 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5276 ModuleFile &M = *SLocMapI->second;
5277 if (M.NumPreprocessedEntities)
5278 return M.BasePreprocessedEntityID;
5279 }
5280
5281 return getTotalNumPreprocessedEntities();
5282}
5283
5284namespace {
5285
Guy Benyei11169dd2012-12-18 14:30:41 +00005286struct PPEntityComp {
5287 const ASTReader &Reader;
5288 ModuleFile &M;
5289
5290 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5291
5292 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5293 SourceLocation LHS = getLoc(L);
5294 SourceLocation RHS = getLoc(R);
5295 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5296 }
5297
5298 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5299 SourceLocation LHS = getLoc(L);
5300 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5301 }
5302
5303 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5304 SourceLocation RHS = getLoc(R);
5305 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5306 }
5307
5308 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005309 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 }
5311};
5312
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005313} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005314
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005315PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5316 bool EndsAfter) const {
5317 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 return getTotalNumPreprocessedEntities();
5319
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005320 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5321 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5323 "Corrupted global sloc offset map");
5324
5325 if (SLocMapI->second->NumPreprocessedEntities == 0)
5326 return findNextPreprocessedEntity(SLocMapI);
5327
5328 ModuleFile &M = *SLocMapI->second;
5329 typedef const PPEntityOffset *pp_iterator;
5330 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5331 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5332
5333 size_t Count = M.NumPreprocessedEntities;
5334 size_t Half;
5335 pp_iterator First = pp_begin;
5336 pp_iterator PPI;
5337
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005338 if (EndsAfter) {
5339 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005340 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005341 } else {
5342 // Do a binary search manually instead of using std::lower_bound because
5343 // The end locations of entities may be unordered (when a macro expansion
5344 // is inside another macro argument), but for this case it is not important
5345 // whether we get the first macro expansion or its containing macro.
5346 while (Count > 0) {
5347 Half = Count / 2;
5348 PPI = First;
5349 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005350 if (SourceMgr.isBeforeInTranslationUnit(
5351 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005352 First = PPI;
5353 ++First;
5354 Count = Count - Half - 1;
5355 } else
5356 Count = Half;
5357 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 }
5359
5360 if (PPI == pp_end)
5361 return findNextPreprocessedEntity(SLocMapI);
5362
5363 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5364}
5365
Guy Benyei11169dd2012-12-18 14:30:41 +00005366/// \brief Returns a pair of [Begin, End) indices of preallocated
5367/// preprocessed entities that \arg Range encompasses.
5368std::pair<unsigned, unsigned>
5369 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5370 if (Range.isInvalid())
5371 return std::make_pair(0,0);
5372 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5373
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005374 PreprocessedEntityID BeginID =
5375 findPreprocessedEntity(Range.getBegin(), false);
5376 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 return std::make_pair(BeginID, EndID);
5378}
5379
5380/// \brief Optionally returns true or false if the preallocated preprocessed
5381/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005382Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 FileID FID) {
5384 if (FID.isInvalid())
5385 return false;
5386
5387 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5388 ModuleFile &M = *PPInfo.first;
5389 unsigned LocalIndex = PPInfo.second;
5390 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005391
Richard Smithcb34bd32016-03-27 07:28:06 +00005392 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 if (Loc.isInvalid())
5394 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005395
Guy Benyei11169dd2012-12-18 14:30:41 +00005396 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5397 return true;
5398 else
5399 return false;
5400}
5401
5402namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005403
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 /// \brief Visitor used to search for information about a header file.
5405 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005406 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005407
David Blaikie05785d12013-02-20 22:23:23 +00005408 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005409
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005411 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5412 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005413
5414 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005415 HeaderFileInfoLookupTable *Table
5416 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5417 if (!Table)
5418 return false;
5419
5420 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005421 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 if (Pos == Table->end())
5423 return false;
5424
Richard Smithbdf2d932015-07-30 03:37:16 +00005425 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 return true;
5427 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005428
David Blaikie05785d12013-02-20 22:23:23 +00005429 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005431
5432} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005433
5434HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005435 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005436 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005437 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005439
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 return HeaderFileInfo();
5441}
5442
5443void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005444 using DiagState = DiagnosticsEngine::DiagState;
5445 SmallVector<DiagState *, 32> DiagStates;
5446
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005447 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005448 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005449 auto &Record = F.PragmaDiagMappings;
5450 if (Record.empty())
5451 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005452
Richard Smithd230de22017-01-26 01:01:01 +00005453 DiagStates.clear();
5454
5455 auto ReadDiagState =
5456 [&](const DiagState &BasedOn, SourceLocation Loc,
5457 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5458 unsigned BackrefID = Record[Idx++];
5459 if (BackrefID != 0)
5460 return DiagStates[BackrefID - 1];
5461
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005463 Diag.DiagStates.push_back(BasedOn);
5464 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005465 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005466 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5467 unsigned DiagID = Record[Idx++];
5468 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005469 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005470 if (Mapping.isPragma() || IncludeNonPragmaStates)
5471 NewState->setMapping(DiagID, Mapping);
5472 }
5473 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5474 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5475 ++Idx;
5476 return NewState;
5477 };
5478
5479 auto *FirstState = ReadDiagState(
5480 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5481 SourceLocation(), F.isModule());
5482 SourceLocation CurStateLoc =
5483 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5484 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5485
5486 if (!F.isModule()) {
5487 Diag.DiagStatesByLoc.CurDiagState = CurState;
5488 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5489
5490 // Preserve the property that the imaginary root file describes the
5491 // current state.
5492 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5493 if (T.empty())
5494 T.push_back({CurState, 0});
5495 else
5496 T[0].State = CurState;
5497 }
5498
5499 while (Idx < Record.size()) {
5500 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5501 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5502 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5503 unsigned Transitions = Record[Idx++];
5504
5505 // Note that we don't need to set up Parent/ParentOffset here, because
5506 // we won't be changing the diagnostic state within imported FileIDs
5507 // (other than perhaps appending to the main source file, which has no
5508 // parent).
5509 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5510 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5511 for (unsigned I = 0; I != Transitions; ++I) {
5512 unsigned Offset = Record[Idx++];
5513 auto *State =
5514 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5515 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005516 }
5517 }
Richard Smithd230de22017-01-26 01:01:01 +00005518
5519 // Don't try to read these mappings again.
5520 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005521 }
5522}
5523
5524/// \brief Get the correct cursor and offset for loading a type.
5525ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5526 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5527 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5528 ModuleFile *M = I->second;
5529 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5530}
5531
5532/// \brief Read and return the type with the given index..
5533///
5534/// The index is the type ID, shifted and minus the number of predefs. This
5535/// routine actually reads the record corresponding to the type at the given
5536/// location. It is a helper routine for GetType, which deals with reading type
5537/// IDs.
5538QualType ASTReader::readTypeRecord(unsigned Index) {
5539 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005540 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005541
5542 // Keep track of where we are in the stream, then jump back there
5543 // after reading this type.
5544 SavedStreamPosition SavedPosition(DeclsCursor);
5545
5546 ReadingKindTracker ReadingKind(Read_Type, *this);
5547
5548 // Note that we are loading a type record.
5549 Deserializing AType(this);
5550
5551 unsigned Idx = 0;
5552 DeclsCursor.JumpToBit(Loc.Offset);
5553 RecordData Record;
5554 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005555 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005556 case TYPE_EXT_QUAL: {
5557 if (Record.size() != 2) {
5558 Error("Incorrect encoding of extended qualifier type");
5559 return QualType();
5560 }
5561 QualType Base = readType(*Loc.F, Record, Idx);
5562 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5563 return Context.getQualifiedType(Base, Quals);
5564 }
5565
5566 case TYPE_COMPLEX: {
5567 if (Record.size() != 1) {
5568 Error("Incorrect encoding of complex type");
5569 return QualType();
5570 }
5571 QualType ElemType = readType(*Loc.F, Record, Idx);
5572 return Context.getComplexType(ElemType);
5573 }
5574
5575 case TYPE_POINTER: {
5576 if (Record.size() != 1) {
5577 Error("Incorrect encoding of pointer type");
5578 return QualType();
5579 }
5580 QualType PointeeType = readType(*Loc.F, Record, Idx);
5581 return Context.getPointerType(PointeeType);
5582 }
5583
Reid Kleckner8a365022013-06-24 17:51:48 +00005584 case TYPE_DECAYED: {
5585 if (Record.size() != 1) {
5586 Error("Incorrect encoding of decayed type");
5587 return QualType();
5588 }
5589 QualType OriginalType = readType(*Loc.F, Record, Idx);
5590 QualType DT = Context.getAdjustedParameterType(OriginalType);
5591 if (!isa<DecayedType>(DT))
5592 Error("Decayed type does not decay");
5593 return DT;
5594 }
5595
Reid Kleckner0503a872013-12-05 01:23:43 +00005596 case TYPE_ADJUSTED: {
5597 if (Record.size() != 2) {
5598 Error("Incorrect encoding of adjusted type");
5599 return QualType();
5600 }
5601 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5602 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5603 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5604 }
5605
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 case TYPE_BLOCK_POINTER: {
5607 if (Record.size() != 1) {
5608 Error("Incorrect encoding of block pointer type");
5609 return QualType();
5610 }
5611 QualType PointeeType = readType(*Loc.F, Record, Idx);
5612 return Context.getBlockPointerType(PointeeType);
5613 }
5614
5615 case TYPE_LVALUE_REFERENCE: {
5616 if (Record.size() != 2) {
5617 Error("Incorrect encoding of lvalue reference type");
5618 return QualType();
5619 }
5620 QualType PointeeType = readType(*Loc.F, Record, Idx);
5621 return Context.getLValueReferenceType(PointeeType, Record[1]);
5622 }
5623
5624 case TYPE_RVALUE_REFERENCE: {
5625 if (Record.size() != 1) {
5626 Error("Incorrect encoding of rvalue reference type");
5627 return QualType();
5628 }
5629 QualType PointeeType = readType(*Loc.F, Record, Idx);
5630 return Context.getRValueReferenceType(PointeeType);
5631 }
5632
5633 case TYPE_MEMBER_POINTER: {
5634 if (Record.size() != 2) {
5635 Error("Incorrect encoding of member pointer type");
5636 return QualType();
5637 }
5638 QualType PointeeType = readType(*Loc.F, Record, Idx);
5639 QualType ClassType = readType(*Loc.F, Record, Idx);
5640 if (PointeeType.isNull() || ClassType.isNull())
5641 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005642
Guy Benyei11169dd2012-12-18 14:30:41 +00005643 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5644 }
5645
5646 case TYPE_CONSTANT_ARRAY: {
5647 QualType ElementType = readType(*Loc.F, Record, Idx);
5648 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5649 unsigned IndexTypeQuals = Record[2];
5650 unsigned Idx = 3;
5651 llvm::APInt Size = ReadAPInt(Record, Idx);
5652 return Context.getConstantArrayType(ElementType, Size,
5653 ASM, IndexTypeQuals);
5654 }
5655
5656 case TYPE_INCOMPLETE_ARRAY: {
5657 QualType ElementType = readType(*Loc.F, Record, Idx);
5658 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5659 unsigned IndexTypeQuals = Record[2];
5660 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5661 }
5662
5663 case TYPE_VARIABLE_ARRAY: {
5664 QualType ElementType = readType(*Loc.F, Record, Idx);
5665 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5666 unsigned IndexTypeQuals = Record[2];
5667 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5668 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5669 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5670 ASM, IndexTypeQuals,
5671 SourceRange(LBLoc, RBLoc));
5672 }
5673
5674 case TYPE_VECTOR: {
5675 if (Record.size() != 3) {
5676 Error("incorrect encoding of vector type in AST file");
5677 return QualType();
5678 }
5679
5680 QualType ElementType = readType(*Loc.F, Record, Idx);
5681 unsigned NumElements = Record[1];
5682 unsigned VecKind = Record[2];
5683 return Context.getVectorType(ElementType, NumElements,
5684 (VectorType::VectorKind)VecKind);
5685 }
5686
5687 case TYPE_EXT_VECTOR: {
5688 if (Record.size() != 3) {
5689 Error("incorrect encoding of extended vector type in AST file");
5690 return QualType();
5691 }
5692
5693 QualType ElementType = readType(*Loc.F, Record, Idx);
5694 unsigned NumElements = Record[1];
5695 return Context.getExtVectorType(ElementType, NumElements);
5696 }
5697
5698 case TYPE_FUNCTION_NO_PROTO: {
5699 if (Record.size() != 6) {
5700 Error("incorrect encoding of no-proto function type");
5701 return QualType();
5702 }
5703 QualType ResultType = readType(*Loc.F, Record, Idx);
5704 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5705 (CallingConv)Record[4], Record[5]);
5706 return Context.getFunctionNoProtoType(ResultType, Info);
5707 }
5708
5709 case TYPE_FUNCTION_PROTO: {
5710 QualType ResultType = readType(*Loc.F, Record, Idx);
5711
5712 FunctionProtoType::ExtProtoInfo EPI;
5713 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5714 /*hasregparm*/ Record[2],
5715 /*regparm*/ Record[3],
5716 static_cast<CallingConv>(Record[4]),
5717 /*produces*/ Record[5]);
5718
5719 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005720
5721 EPI.Variadic = Record[Idx++];
5722 EPI.HasTrailingReturn = Record[Idx++];
5723 EPI.TypeQuals = Record[Idx++];
5724 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005725 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005726 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005727
5728 unsigned NumParams = Record[Idx++];
5729 SmallVector<QualType, 16> ParamTypes;
5730 for (unsigned I = 0; I != NumParams; ++I)
5731 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5732
John McCall18afab72016-03-01 00:49:02 +00005733 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5734 if (Idx != Record.size()) {
5735 for (unsigned I = 0; I != NumParams; ++I)
5736 ExtParameterInfos.push_back(
5737 FunctionProtoType::ExtParameterInfo
5738 ::getFromOpaqueValue(Record[Idx++]));
5739 EPI.ExtParameterInfos = ExtParameterInfos.data();
5740 }
5741
5742 assert(Idx == Record.size());
5743
Jordan Rose5c382722013-03-08 21:51:21 +00005744 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005745 }
5746
5747 case TYPE_UNRESOLVED_USING: {
5748 unsigned Idx = 0;
5749 return Context.getTypeDeclType(
5750 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5751 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005752
Guy Benyei11169dd2012-12-18 14:30:41 +00005753 case TYPE_TYPEDEF: {
5754 if (Record.size() != 2) {
5755 Error("incorrect encoding of typedef type");
5756 return QualType();
5757 }
5758 unsigned Idx = 0;
5759 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5760 QualType Canonical = readType(*Loc.F, Record, Idx);
5761 if (!Canonical.isNull())
5762 Canonical = Context.getCanonicalType(Canonical);
5763 return Context.getTypedefType(Decl, Canonical);
5764 }
5765
5766 case TYPE_TYPEOF_EXPR:
5767 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5768
5769 case TYPE_TYPEOF: {
5770 if (Record.size() != 1) {
5771 Error("incorrect encoding of typeof(type) in AST file");
5772 return QualType();
5773 }
5774 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5775 return Context.getTypeOfType(UnderlyingType);
5776 }
5777
5778 case TYPE_DECLTYPE: {
5779 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5780 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5781 }
5782
5783 case TYPE_UNARY_TRANSFORM: {
5784 QualType BaseType = readType(*Loc.F, Record, Idx);
5785 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5786 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5787 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5788 }
5789
Richard Smith74aeef52013-04-26 16:15:35 +00005790 case TYPE_AUTO: {
5791 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005792 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005793 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005794 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005795 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005796
Richard Smith600b5262017-01-26 20:40:47 +00005797 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5798 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5799 QualType Deduced = readType(*Loc.F, Record, Idx);
5800 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5801 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5802 IsDependent);
5803 }
5804
Guy Benyei11169dd2012-12-18 14:30:41 +00005805 case TYPE_RECORD: {
5806 if (Record.size() != 2) {
5807 Error("incorrect encoding of record type");
5808 return QualType();
5809 }
5810 unsigned Idx = 0;
5811 bool IsDependent = Record[Idx++];
5812 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5813 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5814 QualType T = Context.getRecordType(RD);
5815 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5816 return T;
5817 }
5818
5819 case TYPE_ENUM: {
5820 if (Record.size() != 2) {
5821 Error("incorrect encoding of enum type");
5822 return QualType();
5823 }
5824 unsigned Idx = 0;
5825 bool IsDependent = Record[Idx++];
5826 QualType T
5827 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5828 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5829 return T;
5830 }
5831
5832 case TYPE_ATTRIBUTED: {
5833 if (Record.size() != 3) {
5834 Error("incorrect encoding of attributed type");
5835 return QualType();
5836 }
5837 QualType modifiedType = readType(*Loc.F, Record, Idx);
5838 QualType equivalentType = readType(*Loc.F, Record, Idx);
5839 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5840 return Context.getAttributedType(kind, modifiedType, equivalentType);
5841 }
5842
5843 case TYPE_PAREN: {
5844 if (Record.size() != 1) {
5845 Error("incorrect encoding of paren type");
5846 return QualType();
5847 }
5848 QualType InnerType = readType(*Loc.F, Record, Idx);
5849 return Context.getParenType(InnerType);
5850 }
5851
5852 case TYPE_PACK_EXPANSION: {
5853 if (Record.size() != 2) {
5854 Error("incorrect encoding of pack expansion type");
5855 return QualType();
5856 }
5857 QualType Pattern = readType(*Loc.F, Record, Idx);
5858 if (Pattern.isNull())
5859 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005860 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 if (Record[1])
5862 NumExpansions = Record[1] - 1;
5863 return Context.getPackExpansionType(Pattern, NumExpansions);
5864 }
5865
5866 case TYPE_ELABORATED: {
5867 unsigned Idx = 0;
5868 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5869 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5870 QualType NamedType = readType(*Loc.F, Record, Idx);
5871 return Context.getElaboratedType(Keyword, NNS, NamedType);
5872 }
5873
5874 case TYPE_OBJC_INTERFACE: {
5875 unsigned Idx = 0;
5876 ObjCInterfaceDecl *ItfD
5877 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5878 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5879 }
5880
Manman Rene6be26c2016-09-13 17:25:08 +00005881 case TYPE_OBJC_TYPE_PARAM: {
5882 unsigned Idx = 0;
5883 ObjCTypeParamDecl *Decl
5884 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5885 unsigned NumProtos = Record[Idx++];
5886 SmallVector<ObjCProtocolDecl*, 4> Protos;
5887 for (unsigned I = 0; I != NumProtos; ++I)
5888 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5889 return Context.getObjCTypeParamType(Decl, Protos);
5890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005891 case TYPE_OBJC_OBJECT: {
5892 unsigned Idx = 0;
5893 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005894 unsigned NumTypeArgs = Record[Idx++];
5895 SmallVector<QualType, 4> TypeArgs;
5896 for (unsigned I = 0; I != NumTypeArgs; ++I)
5897 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 unsigned NumProtos = Record[Idx++];
5899 SmallVector<ObjCProtocolDecl*, 4> Protos;
5900 for (unsigned I = 0; I != NumProtos; ++I)
5901 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005902 bool IsKindOf = Record[Idx++];
5903 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 }
5905
5906 case TYPE_OBJC_OBJECT_POINTER: {
5907 unsigned Idx = 0;
5908 QualType Pointee = readType(*Loc.F, Record, Idx);
5909 return Context.getObjCObjectPointerType(Pointee);
5910 }
5911
5912 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5913 unsigned Idx = 0;
5914 QualType Parm = readType(*Loc.F, Record, Idx);
5915 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005916 return Context.getSubstTemplateTypeParmType(
5917 cast<TemplateTypeParmType>(Parm),
5918 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005919 }
5920
5921 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5922 unsigned Idx = 0;
5923 QualType Parm = readType(*Loc.F, Record, Idx);
5924 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5925 return Context.getSubstTemplateTypeParmPackType(
5926 cast<TemplateTypeParmType>(Parm),
5927 ArgPack);
5928 }
5929
5930 case TYPE_INJECTED_CLASS_NAME: {
5931 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5932 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5933 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5934 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005935 const Type *T = nullptr;
5936 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5937 if (const Type *Existing = DI->getTypeForDecl()) {
5938 T = Existing;
5939 break;
5940 }
5941 }
5942 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005943 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005944 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5945 DI->setTypeForDecl(T);
5946 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005947 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 }
5949
5950 case TYPE_TEMPLATE_TYPE_PARM: {
5951 unsigned Idx = 0;
5952 unsigned Depth = Record[Idx++];
5953 unsigned Index = Record[Idx++];
5954 bool Pack = Record[Idx++];
5955 TemplateTypeParmDecl *D
5956 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5957 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5958 }
5959
5960 case TYPE_DEPENDENT_NAME: {
5961 unsigned Idx = 0;
5962 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5963 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005964 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 QualType Canon = readType(*Loc.F, Record, Idx);
5966 if (!Canon.isNull())
5967 Canon = Context.getCanonicalType(Canon);
5968 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5969 }
5970
5971 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5972 unsigned Idx = 0;
5973 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5974 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005975 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 unsigned NumArgs = Record[Idx++];
5977 SmallVector<TemplateArgument, 8> Args;
5978 Args.reserve(NumArgs);
5979 while (NumArgs--)
5980 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5981 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005982 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005983 }
5984
5985 case TYPE_DEPENDENT_SIZED_ARRAY: {
5986 unsigned Idx = 0;
5987
5988 // ArrayType
5989 QualType ElementType = readType(*Loc.F, Record, Idx);
5990 ArrayType::ArraySizeModifier ASM
5991 = (ArrayType::ArraySizeModifier)Record[Idx++];
5992 unsigned IndexTypeQuals = Record[Idx++];
5993
5994 // DependentSizedArrayType
5995 Expr *NumElts = ReadExpr(*Loc.F);
5996 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5997
5998 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5999 IndexTypeQuals, Brackets);
6000 }
6001
6002 case TYPE_TEMPLATE_SPECIALIZATION: {
6003 unsigned Idx = 0;
6004 bool IsDependent = Record[Idx++];
6005 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6006 SmallVector<TemplateArgument, 8> Args;
6007 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6008 QualType Underlying = readType(*Loc.F, Record, Idx);
6009 QualType T;
6010 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006011 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006013 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6015 return T;
6016 }
6017
6018 case TYPE_ATOMIC: {
6019 if (Record.size() != 1) {
6020 Error("Incorrect encoding of atomic type");
6021 return QualType();
6022 }
6023 QualType ValueType = readType(*Loc.F, Record, Idx);
6024 return Context.getAtomicType(ValueType);
6025 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006026
Joey Goulye3c85de2016-12-01 11:30:49 +00006027 case TYPE_PIPE: {
6028 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006029 Error("Incorrect encoding of pipe type");
6030 return QualType();
6031 }
6032
6033 // Reading the pipe element type.
6034 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006035 unsigned ReadOnly = Record[1];
6036 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006037 }
6038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 }
6040 llvm_unreachable("Invalid TypeCode!");
6041}
6042
Richard Smith564417a2014-03-20 21:47:22 +00006043void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6044 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006045 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006046 const RecordData &Record, unsigned &Idx) {
6047 ExceptionSpecificationType EST =
6048 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006049 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006050 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006051 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006052 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006053 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006054 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006055 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006056 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006057 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6058 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006059 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006060 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006061 }
6062}
6063
Guy Benyei11169dd2012-12-18 14:30:41 +00006064class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006065 ModuleFile *F;
6066 ASTReader *Reader;
6067 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 unsigned &Idx;
6069
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006070 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006071 return Reader->ReadSourceLocation(*F, Record, Idx);
6072 }
6073
6074 TypeSourceInfo *GetTypeSourceInfo() {
6075 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6076 }
6077
6078 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6079 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 }
6081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006083 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006085 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006086
6087 // We want compile-time assurance that we've enumerated all of
6088 // these, so unfortunately we have to declare them first, then
6089 // define them out-of-line.
6090#define ABSTRACT_TYPELOC(CLASS, PARENT)
6091#define TYPELOC(CLASS, PARENT) \
6092 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6093#include "clang/AST/TypeLocNodes.def"
6094
6095 void VisitFunctionTypeLoc(FunctionTypeLoc);
6096 void VisitArrayTypeLoc(ArrayTypeLoc);
6097};
6098
6099void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6100 // nothing to do
6101}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006102
Guy Benyei11169dd2012-12-18 14:30:41 +00006103void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006104 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006106 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6107 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6108 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6109 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006110 }
6111}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006112
Guy Benyei11169dd2012-12-18 14:30:41 +00006113void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc 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::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006118 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006119}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006120
Reid Kleckner8a365022013-06-24 17:51:48 +00006121void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6122 // nothing to do
6123}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006124
Reid Kleckner0503a872013-12-05 01:23:43 +00006125void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6126 // nothing to do
6127}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006130 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006134 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006136
Guy Benyei11169dd2012-12-18 14:30:41 +00006137void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006138 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006139}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006140
Guy Benyei11169dd2012-12-18 14:30:41 +00006141void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006142 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006143 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006144}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006145
Guy Benyei11169dd2012-12-18 14:30:41 +00006146void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006147 TL.setLBracketLoc(ReadSourceLocation());
6148 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006149 if (Record[Idx++])
6150 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 else
Craig Toppera13603a2014-05-22 05:54:18 +00006152 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006154
Guy Benyei11169dd2012-12-18 14:30:41 +00006155void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6156 VisitArrayTypeLoc(TL);
6157}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006158
Guy Benyei11169dd2012-12-18 14:30:41 +00006159void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6160 VisitArrayTypeLoc(TL);
6161}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6164 VisitArrayTypeLoc(TL);
6165}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6168 DependentSizedArrayTypeLoc TL) {
6169 VisitArrayTypeLoc(TL);
6170}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006171
Guy Benyei11169dd2012-12-18 14:30:41 +00006172void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6173 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006174 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006175}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006178 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006179}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006180
Guy Benyei11169dd2012-12-18 14:30:41 +00006181void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006182 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006184
Guy Benyei11169dd2012-12-18 14:30:41 +00006185void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006186 TL.setLocalRangeBegin(ReadSourceLocation());
6187 TL.setLParenLoc(ReadSourceLocation());
6188 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006189 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6190 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006191 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006192 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006193 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 }
6195}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006196
Guy Benyei11169dd2012-12-18 14:30:41 +00006197void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6198 VisitFunctionTypeLoc(TL);
6199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006200
Guy Benyei11169dd2012-12-18 14:30:41 +00006201void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6202 VisitFunctionTypeLoc(TL);
6203}
6204void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006205 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006206}
6207void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006208 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006209}
6210void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006211 TL.setTypeofLoc(ReadSourceLocation());
6212 TL.setLParenLoc(ReadSourceLocation());
6213 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006214}
6215void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006216 TL.setTypeofLoc(ReadSourceLocation());
6217 TL.setLParenLoc(ReadSourceLocation());
6218 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006219 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006220}
6221void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006222 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006223}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006224
Guy Benyei11169dd2012-12-18 14:30:41 +00006225void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006226 TL.setKWLoc(ReadSourceLocation());
6227 TL.setLParenLoc(ReadSourceLocation());
6228 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006229 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006230}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006231
Guy Benyei11169dd2012-12-18 14:30:41 +00006232void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006233 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006234}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006235
Richard Smith600b5262017-01-26 20:40:47 +00006236void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6237 DeducedTemplateSpecializationTypeLoc TL) {
6238 TL.setTemplateNameLoc(ReadSourceLocation());
6239}
6240
Guy Benyei11169dd2012-12-18 14:30:41 +00006241void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006242 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006243}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006244
Guy Benyei11169dd2012-12-18 14:30:41 +00006245void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006246 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006247}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006248
Guy Benyei11169dd2012-12-18 14:30:41 +00006249void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006250 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006251 if (TL.hasAttrOperand()) {
6252 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006253 range.setBegin(ReadSourceLocation());
6254 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 TL.setAttrOperandParensRange(range);
6256 }
6257 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006258 if (Record[Idx++])
6259 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006260 else
Craig Toppera13603a2014-05-22 05:54:18 +00006261 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006262 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006263 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006264}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006265
Guy Benyei11169dd2012-12-18 14:30:41 +00006266void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006267 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006268}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006269
Guy Benyei11169dd2012-12-18 14:30:41 +00006270void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6271 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006272 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006273}
6274void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6275 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006276 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006277}
6278void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6279 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006280 TL.setTemplateKeywordLoc(ReadSourceLocation());
6281 TL.setTemplateNameLoc(ReadSourceLocation());
6282 TL.setLAngleLoc(ReadSourceLocation());
6283 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006285 TL.setArgLocInfo(
6286 i,
6287 Reader->GetTemplateArgumentLocInfo(
6288 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006289}
6290void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006291 TL.setLParenLoc(ReadSourceLocation());
6292 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006293}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006294
Guy Benyei11169dd2012-12-18 14:30:41 +00006295void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006296 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006297 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006298}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006299
Guy Benyei11169dd2012-12-18 14:30:41 +00006300void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006301 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006302}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006303
Guy Benyei11169dd2012-12-18 14:30:41 +00006304void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006305 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006306 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006307 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006308}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006309
Guy Benyei11169dd2012-12-18 14:30:41 +00006310void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6311 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006312 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006313 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006314 TL.setTemplateKeywordLoc(ReadSourceLocation());
6315 TL.setTemplateNameLoc(ReadSourceLocation());
6316 TL.setLAngleLoc(ReadSourceLocation());
6317 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006319 TL.setArgLocInfo(
6320 I,
6321 Reader->GetTemplateArgumentLocInfo(
6322 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006323}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006324
Guy Benyei11169dd2012-12-18 14:30:41 +00006325void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006326 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006327}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006328
Guy Benyei11169dd2012-12-18 14:30:41 +00006329void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006330 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006331}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006332
Manman Rene6be26c2016-09-13 17:25:08 +00006333void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6334 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006335 TL.setProtocolLAngleLoc(ReadSourceLocation());
6336 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006337 }
6338 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006339 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006340}
6341
Guy Benyei11169dd2012-12-18 14:30:41 +00006342void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006343 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006344 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6345 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006346 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006347 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006348 TL.setProtocolLAngleLoc(ReadSourceLocation());
6349 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006351 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006352}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006353
Guy Benyei11169dd2012-12-18 14:30:41 +00006354void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006355 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006356}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006357
Guy Benyei11169dd2012-12-18 14:30:41 +00006358void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006359 TL.setKWLoc(ReadSourceLocation());
6360 TL.setLParenLoc(ReadSourceLocation());
6361 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006362}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006363
Xiuli Pan9c14e282016-01-09 12:53:17 +00006364void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006365 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006366}
Guy Benyei11169dd2012-12-18 14:30:41 +00006367
David L. Jonesbe1557a2016-12-21 00:17:49 +00006368TypeSourceInfo *
6369ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6370 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 QualType InfoTy = readType(F, Record, Idx);
6372 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006373 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006374
6375 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006376 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6378 TLR.Visit(TL);
6379 return TInfo;
6380}
6381
6382QualType ASTReader::GetType(TypeID ID) {
6383 unsigned FastQuals = ID & Qualifiers::FastMask;
6384 unsigned Index = ID >> Qualifiers::FastWidth;
6385
6386 if (Index < NUM_PREDEF_TYPE_IDS) {
6387 QualType T;
6388 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006389 case PREDEF_TYPE_NULL_ID:
6390 return QualType();
6391 case PREDEF_TYPE_VOID_ID:
6392 T = Context.VoidTy;
6393 break;
6394 case PREDEF_TYPE_BOOL_ID:
6395 T = Context.BoolTy;
6396 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006397
6398 case PREDEF_TYPE_CHAR_U_ID:
6399 case PREDEF_TYPE_CHAR_S_ID:
6400 // FIXME: Check that the signedness of CharTy is correct!
6401 T = Context.CharTy;
6402 break;
6403
Alexey Baderbdf7c842015-09-15 12:18:29 +00006404 case PREDEF_TYPE_UCHAR_ID:
6405 T = Context.UnsignedCharTy;
6406 break;
6407 case PREDEF_TYPE_USHORT_ID:
6408 T = Context.UnsignedShortTy;
6409 break;
6410 case PREDEF_TYPE_UINT_ID:
6411 T = Context.UnsignedIntTy;
6412 break;
6413 case PREDEF_TYPE_ULONG_ID:
6414 T = Context.UnsignedLongTy;
6415 break;
6416 case PREDEF_TYPE_ULONGLONG_ID:
6417 T = Context.UnsignedLongLongTy;
6418 break;
6419 case PREDEF_TYPE_UINT128_ID:
6420 T = Context.UnsignedInt128Ty;
6421 break;
6422 case PREDEF_TYPE_SCHAR_ID:
6423 T = Context.SignedCharTy;
6424 break;
6425 case PREDEF_TYPE_WCHAR_ID:
6426 T = Context.WCharTy;
6427 break;
6428 case PREDEF_TYPE_SHORT_ID:
6429 T = Context.ShortTy;
6430 break;
6431 case PREDEF_TYPE_INT_ID:
6432 T = Context.IntTy;
6433 break;
6434 case PREDEF_TYPE_LONG_ID:
6435 T = Context.LongTy;
6436 break;
6437 case PREDEF_TYPE_LONGLONG_ID:
6438 T = Context.LongLongTy;
6439 break;
6440 case PREDEF_TYPE_INT128_ID:
6441 T = Context.Int128Ty;
6442 break;
6443 case PREDEF_TYPE_HALF_ID:
6444 T = Context.HalfTy;
6445 break;
6446 case PREDEF_TYPE_FLOAT_ID:
6447 T = Context.FloatTy;
6448 break;
6449 case PREDEF_TYPE_DOUBLE_ID:
6450 T = Context.DoubleTy;
6451 break;
6452 case PREDEF_TYPE_LONGDOUBLE_ID:
6453 T = Context.LongDoubleTy;
6454 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006455 case PREDEF_TYPE_FLOAT128_ID:
6456 T = Context.Float128Ty;
6457 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006458 case PREDEF_TYPE_OVERLOAD_ID:
6459 T = Context.OverloadTy;
6460 break;
6461 case PREDEF_TYPE_BOUND_MEMBER:
6462 T = Context.BoundMemberTy;
6463 break;
6464 case PREDEF_TYPE_PSEUDO_OBJECT:
6465 T = Context.PseudoObjectTy;
6466 break;
6467 case PREDEF_TYPE_DEPENDENT_ID:
6468 T = Context.DependentTy;
6469 break;
6470 case PREDEF_TYPE_UNKNOWN_ANY:
6471 T = Context.UnknownAnyTy;
6472 break;
6473 case PREDEF_TYPE_NULLPTR_ID:
6474 T = Context.NullPtrTy;
6475 break;
6476 case PREDEF_TYPE_CHAR16_ID:
6477 T = Context.Char16Ty;
6478 break;
6479 case PREDEF_TYPE_CHAR32_ID:
6480 T = Context.Char32Ty;
6481 break;
6482 case PREDEF_TYPE_OBJC_ID:
6483 T = Context.ObjCBuiltinIdTy;
6484 break;
6485 case PREDEF_TYPE_OBJC_CLASS:
6486 T = Context.ObjCBuiltinClassTy;
6487 break;
6488 case PREDEF_TYPE_OBJC_SEL:
6489 T = Context.ObjCBuiltinSelTy;
6490 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006491#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6492 case PREDEF_TYPE_##Id##_ID: \
6493 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006494 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006495#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006496 case PREDEF_TYPE_SAMPLER_ID:
6497 T = Context.OCLSamplerTy;
6498 break;
6499 case PREDEF_TYPE_EVENT_ID:
6500 T = Context.OCLEventTy;
6501 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006502 case PREDEF_TYPE_CLK_EVENT_ID:
6503 T = Context.OCLClkEventTy;
6504 break;
6505 case PREDEF_TYPE_QUEUE_ID:
6506 T = Context.OCLQueueTy;
6507 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006508 case PREDEF_TYPE_RESERVE_ID_ID:
6509 T = Context.OCLReserveIDTy;
6510 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006511 case PREDEF_TYPE_AUTO_DEDUCT:
6512 T = Context.getAutoDeductType();
6513 break;
6514
6515 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6516 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 break;
6518
6519 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6520 T = Context.ARCUnbridgedCastTy;
6521 break;
6522
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 case PREDEF_TYPE_BUILTIN_FN:
6524 T = Context.BuiltinFnTy;
6525 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006526
6527 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6528 T = Context.OMPArraySectionTy;
6529 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 }
6531
6532 assert(!T.isNull() && "Unknown predefined type");
6533 return T.withFastQualifiers(FastQuals);
6534 }
6535
6536 Index -= NUM_PREDEF_TYPE_IDS;
6537 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6538 if (TypesLoaded[Index].isNull()) {
6539 TypesLoaded[Index] = readTypeRecord(Index);
6540 if (TypesLoaded[Index].isNull())
6541 return QualType();
6542
6543 TypesLoaded[Index]->setFromAST();
6544 if (DeserializationListener)
6545 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6546 TypesLoaded[Index]);
6547 }
6548
6549 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6550}
6551
6552QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6553 return GetType(getGlobalTypeID(F, LocalID));
6554}
6555
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006556serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006557ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6558 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6559 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006560
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6562 return LocalID;
6563
Richard Smith37a93df2017-02-18 00:32:02 +00006564 if (!F.ModuleOffsetMap.empty())
6565 ReadModuleOffsetMap(F);
6566
Guy Benyei11169dd2012-12-18 14:30:41 +00006567 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6568 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6569 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006570
Guy Benyei11169dd2012-12-18 14:30:41 +00006571 unsigned GlobalIndex = LocalIndex + I->second;
6572 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6573}
6574
6575TemplateArgumentLocInfo
6576ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6577 TemplateArgument::ArgKind Kind,
6578 const RecordData &Record,
6579 unsigned &Index) {
6580 switch (Kind) {
6581 case TemplateArgument::Expression:
6582 return ReadExpr(F);
6583 case TemplateArgument::Type:
6584 return GetTypeSourceInfo(F, Record, Index);
6585 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006586 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 Index);
6588 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6589 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6590 SourceLocation());
6591 }
6592 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006593 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 Index);
6595 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6596 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006597 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 EllipsisLoc);
6599 }
6600 case TemplateArgument::Null:
6601 case TemplateArgument::Integral:
6602 case TemplateArgument::Declaration:
6603 case TemplateArgument::NullPtr:
6604 case TemplateArgument::Pack:
6605 // FIXME: Is this right?
6606 return TemplateArgumentLocInfo();
6607 }
6608 llvm_unreachable("unexpected template argument loc");
6609}
6610
6611TemplateArgumentLoc
6612ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6613 const RecordData &Record, unsigned &Index) {
6614 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6615
6616 if (Arg.getKind() == TemplateArgument::Expression) {
6617 if (Record[Index++]) // bool InfoHasSameExpr.
6618 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6619 }
6620 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6621 Record, Index));
6622}
6623
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006624const ASTTemplateArgumentListInfo*
6625ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6626 const RecordData &Record,
6627 unsigned &Index) {
6628 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6629 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6630 unsigned NumArgsAsWritten = Record[Index++];
6631 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6632 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6633 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6634 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6635}
6636
Guy Benyei11169dd2012-12-18 14:30:41 +00006637Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6638 return GetDecl(ID);
6639}
6640
Richard Smith053f6c62014-05-16 23:01:30 +00006641void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006642 if (NumCurrentElementsDeserializing) {
6643 // We arrange to not care about the complete redeclaration chain while we're
6644 // deserializing. Just remember that the AST has marked this one as complete
6645 // but that it's not actually complete yet, so we know we still need to
6646 // complete it later.
6647 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6648 return;
6649 }
6650
Richard Smith053f6c62014-05-16 23:01:30 +00006651 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6652
Richard Smith053f6c62014-05-16 23:01:30 +00006653 // If this is a named declaration, complete it by looking it up
6654 // within its context.
6655 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006656 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006657 // all mergeable entities within it.
6658 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6659 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6660 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006661 if (!getContext().getLangOpts().CPlusPlus &&
6662 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006663 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006664 // the identifier instead. (For C++ modules, we don't store decls
6665 // in the serialized identifier table, so we do the lookup in the TU.)
6666 auto *II = Name.getAsIdentifierInfo();
6667 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006668 if (II->isOutOfDate())
6669 updateOutOfDateIdentifier(*II);
6670 } else
6671 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006672 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006673 // Find all declarations of this kind from the relevant context.
6674 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6675 auto *DC = cast<DeclContext>(DCDecl);
6676 SmallVector<Decl*, 8> Decls;
6677 FindExternalLexicalDecls(
6678 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6679 }
Richard Smith053f6c62014-05-16 23:01:30 +00006680 }
6681 }
Richard Smith50895422015-01-31 03:04:55 +00006682
6683 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6684 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6685 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6686 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6687 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6688 if (auto *Template = FD->getPrimaryTemplate())
6689 Template->LoadLazySpecializations();
6690 }
Richard Smith053f6c62014-05-16 23:01:30 +00006691}
6692
Richard Smithc2bb8182015-03-24 06:36:48 +00006693CXXCtorInitializer **
6694ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6695 RecordLocation Loc = getLocalBitOffset(Offset);
6696 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6697 SavedStreamPosition SavedPosition(Cursor);
6698 Cursor.JumpToBit(Loc.Offset);
6699 ReadingKindTracker ReadingKind(Read_Decl, *this);
6700
6701 RecordData Record;
6702 unsigned Code = Cursor.ReadCode();
6703 unsigned RecCode = Cursor.readRecord(Code, Record);
6704 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6705 Error("malformed AST file: missing C++ ctor initializers");
6706 return nullptr;
6707 }
6708
6709 unsigned Idx = 0;
6710 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6711}
6712
Guy Benyei11169dd2012-12-18 14:30:41 +00006713CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6714 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006715 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 SavedStreamPosition SavedPosition(Cursor);
6717 Cursor.JumpToBit(Loc.Offset);
6718 ReadingKindTracker ReadingKind(Read_Decl, *this);
6719 RecordData Record;
6720 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006721 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006722 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006723 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006724 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
6726
6727 unsigned Idx = 0;
6728 unsigned NumBases = Record[Idx++];
6729 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6730 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6731 for (unsigned I = 0; I != NumBases; ++I)
6732 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6733 return Bases;
6734}
6735
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006736serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006737ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6738 if (LocalID < NUM_PREDEF_DECL_IDS)
6739 return LocalID;
6740
Richard Smith37a93df2017-02-18 00:32:02 +00006741 if (!F.ModuleOffsetMap.empty())
6742 ReadModuleOffsetMap(F);
6743
Guy Benyei11169dd2012-12-18 14:30:41 +00006744 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6745 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6746 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006747
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 return LocalID + I->second;
6749}
6750
6751bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6752 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006753 // Predefined decls aren't from any module.
6754 if (ID < NUM_PREDEF_DECL_IDS)
6755 return false;
6756
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006757 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006758 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006759}
6760
Douglas Gregor9f782892013-01-21 15:25:38 +00006761ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006763 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6765 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6766 return I->second;
6767}
6768
6769SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6770 if (ID < NUM_PREDEF_DECL_IDS)
6771 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006772
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6774
6775 if (Index > DeclsLoaded.size()) {
6776 Error("declaration ID out-of-range for AST file");
6777 return SourceLocation();
6778 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006779
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 if (Decl *D = DeclsLoaded[Index])
6781 return D->getLocation();
6782
Richard Smithcb34bd32016-03-27 07:28:06 +00006783 SourceLocation Loc;
6784 DeclCursorForID(ID, Loc);
6785 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006786}
6787
Richard Smithfe620d22015-03-05 23:24:12 +00006788static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6789 switch (ID) {
6790 case PREDEF_DECL_NULL_ID:
6791 return nullptr;
6792
6793 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6794 return Context.getTranslationUnitDecl();
6795
6796 case PREDEF_DECL_OBJC_ID_ID:
6797 return Context.getObjCIdDecl();
6798
6799 case PREDEF_DECL_OBJC_SEL_ID:
6800 return Context.getObjCSelDecl();
6801
6802 case PREDEF_DECL_OBJC_CLASS_ID:
6803 return Context.getObjCClassDecl();
6804
6805 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6806 return Context.getObjCProtocolDecl();
6807
6808 case PREDEF_DECL_INT_128_ID:
6809 return Context.getInt128Decl();
6810
6811 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6812 return Context.getUInt128Decl();
6813
6814 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6815 return Context.getObjCInstanceTypeDecl();
6816
6817 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6818 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006819
Richard Smith9b88a4c2015-07-27 05:40:23 +00006820 case PREDEF_DECL_VA_LIST_TAG:
6821 return Context.getVaListTagDecl();
6822
Charles Davisc7d5c942015-09-17 20:55:33 +00006823 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6824 return Context.getBuiltinMSVaListDecl();
6825
Richard Smithf19e1272015-03-07 00:04:49 +00006826 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6827 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006828
6829 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6830 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006831
6832 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6833 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006834
6835 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6836 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006837
6838 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6839 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006840 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006841 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006842}
6843
Richard Smithcd45dbc2014-04-19 03:48:30 +00006844Decl *ASTReader::GetExistingDecl(DeclID ID) {
6845 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006846 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6847 if (D) {
6848 // Track that we have merged the declaration with ID \p ID into the
6849 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006850 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006851 if (Merged.empty())
6852 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006853 }
Richard Smithfe620d22015-03-05 23:24:12 +00006854 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006856
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6858
6859 if (Index >= DeclsLoaded.size()) {
6860 assert(0 && "declaration ID out-of-range for AST file");
6861 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006862 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006863 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006864
6865 return DeclsLoaded[Index];
6866}
6867
6868Decl *ASTReader::GetDecl(DeclID ID) {
6869 if (ID < NUM_PREDEF_DECL_IDS)
6870 return GetExistingDecl(ID);
6871
6872 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6873
6874 if (Index >= DeclsLoaded.size()) {
6875 assert(0 && "declaration ID out-of-range for AST file");
6876 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006877 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006878 }
6879
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 if (!DeclsLoaded[Index]) {
6881 ReadDeclRecord(ID);
6882 if (DeserializationListener)
6883 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6884 }
6885
6886 return DeclsLoaded[Index];
6887}
6888
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006889DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 DeclID GlobalID) {
6891 if (GlobalID < NUM_PREDEF_DECL_IDS)
6892 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006893
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6895 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6896 ModuleFile *Owner = I->second;
6897
6898 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6899 = M.GlobalToLocalDeclIDs.find(Owner);
6900 if (Pos == M.GlobalToLocalDeclIDs.end())
6901 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006902
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 return GlobalID - Owner->BaseDeclID + Pos->second;
6904}
6905
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006906serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 const RecordData &Record,
6908 unsigned &Idx) {
6909 if (Idx >= Record.size()) {
6910 Error("Corrupted AST file");
6911 return 0;
6912 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006913
Guy Benyei11169dd2012-12-18 14:30:41 +00006914 return getGlobalDeclID(F, Record[Idx++]);
6915}
6916
6917/// \brief Resolve the offset of a statement into a statement.
6918///
6919/// This operation will read a new statement from the external
6920/// source each time it is called, and is meant to be used via a
6921/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6922Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6923 // Switch case IDs are per Decl.
6924 ClearSwitchCaseIDs();
6925
6926 // Offset here is a global offset across the entire chain.
6927 RecordLocation Loc = getLocalBitOffset(Offset);
6928 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00006929 assert(NumCurrentElementsDeserializing == 0 &&
6930 "should not be called while already deserializing");
6931 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 return ReadStmtFromStream(*Loc.F);
6933}
6934
Richard Smith3cb15722015-08-05 22:41:45 +00006935void ASTReader::FindExternalLexicalDecls(
6936 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6937 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006938 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6939
Richard Smith9ccdd932015-08-06 22:14:12 +00006940 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006941 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6942 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6943 auto K = (Decl::Kind)+LexicalDecls[I];
6944 if (!IsKindWeWant(K))
6945 continue;
6946
6947 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6948
6949 // Don't add predefined declarations to the lexical context more
6950 // than once.
6951 if (ID < NUM_PREDEF_DECL_IDS) {
6952 if (PredefsVisited[ID])
6953 continue;
6954
6955 PredefsVisited[ID] = true;
6956 }
6957
6958 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006959 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006960 if (!DC->isDeclInLexicalTraversal(D))
6961 Decls.push_back(D);
6962 }
6963 }
6964 };
6965
6966 if (isa<TranslationUnitDecl>(DC)) {
6967 for (auto Lexical : TULexicalDecls)
6968 Visit(Lexical.first, Lexical.second);
6969 } else {
6970 auto I = LexicalDecls.find(DC);
6971 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006972 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006973 }
6974
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006976}
6977
6978namespace {
6979
6980class DeclIDComp {
6981 ASTReader &Reader;
6982 ModuleFile &Mod;
6983
6984public:
6985 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6986
6987 bool operator()(LocalDeclID L, LocalDeclID R) const {
6988 SourceLocation LHS = getLocation(L);
6989 SourceLocation RHS = getLocation(R);
6990 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6991 }
6992
6993 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6994 SourceLocation RHS = getLocation(R);
6995 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6996 }
6997
6998 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6999 SourceLocation LHS = getLocation(L);
7000 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7001 }
7002
7003 SourceLocation getLocation(LocalDeclID ID) const {
7004 return Reader.getSourceManager().getFileLoc(
7005 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7006 }
7007};
7008
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007009} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007010
7011void ASTReader::FindFileRegionDecls(FileID File,
7012 unsigned Offset, unsigned Length,
7013 SmallVectorImpl<Decl *> &Decls) {
7014 SourceManager &SM = getSourceManager();
7015
7016 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7017 if (I == FileDeclIDs.end())
7018 return;
7019
7020 FileDeclsInfo &DInfo = I->second;
7021 if (DInfo.Decls.empty())
7022 return;
7023
7024 SourceLocation
7025 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7026 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7027
7028 DeclIDComp DIDComp(*this, *DInfo.Mod);
7029 ArrayRef<serialization::LocalDeclID>::iterator
7030 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7031 BeginLoc, DIDComp);
7032 if (BeginIt != DInfo.Decls.begin())
7033 --BeginIt;
7034
7035 // If we are pointing at a top-level decl inside an objc container, we need
7036 // to backtrack until we find it otherwise we will fail to report that the
7037 // region overlaps with an objc container.
7038 while (BeginIt != DInfo.Decls.begin() &&
7039 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7040 ->isTopLevelDeclInObjCContainer())
7041 --BeginIt;
7042
7043 ArrayRef<serialization::LocalDeclID>::iterator
7044 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7045 EndLoc, DIDComp);
7046 if (EndIt != DInfo.Decls.end())
7047 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007048
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 for (ArrayRef<serialization::LocalDeclID>::iterator
7050 DIt = BeginIt; DIt != EndIt; ++DIt)
7051 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7052}
7053
Richard Smith9ce12e32013-02-07 03:30:24 +00007054bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007055ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7056 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007057 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007058 "DeclContext has no visible decls in storage");
7059 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007060 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007061
Richard Smithd88a7f12015-09-01 20:35:42 +00007062 auto It = Lookups.find(DC);
7063 if (It == Lookups.end())
7064 return false;
7065
Richard Smith8c913ec2014-08-14 02:21:01 +00007066 Deserializing LookupResults(this);
7067
Richard Smithd88a7f12015-09-01 20:35:42 +00007068 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007069 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007070 for (DeclID ID : It->second.Table.find(Name)) {
7071 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7072 if (ND->getDeclName() == Name)
7073 Decls.push_back(ND);
7074 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007075
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 ++NumVisibleDeclContextsRead;
7077 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007078 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007079}
7080
Guy Benyei11169dd2012-12-18 14:30:41 +00007081void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7082 if (!DC->hasExternalVisibleStorage())
7083 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007084
7085 auto It = Lookups.find(DC);
7086 assert(It != Lookups.end() &&
7087 "have external visible storage but no lookup tables");
7088
Craig Topper79be4cd2013-07-05 04:33:53 +00007089 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007090
Richard Smithd88a7f12015-09-01 20:35:42 +00007091 for (DeclID ID : It->second.Table.findAll()) {
7092 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7093 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 }
7095
Guy Benyei11169dd2012-12-18 14:30:41 +00007096 ++NumVisibleDeclContextsRead;
7097
Craig Topper79be4cd2013-07-05 04:33:53 +00007098 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7100 }
7101 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7102}
7103
Richard Smithd88a7f12015-09-01 20:35:42 +00007104const serialization::reader::DeclContextLookupTable *
7105ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7106 auto I = Lookups.find(Primary);
7107 return I == Lookups.end() ? nullptr : &I->second;
7108}
7109
Guy Benyei11169dd2012-12-18 14:30:41 +00007110/// \brief Under non-PCH compilation the consumer receives the objc methods
7111/// before receiving the implementation, and codegen depends on this.
7112/// We simulate this by deserializing and passing to consumer the methods of the
7113/// implementation before passing the deserialized implementation decl.
7114static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7115 ASTConsumer *Consumer) {
7116 assert(ImplD && Consumer);
7117
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007118 for (auto *I : ImplD->methods())
7119 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007120
7121 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7122}
7123
7124void ASTReader::PassInterestingDeclsToConsumer() {
7125 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00007126
7127 if (PassingDeclsToConsumer)
7128 return;
7129
7130 // Guard variable to avoid recursively redoing the process of passing
7131 // decls to consumer.
7132 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7133 true);
7134
Richard Smith9e2341d2015-03-23 03:25:59 +00007135 // Ensure that we've loaded all potentially-interesting declarations
7136 // that need to be eagerly loaded.
7137 for (auto ID : EagerlyDeserializedDecls)
7138 GetDecl(ID);
7139 EagerlyDeserializedDecls.clear();
7140
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 while (!InterestingDecls.empty()) {
7142 Decl *D = InterestingDecls.front();
7143 InterestingDecls.pop_front();
7144
7145 PassInterestingDeclToConsumer(D);
7146 }
7147}
7148
7149void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7150 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7151 PassObjCImplDeclToConsumer(ImplD, Consumer);
7152 else
7153 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7154}
7155
7156void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7157 this->Consumer = Consumer;
7158
Richard Smith9e2341d2015-03-23 03:25:59 +00007159 if (Consumer)
7160 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007161
7162 if (DeserializationListener)
7163 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007164}
7165
7166void ASTReader::PrintStats() {
7167 std::fprintf(stderr, "*** AST File Statistics:\n");
7168
7169 unsigned NumTypesLoaded
7170 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7171 QualType());
7172 unsigned NumDeclsLoaded
7173 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007174 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 unsigned NumIdentifiersLoaded
7176 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7177 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007178 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 unsigned NumMacrosLoaded
7180 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7181 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007182 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 unsigned NumSelectorsLoaded
7184 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7185 SelectorsLoaded.end(),
7186 Selector());
7187
7188 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7189 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7190 NumSLocEntriesRead, TotalNumSLocEntries,
7191 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7192 if (!TypesLoaded.empty())
7193 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7194 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7195 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7196 if (!DeclsLoaded.empty())
7197 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7198 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7199 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7200 if (!IdentifiersLoaded.empty())
7201 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7202 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7203 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7204 if (!MacrosLoaded.empty())
7205 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7206 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7207 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7208 if (!SelectorsLoaded.empty())
7209 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7210 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7211 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7212 if (TotalNumStatements)
7213 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7214 NumStatementsRead, TotalNumStatements,
7215 ((float)NumStatementsRead/TotalNumStatements * 100));
7216 if (TotalNumMacros)
7217 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7218 NumMacrosRead, TotalNumMacros,
7219 ((float)NumMacrosRead/TotalNumMacros * 100));
7220 if (TotalLexicalDeclContexts)
7221 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7222 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7223 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7224 * 100));
7225 if (TotalVisibleDeclContexts)
7226 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7227 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7228 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7229 * 100));
7230 if (TotalNumMethodPoolEntries) {
7231 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7232 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7233 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7234 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007236 if (NumMethodPoolLookups) {
7237 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7238 NumMethodPoolHits, NumMethodPoolLookups,
7239 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7240 }
7241 if (NumMethodPoolTableLookups) {
7242 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7243 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7244 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7245 * 100.0));
7246 }
7247
Douglas Gregor00a50f72013-01-25 00:38:33 +00007248 if (NumIdentifierLookupHits) {
7249 std::fprintf(stderr,
7250 " %u / %u identifier table lookups succeeded (%f%%)\n",
7251 NumIdentifierLookupHits, NumIdentifierLookups,
7252 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7253 }
7254
Douglas Gregore060e572013-01-25 01:03:03 +00007255 if (GlobalIndex) {
7256 std::fprintf(stderr, "\n");
7257 GlobalIndex->printStats();
7258 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007259
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 std::fprintf(stderr, "\n");
7261 dump();
7262 std::fprintf(stderr, "\n");
7263}
7264
7265template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007266LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007267dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007268 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 InitialCapacity> &Map) {
7270 if (Map.begin() == Map.end())
7271 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007272
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7274 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007275 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 I != IEnd; ++I) {
7277 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7278 << "\n";
7279 }
7280}
7281
Yaron Kerencdae9412016-01-29 19:38:18 +00007282LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7284 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7285 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7286 dumpModuleIDMap("Global type map", GlobalTypeMap);
7287 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7288 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7289 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7290 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7291 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007292 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007294
Guy Benyei11169dd2012-12-18 14:30:41 +00007295 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007296 for (ModuleFile &M : ModuleMgr)
7297 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007298}
7299
7300/// Return the amount of memory used by memory buffers, breaking down
7301/// by heap-backed versus mmap'ed memory.
7302void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007303 for (ModuleFile &I : ModuleMgr) {
7304 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007305 size_t bytes = buf->getBufferSize();
7306 switch (buf->getBufferKind()) {
7307 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7308 sizes.malloc_bytes += bytes;
7309 break;
7310 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7311 sizes.mmap_bytes += bytes;
7312 break;
7313 }
7314 }
7315 }
7316}
7317
7318void ASTReader::InitializeSema(Sema &S) {
7319 SemaObj = &S;
7320 S.addExternalSource(this);
7321
7322 // Makes sure any declarations that were deserialized "too early"
7323 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007324 for (uint64_t ID : PreloadedDeclIDs) {
7325 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7326 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007328 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007329
Richard Smith3d8e97e2013-10-18 06:54:39 +00007330 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 if (!FPPragmaOptions.empty()) {
7332 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7333 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7334 }
7335
Yaxun Liu5b746652016-12-18 05:18:55 +00007336 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7337 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7338 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007339
7340 UpdateSema();
7341}
7342
7343void ASTReader::UpdateSema() {
7344 assert(SemaObj && "no Sema to update");
7345
7346 // Load the offsets of the declarations that Sema references.
7347 // They will be lazily deserialized when needed.
7348 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007349 assert(SemaDeclRefs.size() % 3 == 0);
7350 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007351 if (!SemaObj->StdNamespace)
7352 SemaObj->StdNamespace = SemaDeclRefs[I];
7353 if (!SemaObj->StdBadAlloc)
7354 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007355 if (!SemaObj->StdAlignValT)
7356 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007357 }
7358 SemaDeclRefs.clear();
7359 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007360
Nico Weber779355f2016-03-02 23:22:00 +00007361 // Update the state of pragmas. Use the same API as if we had encountered the
7362 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007363 if(OptimizeOffPragmaLocation.isValid())
7364 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007365 if (PragmaMSStructState != -1)
7366 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007367 if (PointersToMembersPragmaLocation.isValid()) {
7368 SemaObj->ActOnPragmaMSPointersToMembers(
7369 (LangOptions::PragmaMSPointersToMembersKind)
7370 PragmaMSPointersToMembersState,
7371 PointersToMembersPragmaLocation);
7372 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007373 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007374}
7375
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007376IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 // Note that we are loading an identifier.
7378 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007379
Douglas Gregor7211ac12013-01-25 23:32:03 +00007380 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007381 NumIdentifierLookups,
7382 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007383
7384 // We don't need to do identifier table lookups in C++ modules (we preload
7385 // all interesting declarations, and don't need to use the scope for name
7386 // lookups). Perform the lookup in PCH files, though, since we don't build
7387 // a complete initial identifier table if we're carrying on from a PCH.
7388 if (Context.getLangOpts().CPlusPlus) {
7389 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007390 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007391 break;
7392 } else {
7393 // If there is a global index, look there first to determine which modules
7394 // provably do not have any results for this identifier.
7395 GlobalModuleIndex::HitSet Hits;
7396 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7397 if (!loadGlobalIndex()) {
7398 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7399 HitsPtr = &Hits;
7400 }
7401 }
7402
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007403 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007404 }
7405
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 IdentifierInfo *II = Visitor.getIdentifierInfo();
7407 markIdentifierUpToDate(II);
7408 return II;
7409}
7410
7411namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007412
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 /// \brief An identifier-lookup iterator that enumerates all of the
7414 /// identifiers stored within a set of AST files.
7415 class ASTIdentifierIterator : public IdentifierIterator {
7416 /// \brief The AST reader whose identifiers are being enumerated.
7417 const ASTReader &Reader;
7418
7419 /// \brief The current index into the chain of AST files stored in
7420 /// the AST reader.
7421 unsigned Index;
7422
7423 /// \brief The current position within the identifier lookup table
7424 /// of the current AST file.
7425 ASTIdentifierLookupTable::key_iterator Current;
7426
7427 /// \brief The end position within the identifier lookup table of
7428 /// the current AST file.
7429 ASTIdentifierLookupTable::key_iterator End;
7430
Ben Langmuir537c5b52016-05-04 00:53:13 +00007431 /// \brief Whether to skip any modules in the ASTReader.
7432 bool SkipModules;
7433
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007435 explicit ASTIdentifierIterator(const ASTReader &Reader,
7436 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007437
Craig Topper3e89dfe2014-03-13 02:13:41 +00007438 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007440
7441} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007442
Ben Langmuir537c5b52016-05-04 00:53:13 +00007443ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7444 bool SkipModules)
7445 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446}
7447
7448StringRef ASTIdentifierIterator::Next() {
7449 while (Current == End) {
7450 // If we have exhausted all of our AST files, we're done.
7451 if (Index == 0)
7452 return StringRef();
7453
7454 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007455 ModuleFile &F = Reader.ModuleMgr[Index];
7456 if (SkipModules && F.isModule())
7457 continue;
7458
7459 ASTIdentifierLookupTable *IdTable =
7460 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007461 Current = IdTable->key_begin();
7462 End = IdTable->key_end();
7463 }
7464
7465 // We have any identifiers remaining in the current AST file; return
7466 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007467 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007468 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007469 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007470}
7471
Ben Langmuir537c5b52016-05-04 00:53:13 +00007472namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007473
Ben Langmuir537c5b52016-05-04 00:53:13 +00007474/// A utility for appending two IdentifierIterators.
7475class ChainedIdentifierIterator : public IdentifierIterator {
7476 std::unique_ptr<IdentifierIterator> Current;
7477 std::unique_ptr<IdentifierIterator> Queued;
7478
7479public:
7480 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7481 std::unique_ptr<IdentifierIterator> Second)
7482 : Current(std::move(First)), Queued(std::move(Second)) {}
7483
7484 StringRef Next() override {
7485 if (!Current)
7486 return StringRef();
7487
7488 StringRef result = Current->Next();
7489 if (!result.empty())
7490 return result;
7491
7492 // Try the queued iterator, which may itself be empty.
7493 Current.reset();
7494 std::swap(Current, Queued);
7495 return Next();
7496 }
7497};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007498
Ben Langmuir537c5b52016-05-04 00:53:13 +00007499} // end anonymous namespace.
7500
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007501IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007502 if (!loadGlobalIndex()) {
7503 std::unique_ptr<IdentifierIterator> ReaderIter(
7504 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7505 std::unique_ptr<IdentifierIterator> ModulesIter(
7506 GlobalIndex->createIdentifierIterator());
7507 return new ChainedIdentifierIterator(std::move(ReaderIter),
7508 std::move(ModulesIter));
7509 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007510
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 return new ASTIdentifierIterator(*this);
7512}
7513
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007514namespace clang {
7515namespace serialization {
7516
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 class ReadMethodPoolVisitor {
7518 ASTReader &Reader;
7519 Selector Sel;
7520 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007521 unsigned InstanceBits;
7522 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007523 bool InstanceHasMoreThanOneDecl;
7524 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007525 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7526 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007527
7528 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007529 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007530 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007531 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007532 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7533 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007534
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007535 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007536 if (!M.SelectorLookupTable)
7537 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007538
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007540 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 return true;
7542
Richard Smithbdf2d932015-07-30 03:37:16 +00007543 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007544 ASTSelectorLookupTable *PoolTable
7545 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007546 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 if (Pos == PoolTable->end())
7548 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007549
Richard Smithbdf2d932015-07-30 03:37:16 +00007550 ++Reader.NumMethodPoolTableHits;
7551 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007552 // FIXME: Not quite happy with the statistics here. We probably should
7553 // disable this tracking when called via LoadSelector.
7554 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007555 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007557 if (Reader.DeserializationListener)
7558 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007559
Richard Smithbdf2d932015-07-30 03:37:16 +00007560 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7561 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7562 InstanceBits = Data.InstanceBits;
7563 FactoryBits = Data.FactoryBits;
7564 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7565 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007566 return true;
7567 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007568
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007570 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7571 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 }
7573
7574 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007575 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007576 return FactoryMethods;
7577 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007578
7579 unsigned getInstanceBits() const { return InstanceBits; }
7580 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007581 bool instanceHasMoreThanOneDecl() const {
7582 return InstanceHasMoreThanOneDecl;
7583 }
7584 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007586
7587} // end namespace serialization
7588} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007589
7590/// \brief Add the given set of methods to the method list.
7591static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7592 ObjCMethodList &List) {
7593 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7594 S.addMethodToGlobalList(&List, Methods[I]);
7595 }
7596}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007597
Guy Benyei11169dd2012-12-18 14:30:41 +00007598void ASTReader::ReadMethodPool(Selector Sel) {
7599 // Get the selector generation and update it to the current generation.
7600 unsigned &Generation = SelectorGeneration[Sel];
7601 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007602 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007603 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007604
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007606 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007608 ModuleMgr.visit(Visitor);
7609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007611 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007613
7614 ++NumMethodPoolHits;
7615
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 if (!getSema())
7617 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007618
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 Sema &S = *getSema();
7620 Sema::GlobalMethodPool::iterator Pos
7621 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007622
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007623 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007624 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007625 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007626 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007627
7628 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7629 // when building a module we keep every method individually and may need to
7630 // update hasMoreThanOneDecl as we add the methods.
7631 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7632 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007633}
7634
Manman Rena0f31a02016-04-29 19:04:05 +00007635void ASTReader::updateOutOfDateSelector(Selector Sel) {
7636 if (SelectorOutOfDate[Sel])
7637 ReadMethodPool(Sel);
7638}
7639
Guy Benyei11169dd2012-12-18 14:30:41 +00007640void ASTReader::ReadKnownNamespaces(
7641 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7642 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007643
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007645 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7647 Namespaces.push_back(Namespace);
7648 }
7649}
7650
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007651void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007652 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007653 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7654 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007655 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007656 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007657 Undefined.insert(std::make_pair(D, Loc));
7658 }
7659}
Nick Lewycky8334af82013-01-26 00:35:08 +00007660
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007661void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7662 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7663 Exprs) {
7664 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7665 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7666 uint64_t Count = DelayedDeleteExprs[Idx++];
7667 for (uint64_t C = 0; C < Count; ++C) {
7668 SourceLocation DeleteLoc =
7669 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7670 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7671 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7672 }
7673 }
7674}
7675
Guy Benyei11169dd2012-12-18 14:30:41 +00007676void ASTReader::ReadTentativeDefinitions(
7677 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7678 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7679 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7680 if (Var)
7681 TentativeDefs.push_back(Var);
7682 }
7683 TentativeDefinitions.clear();
7684}
7685
7686void ASTReader::ReadUnusedFileScopedDecls(
7687 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7688 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7689 DeclaratorDecl *D
7690 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7691 if (D)
7692 Decls.push_back(D);
7693 }
7694 UnusedFileScopedDecls.clear();
7695}
7696
7697void ASTReader::ReadDelegatingConstructors(
7698 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7699 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7700 CXXConstructorDecl *D
7701 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7702 if (D)
7703 Decls.push_back(D);
7704 }
7705 DelegatingCtorDecls.clear();
7706}
7707
7708void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7709 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7710 TypedefNameDecl *D
7711 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7712 if (D)
7713 Decls.push_back(D);
7714 }
7715 ExtVectorDecls.clear();
7716}
7717
Nico Weber72889432014-09-06 01:25:55 +00007718void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7719 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7720 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7721 ++I) {
7722 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7723 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7724 if (D)
7725 Decls.insert(D);
7726 }
7727 UnusedLocalTypedefNameCandidates.clear();
7728}
7729
Guy Benyei11169dd2012-12-18 14:30:41 +00007730void ASTReader::ReadReferencedSelectors(
7731 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7732 if (ReferencedSelectorsData.empty())
7733 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007734
Guy Benyei11169dd2012-12-18 14:30:41 +00007735 // If there are @selector references added them to its pool. This is for
7736 // implementation of -Wselector.
7737 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7738 unsigned I = 0;
7739 while (I < DataSize) {
7740 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7741 SourceLocation SelLoc
7742 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7743 Sels.push_back(std::make_pair(Sel, SelLoc));
7744 }
7745 ReferencedSelectorsData.clear();
7746}
7747
7748void ASTReader::ReadWeakUndeclaredIdentifiers(
7749 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7750 if (WeakUndeclaredIdentifiers.empty())
7751 return;
7752
7753 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007754 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007756 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7758 SourceLocation Loc
7759 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7760 bool Used = WeakUndeclaredIdentifiers[I++];
7761 WeakInfo WI(AliasId, Loc);
7762 WI.setUsed(Used);
7763 WeakIDs.push_back(std::make_pair(WeakId, WI));
7764 }
7765 WeakUndeclaredIdentifiers.clear();
7766}
7767
7768void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7769 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7770 ExternalVTableUse VT;
7771 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7772 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7773 VT.DefinitionRequired = VTableUses[Idx++];
7774 VTables.push_back(VT);
7775 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007776
Guy Benyei11169dd2012-12-18 14:30:41 +00007777 VTableUses.clear();
7778}
7779
7780void ASTReader::ReadPendingInstantiations(
7781 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7782 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7783 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7784 SourceLocation Loc
7785 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7786
7787 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 PendingInstantiations.clear();
7790}
7791
Richard Smithe40f2ba2013-08-07 21:41:30 +00007792void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007793 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7794 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007795 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7796 /* In loop */) {
7797 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7798
Justin Lebar28f09c52016-10-10 16:26:08 +00007799 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007800 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7801
7802 ModuleFile *F = getOwningModuleFile(LT->D);
7803 assert(F && "No module");
7804
7805 unsigned TokN = LateParsedTemplates[Idx++];
7806 LT->Toks.reserve(TokN);
7807 for (unsigned T = 0; T < TokN; ++T)
7808 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7809
Justin Lebar28f09c52016-10-10 16:26:08 +00007810 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007811 }
7812
7813 LateParsedTemplates.clear();
7814}
7815
Guy Benyei11169dd2012-12-18 14:30:41 +00007816void ASTReader::LoadSelector(Selector Sel) {
7817 // It would be complicated to avoid reading the methods anyway. So don't.
7818 ReadMethodPool(Sel);
7819}
7820
7821void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7822 assert(ID && "Non-zero identifier ID required");
7823 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7824 IdentifiersLoaded[ID - 1] = II;
7825 if (DeserializationListener)
7826 DeserializationListener->IdentifierRead(ID, II);
7827}
7828
7829/// \brief Set the globally-visible declarations associated with the given
7830/// identifier.
7831///
7832/// If the AST reader is currently in a state where the given declaration IDs
7833/// cannot safely be resolved, they are queued until it is safe to resolve
7834/// them.
7835///
7836/// \param II an IdentifierInfo that refers to one or more globally-visible
7837/// declarations.
7838///
7839/// \param DeclIDs the set of declaration IDs with the name @p II that are
7840/// visible at global scope.
7841///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007842/// \param Decls if non-null, this vector will be populated with the set of
7843/// deserialized declarations. These declarations will not be pushed into
7844/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007845void
7846ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7847 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007848 SmallVectorImpl<Decl *> *Decls) {
7849 if (NumCurrentElementsDeserializing && !Decls) {
7850 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 return;
7852 }
7853
7854 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007855 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 // Queue this declaration so that it will be added to the
7857 // translation unit scope and identifier's declaration chain
7858 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007859 PreloadedDeclIDs.push_back(DeclIDs[I]);
7860 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007861 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007862
7863 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7864
7865 // If we're simply supposed to record the declarations, do so now.
7866 if (Decls) {
7867 Decls->push_back(D);
7868 continue;
7869 }
7870
7871 // Introduce this declaration into the translation-unit scope
7872 // and add it to the declaration chain for this identifier, so
7873 // that (unqualified) name lookup will find it.
7874 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 }
7876}
7877
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007878IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007879 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007880 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007881
7882 if (IdentifiersLoaded.empty()) {
7883 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007884 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 }
7886
7887 ID -= 1;
7888 if (!IdentifiersLoaded[ID]) {
7889 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7890 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7891 ModuleFile *M = I->second;
7892 unsigned Index = ID - M->BaseIdentifierID;
7893 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7894
7895 // All of the strings in the AST file are preceded by a 16-bit length.
7896 // Extract that 16-bit length to avoid having to execute strlen().
7897 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7898 // unsigned integers. This is important to avoid integer overflow when
7899 // we cast them to 'unsigned'.
7900 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7901 unsigned StrLen = (((unsigned) StrLenPtr[0])
7902 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007903 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7904 IdentifiersLoaded[ID] = &II;
7905 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007906 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007907 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 }
7909
7910 return IdentifiersLoaded[ID];
7911}
7912
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007913IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7914 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007915}
7916
7917IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7918 if (LocalID < NUM_PREDEF_IDENT_IDS)
7919 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007920
Richard Smith37a93df2017-02-18 00:32:02 +00007921 if (!M.ModuleOffsetMap.empty())
7922 ReadModuleOffsetMap(M);
7923
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7925 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007926 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007928
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 return LocalID + I->second;
7930}
7931
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007932MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007934 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007935
7936 if (MacrosLoaded.empty()) {
7937 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007938 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 }
7940
7941 ID -= NUM_PREDEF_MACRO_IDS;
7942 if (!MacrosLoaded[ID]) {
7943 GlobalMacroMapType::iterator I
7944 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7945 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7946 ModuleFile *M = I->second;
7947 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007948 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007949
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007950 if (DeserializationListener)
7951 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7952 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 }
7954
7955 return MacrosLoaded[ID];
7956}
7957
7958MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7959 if (LocalID < NUM_PREDEF_MACRO_IDS)
7960 return LocalID;
7961
Richard Smith37a93df2017-02-18 00:32:02 +00007962 if (!M.ModuleOffsetMap.empty())
7963 ReadModuleOffsetMap(M);
7964
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7966 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7967 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7968
7969 return LocalID + I->second;
7970}
7971
7972serialization::SubmoduleID
7973ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7974 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7975 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007976
Richard Smith37a93df2017-02-18 00:32:02 +00007977 if (!M.ModuleOffsetMap.empty())
7978 ReadModuleOffsetMap(M);
7979
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7981 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007982 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007984
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 return LocalID + I->second;
7986}
7987
7988Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7989 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7990 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007991 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007993
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 if (GlobalID > SubmodulesLoaded.size()) {
7995 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007996 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007998
Guy Benyei11169dd2012-12-18 14:30:41 +00007999 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8000}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008001
8002Module *ASTReader::getModule(unsigned ID) {
8003 return getSubmodule(ID);
8004}
8005
Richard Smithd88a7f12015-09-01 20:35:42 +00008006ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8007 if (ID & 1) {
8008 // It's a module, look it up by submodule ID.
8009 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8010 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8011 } else {
8012 // It's a prefix (preamble, PCH, ...). Look it up by index.
8013 unsigned IndexFromEnd = ID >> 1;
8014 assert(IndexFromEnd && "got reference to unknown module file");
8015 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8016 }
8017}
8018
8019unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8020 if (!F)
8021 return 1;
8022
8023 // For a file representing a module, use the submodule ID of the top-level
8024 // module as the file ID. For any other kind of file, the number of such
8025 // files loaded beforehand will be the same on reload.
8026 // FIXME: Is this true even if we have an explicit module file and a PCH?
8027 if (F->isModule())
8028 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8029
8030 auto PCHModules = getModuleManager().pch_modules();
8031 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8032 assert(I != PCHModules.end() && "emitting reference to unknown file");
8033 return (I - PCHModules.end()) << 1;
8034}
8035
Adrian Prantl15bcf702015-06-30 17:39:43 +00008036llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8037ASTReader::getSourceDescriptor(unsigned ID) {
8038 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008039 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008040
8041 // If there is only a single PCH, return it instead.
8042 // Chained PCH are not suported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008043 const auto &PCHChain = ModuleMgr.pch_modules();
8044 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008045 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008046 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008047 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8048 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8049 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008050 }
8051 return None;
8052}
8053
David Blaikie9ffe5a32017-01-30 05:00:26 +00008054ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
8055 const Module *M = getSubmodule(ID);
8056 if (!M || !M->WithCodegen)
8057 return EK_ReplyHazy;
8058
8059 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
8060 assert(MF); // ?
8061 if (MF->Kind == ModuleKind::MK_MainFile)
8062 return EK_Never;
8063 return EK_Always;
8064}
8065
Guy Benyei11169dd2012-12-18 14:30:41 +00008066Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8067 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8068}
8069
8070Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8071 if (ID == 0)
8072 return Selector();
8073
8074 if (ID > SelectorsLoaded.size()) {
8075 Error("selector ID out of range in AST file");
8076 return Selector();
8077 }
8078
Craig Toppera13603a2014-05-22 05:54:18 +00008079 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 // Load this selector from the selector table.
8081 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8082 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8083 ModuleFile &M = *I->second;
8084 ASTSelectorLookupTrait Trait(*this, M);
8085 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8086 SelectorsLoaded[ID - 1] =
8087 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8088 if (DeserializationListener)
8089 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8090 }
8091
8092 return SelectorsLoaded[ID - 1];
8093}
8094
8095Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8096 return DecodeSelector(ID);
8097}
8098
8099uint32_t ASTReader::GetNumExternalSelectors() {
8100 // ID 0 (the null selector) is considered an external selector.
8101 return getTotalNumSelectors() + 1;
8102}
8103
8104serialization::SelectorID
8105ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8106 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8107 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008108
Richard Smith37a93df2017-02-18 00:32:02 +00008109 if (!M.ModuleOffsetMap.empty())
8110 ReadModuleOffsetMap(M);
8111
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8113 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008114 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008116
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 return LocalID + I->second;
8118}
8119
8120DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008121ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 const RecordData &Record, unsigned &Idx) {
8123 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8124 switch (Kind) {
8125 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008126 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008127
8128 case DeclarationName::ObjCZeroArgSelector:
8129 case DeclarationName::ObjCOneArgSelector:
8130 case DeclarationName::ObjCMultiArgSelector:
8131 return DeclarationName(ReadSelector(F, Record, Idx));
8132
8133 case DeclarationName::CXXConstructorName:
8134 return Context.DeclarationNames.getCXXConstructorName(
8135 Context.getCanonicalType(readType(F, Record, Idx)));
8136
8137 case DeclarationName::CXXDestructorName:
8138 return Context.DeclarationNames.getCXXDestructorName(
8139 Context.getCanonicalType(readType(F, Record, Idx)));
8140
Richard Smith35845152017-02-07 01:37:30 +00008141 case DeclarationName::CXXDeductionGuideName:
8142 return Context.DeclarationNames.getCXXDeductionGuideName(
8143 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8144
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 case DeclarationName::CXXConversionFunctionName:
8146 return Context.DeclarationNames.getCXXConversionFunctionName(
8147 Context.getCanonicalType(readType(F, Record, Idx)));
8148
8149 case DeclarationName::CXXOperatorName:
8150 return Context.DeclarationNames.getCXXOperatorName(
8151 (OverloadedOperatorKind)Record[Idx++]);
8152
8153 case DeclarationName::CXXLiteralOperatorName:
8154 return Context.DeclarationNames.getCXXLiteralOperatorName(
8155 GetIdentifierInfo(F, Record, Idx));
8156
8157 case DeclarationName::CXXUsingDirective:
8158 return DeclarationName::getUsingDirectiveName();
8159 }
8160
8161 llvm_unreachable("Invalid NameKind!");
8162}
8163
8164void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8165 DeclarationNameLoc &DNLoc,
8166 DeclarationName Name,
8167 const RecordData &Record, unsigned &Idx) {
8168 switch (Name.getNameKind()) {
8169 case DeclarationName::CXXConstructorName:
8170 case DeclarationName::CXXDestructorName:
8171 case DeclarationName::CXXConversionFunctionName:
8172 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8173 break;
8174
8175 case DeclarationName::CXXOperatorName:
8176 DNLoc.CXXOperatorName.BeginOpNameLoc
8177 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8178 DNLoc.CXXOperatorName.EndOpNameLoc
8179 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8180 break;
8181
8182 case DeclarationName::CXXLiteralOperatorName:
8183 DNLoc.CXXLiteralOperatorName.OpNameLoc
8184 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8185 break;
8186
8187 case DeclarationName::Identifier:
8188 case DeclarationName::ObjCZeroArgSelector:
8189 case DeclarationName::ObjCOneArgSelector:
8190 case DeclarationName::ObjCMultiArgSelector:
8191 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008192 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008193 break;
8194 }
8195}
8196
8197void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8198 DeclarationNameInfo &NameInfo,
8199 const RecordData &Record, unsigned &Idx) {
8200 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8201 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8202 DeclarationNameLoc DNLoc;
8203 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8204 NameInfo.setInfo(DNLoc);
8205}
8206
8207void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8208 const RecordData &Record, unsigned &Idx) {
8209 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8210 unsigned NumTPLists = Record[Idx++];
8211 Info.NumTemplParamLists = NumTPLists;
8212 if (NumTPLists) {
8213 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008214 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008215 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8216 }
8217}
8218
8219TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008220ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 unsigned &Idx) {
8222 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8223 switch (Kind) {
8224 case TemplateName::Template:
8225 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8226
8227 case TemplateName::OverloadedTemplate: {
8228 unsigned size = Record[Idx++];
8229 UnresolvedSet<8> Decls;
8230 while (size--)
8231 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8232
8233 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8234 }
8235
8236 case TemplateName::QualifiedTemplate: {
8237 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8238 bool hasTemplKeyword = Record[Idx++];
8239 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8240 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8241 }
8242
8243 case TemplateName::DependentTemplate: {
8244 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8245 if (Record[Idx++]) // isIdentifier
8246 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008247 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 Idx));
8249 return Context.getDependentTemplateName(NNS,
8250 (OverloadedOperatorKind)Record[Idx++]);
8251 }
8252
8253 case TemplateName::SubstTemplateTemplateParm: {
8254 TemplateTemplateParmDecl *param
8255 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8256 if (!param) return TemplateName();
8257 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8258 return Context.getSubstTemplateTemplateParm(param, replacement);
8259 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008260
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008262 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8264 if (!Param)
8265 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008266
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8268 if (ArgPack.getKind() != TemplateArgument::Pack)
8269 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008270
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8272 }
8273 }
8274
8275 llvm_unreachable("Unhandled template name kind!");
8276}
8277
Richard Smith2bb3c342015-08-09 01:05:31 +00008278TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8279 const RecordData &Record,
8280 unsigned &Idx,
8281 bool Canonicalize) {
8282 if (Canonicalize) {
8283 // The caller wants a canonical template argument. Sometimes the AST only
8284 // wants template arguments in canonical form (particularly as the template
8285 // argument lists of template specializations) so ensure we preserve that
8286 // canonical form across serialization.
8287 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8288 return Context.getCanonicalTemplateArgument(Arg);
8289 }
8290
Guy Benyei11169dd2012-12-18 14:30:41 +00008291 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8292 switch (Kind) {
8293 case TemplateArgument::Null:
8294 return TemplateArgument();
8295 case TemplateArgument::Type:
8296 return TemplateArgument(readType(F, Record, Idx));
8297 case TemplateArgument::Declaration: {
8298 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008299 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 }
8301 case TemplateArgument::NullPtr:
8302 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8303 case TemplateArgument::Integral: {
8304 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8305 QualType T = readType(F, Record, Idx);
8306 return TemplateArgument(Context, Value, T);
8307 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008308 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8310 case TemplateArgument::TemplateExpansion: {
8311 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008312 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008313 if (unsigned NumExpansions = Record[Idx++])
8314 NumTemplateExpansions = NumExpansions - 1;
8315 return TemplateArgument(Name, NumTemplateExpansions);
8316 }
8317 case TemplateArgument::Expression:
8318 return TemplateArgument(ReadExpr(F));
8319 case TemplateArgument::Pack: {
8320 unsigned NumArgs = Record[Idx++];
8321 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8322 for (unsigned I = 0; I != NumArgs; ++I)
8323 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008324 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008325 }
8326 }
8327
8328 llvm_unreachable("Unhandled template argument kind!");
8329}
8330
8331TemplateParameterList *
8332ASTReader::ReadTemplateParameterList(ModuleFile &F,
8333 const RecordData &Record, unsigned &Idx) {
8334 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8335 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8336 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8337
8338 unsigned NumParams = Record[Idx++];
8339 SmallVector<NamedDecl *, 16> Params;
8340 Params.reserve(NumParams);
8341 while (NumParams--)
8342 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8343
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008344 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 TemplateParameterList* TemplateParams =
8346 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008347 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008348 return TemplateParams;
8349}
8350
8351void
8352ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008353ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008355 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 unsigned NumTemplateArgs = Record[Idx++];
8357 TemplArgs.reserve(NumTemplateArgs);
8358 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008359 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008360}
8361
8362/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008363void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 const RecordData &Record, unsigned &Idx) {
8365 unsigned NumDecls = Record[Idx++];
8366 Set.reserve(Context, NumDecls);
8367 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008368 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008370 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008371 }
8372}
8373
8374CXXBaseSpecifier
8375ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8376 const RecordData &Record, unsigned &Idx) {
8377 bool isVirtual = static_cast<bool>(Record[Idx++]);
8378 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8379 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8380 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8381 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8382 SourceRange Range = ReadSourceRange(F, Record, Idx);
8383 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008384 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 EllipsisLoc);
8386 Result.setInheritConstructors(inheritConstructors);
8387 return Result;
8388}
8389
Richard Smithc2bb8182015-03-24 06:36:48 +00008390CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008391ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8392 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008394 assert(NumInitializers && "wrote ctor initializers but have no inits");
8395 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8396 for (unsigned i = 0; i != NumInitializers; ++i) {
8397 TypeSourceInfo *TInfo = nullptr;
8398 bool IsBaseVirtual = false;
8399 FieldDecl *Member = nullptr;
8400 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008401
Richard Smithc2bb8182015-03-24 06:36:48 +00008402 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8403 switch (Type) {
8404 case CTOR_INITIALIZER_BASE:
8405 TInfo = GetTypeSourceInfo(F, Record, Idx);
8406 IsBaseVirtual = Record[Idx++];
8407 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008408
Richard Smithc2bb8182015-03-24 06:36:48 +00008409 case CTOR_INITIALIZER_DELEGATING:
8410 TInfo = GetTypeSourceInfo(F, Record, Idx);
8411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008412
Richard Smithc2bb8182015-03-24 06:36:48 +00008413 case CTOR_INITIALIZER_MEMBER:
8414 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8415 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008416
Richard Smithc2bb8182015-03-24 06:36:48 +00008417 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8418 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8419 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008420 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008421
8422 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8423 Expr *Init = ReadExpr(F);
8424 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8425 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008426
8427 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008428 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008429 BOMInit = new (Context)
8430 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8431 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008432 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008433 BOMInit = new (Context)
8434 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008435 else if (Member)
8436 BOMInit = new (Context)
8437 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8438 Init, RParenLoc);
8439 else
8440 BOMInit = new (Context)
8441 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8442 LParenLoc, Init, RParenLoc);
8443
Richard Smith418ed822016-12-14 19:45:03 +00008444 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008445 unsigned SourceOrder = Record[Idx++];
8446 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008447 }
8448
Richard Smithc2bb8182015-03-24 06:36:48 +00008449 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 }
8451
Richard Smithc2bb8182015-03-24 06:36:48 +00008452 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008453}
8454
8455NestedNameSpecifier *
8456ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8457 const RecordData &Record, unsigned &Idx) {
8458 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008459 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008460 for (unsigned I = 0; I != N; ++I) {
8461 NestedNameSpecifier::SpecifierKind Kind
8462 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8463 switch (Kind) {
8464 case NestedNameSpecifier::Identifier: {
8465 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8466 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8467 break;
8468 }
8469
8470 case NestedNameSpecifier::Namespace: {
8471 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8472 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8473 break;
8474 }
8475
8476 case NestedNameSpecifier::NamespaceAlias: {
8477 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8478 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8479 break;
8480 }
8481
8482 case NestedNameSpecifier::TypeSpec:
8483 case NestedNameSpecifier::TypeSpecWithTemplate: {
8484 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8485 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008486 return nullptr;
8487
Guy Benyei11169dd2012-12-18 14:30:41 +00008488 bool Template = Record[Idx++];
8489 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8490 break;
8491 }
8492
8493 case NestedNameSpecifier::Global: {
8494 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8495 // No associated value, and there can't be a prefix.
8496 break;
8497 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008498
8499 case NestedNameSpecifier::Super: {
8500 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8501 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8502 break;
8503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008504 }
8505 Prev = NNS;
8506 }
8507 return NNS;
8508}
8509
8510NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008511ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 unsigned &Idx) {
8513 unsigned N = Record[Idx++];
8514 NestedNameSpecifierLocBuilder Builder;
8515 for (unsigned I = 0; I != N; ++I) {
8516 NestedNameSpecifier::SpecifierKind Kind
8517 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8518 switch (Kind) {
8519 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008520 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008521 SourceRange Range = ReadSourceRange(F, Record, Idx);
8522 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8523 break;
8524 }
8525
8526 case NestedNameSpecifier::Namespace: {
8527 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8528 SourceRange Range = ReadSourceRange(F, Record, Idx);
8529 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8530 break;
8531 }
8532
8533 case NestedNameSpecifier::NamespaceAlias: {
8534 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8535 SourceRange Range = ReadSourceRange(F, Record, Idx);
8536 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8537 break;
8538 }
8539
8540 case NestedNameSpecifier::TypeSpec:
8541 case NestedNameSpecifier::TypeSpecWithTemplate: {
8542 bool Template = Record[Idx++];
8543 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8544 if (!T)
8545 return NestedNameSpecifierLoc();
8546 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8547
8548 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008549 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008550 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8551 T->getTypeLoc(), ColonColonLoc);
8552 break;
8553 }
8554
8555 case NestedNameSpecifier::Global: {
8556 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8557 Builder.MakeGlobal(Context, ColonColonLoc);
8558 break;
8559 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008560
8561 case NestedNameSpecifier::Super: {
8562 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8563 SourceRange Range = ReadSourceRange(F, Record, Idx);
8564 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8565 break;
8566 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008567 }
8568 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008569
Guy Benyei11169dd2012-12-18 14:30:41 +00008570 return Builder.getWithLocInContext(Context);
8571}
8572
8573SourceRange
8574ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8575 unsigned &Idx) {
8576 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8577 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8578 return SourceRange(beg, end);
8579}
8580
8581/// \brief Read an integral value
8582llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8583 unsigned BitWidth = Record[Idx++];
8584 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8585 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8586 Idx += NumWords;
8587 return Result;
8588}
8589
8590/// \brief Read a signed integral value
8591llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8592 bool isUnsigned = Record[Idx++];
8593 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8594}
8595
8596/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008597llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8598 const llvm::fltSemantics &Sem,
8599 unsigned &Idx) {
8600 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008601}
8602
8603// \brief Read a string
8604std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8605 unsigned Len = Record[Idx++];
8606 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8607 Idx += Len;
8608 return Result;
8609}
8610
Richard Smith7ed1bc92014-12-05 22:42:13 +00008611std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8612 unsigned &Idx) {
8613 std::string Filename = ReadString(Record, Idx);
8614 ResolveImportedPath(F, Filename);
8615 return Filename;
8616}
8617
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008618VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 unsigned &Idx) {
8620 unsigned Major = Record[Idx++];
8621 unsigned Minor = Record[Idx++];
8622 unsigned Subminor = Record[Idx++];
8623 if (Minor == 0)
8624 return VersionTuple(Major);
8625 if (Subminor == 0)
8626 return VersionTuple(Major, Minor - 1);
8627 return VersionTuple(Major, Minor - 1, Subminor - 1);
8628}
8629
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008630CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008631 const RecordData &Record,
8632 unsigned &Idx) {
8633 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8634 return CXXTemporary::Create(Context, Decl);
8635}
8636
Richard Smith37a93df2017-02-18 00:32:02 +00008637DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008638 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008639}
8640
Richard Smith37a93df2017-02-18 00:32:02 +00008641DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 return Diags.Report(Loc, DiagID);
8643}
8644
8645/// \brief Retrieve the identifier table associated with the
8646/// preprocessor.
8647IdentifierTable &ASTReader::getIdentifierTable() {
8648 return PP.getIdentifierTable();
8649}
8650
8651/// \brief Record that the given ID maps to the given switch-case
8652/// statement.
8653void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008654 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008655 "Already have a SwitchCase with this ID");
8656 (*CurrSwitchCaseStmts)[ID] = SC;
8657}
8658
8659/// \brief Retrieve the switch-case statement with the given ID.
8660SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008661 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008662 return (*CurrSwitchCaseStmts)[ID];
8663}
8664
8665void ASTReader::ClearSwitchCaseIDs() {
8666 CurrSwitchCaseStmts->clear();
8667}
8668
8669void ASTReader::ReadComments() {
8670 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008671 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008672 serialization::ModuleFile *> >::iterator
8673 I = CommentsCursors.begin(),
8674 E = CommentsCursors.end();
8675 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008676 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008677 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008678 serialization::ModuleFile &F = *I->second;
8679 SavedStreamPosition SavedPosition(Cursor);
8680
8681 RecordData Record;
8682 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008683 llvm::BitstreamEntry Entry =
8684 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008685
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008686 switch (Entry.Kind) {
8687 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8688 case llvm::BitstreamEntry::Error:
8689 Error("malformed block record in AST file");
8690 return;
8691 case llvm::BitstreamEntry::EndBlock:
8692 goto NextCursor;
8693 case llvm::BitstreamEntry::Record:
8694 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008695 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 }
8697
8698 // Read a record.
8699 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008700 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008701 case COMMENTS_RAW_COMMENT: {
8702 unsigned Idx = 0;
8703 SourceRange SR = ReadSourceRange(F, Record, Idx);
8704 RawComment::CommentKind Kind =
8705 (RawComment::CommentKind) Record[Idx++];
8706 bool IsTrailingComment = Record[Idx++];
8707 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008708 Comments.push_back(new (Context) RawComment(
8709 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8710 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008711 break;
8712 }
8713 }
8714 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008715 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008716 // De-serialized SourceLocations get negative FileIDs for other modules,
8717 // potentially invalidating the original order. Sort it again.
8718 std::sort(Comments.begin(), Comments.end(),
8719 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008720 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008721 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008722}
8723
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008724void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8725 bool IncludeSystem, bool Complain,
8726 llvm::function_ref<void(const serialization::InputFile &IF,
8727 bool isSystem)> Visitor) {
8728 unsigned NumUserInputs = MF.NumUserInputFiles;
8729 unsigned NumInputs = MF.InputFilesLoaded.size();
8730 assert(NumUserInputs <= NumInputs);
8731 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8732 for (unsigned I = 0; I < N; ++I) {
8733 bool IsSystem = I >= NumUserInputs;
8734 InputFile IF = getInputFile(MF, I+1, Complain);
8735 Visitor(IF, IsSystem);
8736 }
8737}
8738
Richard Smithcd45dbc2014-04-19 03:48:30 +00008739std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8740 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008741 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008742 return M->getFullModuleName();
8743
8744 // Otherwise, use the name of the top-level module the decl is within.
8745 if (ModuleFile *M = getOwningModuleFile(D))
8746 return M->ModuleName;
8747
8748 // Not from a module.
8749 return "";
8750}
8751
Guy Benyei11169dd2012-12-18 14:30:41 +00008752void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008753 while (!PendingIdentifierInfos.empty() ||
8754 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008755 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008756 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008757 // If any identifiers with corresponding top-level declarations have
8758 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008759 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8760 TopLevelDeclsMap;
8761 TopLevelDeclsMap TopLevelDecls;
8762
Guy Benyei11169dd2012-12-18 14:30:41 +00008763 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008764 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008765 SmallVector<uint32_t, 4> DeclIDs =
8766 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008767 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008768
8769 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008770 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008771
Richard Smith851072e2014-05-19 20:59:20 +00008772 // For each decl chain that we wanted to complete while deserializing, mark
8773 // it as "still needs to be completed".
8774 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8775 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8776 }
8777 PendingIncompleteDeclChains.clear();
8778
Guy Benyei11169dd2012-12-18 14:30:41 +00008779 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008780 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008781 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008782 PendingDeclChains.clear();
8783
Douglas Gregor6168bd22013-02-18 15:53:43 +00008784 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008785 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8786 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008787 IdentifierInfo *II = TLD->first;
8788 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008789 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008790 }
8791 }
8792
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 // Load any pending macro definitions.
8794 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008795 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8796 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8797 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8798 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008799 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008800 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008801 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008802 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008803 resolvePendingMacro(II, Info);
8804 }
8805 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008806 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008807 ++IDIdx) {
8808 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008809 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008810 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 }
8812 }
8813 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008814
8815 // Wire up the DeclContexts for Decls that we delayed setting until
8816 // recursive loading is completed.
8817 while (!PendingDeclContextInfos.empty()) {
8818 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8819 PendingDeclContextInfos.pop_front();
8820 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8821 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8822 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8823 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008824
Richard Smithd1c46742014-04-30 02:24:17 +00008825 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008826 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008827 auto Update = PendingUpdateRecords.pop_back_val();
8828 ReadingKindTracker ReadingKind(Read_Decl, *this);
8829 loadDeclUpdateRecords(Update.first, Update.second);
8830 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008831 }
Richard Smith8a639892015-01-24 01:07:20 +00008832
8833 // At this point, all update records for loaded decls are in place, so any
8834 // fake class definitions should have become real.
8835 assert(PendingFakeDefinitionData.empty() &&
8836 "faked up a class definition but never saw the real one");
8837
Guy Benyei11169dd2012-12-18 14:30:41 +00008838 // If we deserialized any C++ or Objective-C class definitions, any
8839 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008840 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008841 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008842 for (Decl *D : PendingDefinitions) {
8843 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008844 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008845 // Make sure that the TagType points at the definition.
8846 const_cast<TagType*>(TagT)->decl = TD;
8847 }
Richard Smith8ce51082015-03-11 01:44:51 +00008848
Craig Topperc6914d02014-08-25 04:15:02 +00008849 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008850 for (auto *R = getMostRecentExistingDecl(RD); R;
8851 R = R->getPreviousDecl()) {
8852 assert((R == D) ==
8853 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008854 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008855 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008856 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008857 }
8858
8859 continue;
8860 }
Richard Smith8ce51082015-03-11 01:44:51 +00008861
Craig Topperc6914d02014-08-25 04:15:02 +00008862 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008863 // Make sure that the ObjCInterfaceType points at the definition.
8864 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8865 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008866
8867 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8868 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8869
Guy Benyei11169dd2012-12-18 14:30:41 +00008870 continue;
8871 }
Richard Smith8ce51082015-03-11 01:44:51 +00008872
Craig Topperc6914d02014-08-25 04:15:02 +00008873 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008874 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8875 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8876
Guy Benyei11169dd2012-12-18 14:30:41 +00008877 continue;
8878 }
Richard Smith8ce51082015-03-11 01:44:51 +00008879
Craig Topperc6914d02014-08-25 04:15:02 +00008880 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008881 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8882 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008883 }
8884 PendingDefinitions.clear();
8885
8886 // Load the bodies of any functions or methods we've encountered. We do
8887 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008888 // have been fully wired up (hasBody relies on this).
8889 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008890 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8891 PBEnd = PendingBodies.end();
8892 PB != PBEnd; ++PB) {
8893 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8894 // FIXME: Check for =delete/=default?
8895 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008896 const FunctionDecl *Defn = nullptr;
8897 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008898 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008899 else
Richard Smith6561f922016-09-12 21:06:40 +00008900 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008901 continue;
8902 }
8903
8904 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8905 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8906 MD->setLazyBody(PB->second);
8907 }
8908 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008909
8910 // Do some cleanup.
8911 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8912 getContext().deduplicateMergedDefinitonsFor(ND);
8913 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008914}
8915
8916void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008917 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8918 return;
8919
Richard Smitha0ce9c42014-07-29 23:23:27 +00008920 // Trigger the import of the full definition of each class that had any
8921 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008922 // These updates may in turn find and diagnose some ODR failures, so take
8923 // ownership of the set first.
8924 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8925 PendingOdrMergeFailures.clear();
8926 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008927 Merge.first->buildLookup();
8928 Merge.first->decls_begin();
8929 Merge.first->bases_begin();
8930 Merge.first->vbases_begin();
8931 for (auto *RD : Merge.second) {
8932 RD->decls_begin();
8933 RD->bases_begin();
8934 RD->vbases_begin();
8935 }
8936 }
8937
8938 // For each declaration from a merged context, check that the canonical
8939 // definition of that context also contains a declaration of the same
8940 // entity.
8941 //
8942 // Caution: this loop does things that might invalidate iterators into
8943 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8944 while (!PendingOdrMergeChecks.empty()) {
8945 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8946
8947 // FIXME: Skip over implicit declarations for now. This matters for things
8948 // like implicitly-declared special member functions. This isn't entirely
8949 // correct; we can end up with multiple unmerged declarations of the same
8950 // implicit entity.
8951 if (D->isImplicit())
8952 continue;
8953
8954 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008955
8956 bool Found = false;
8957 const Decl *DCanon = D->getCanonicalDecl();
8958
Richard Smith01bdb7a2014-08-28 05:44:07 +00008959 for (auto RI : D->redecls()) {
8960 if (RI->getLexicalDeclContext() == CanonDef) {
8961 Found = true;
8962 break;
8963 }
8964 }
8965 if (Found)
8966 continue;
8967
Richard Smith0f4e2c42015-08-06 04:23:48 +00008968 // Quick check failed, time to do the slow thing. Note, we can't just
8969 // look up the name of D in CanonDef here, because the member that is
8970 // in CanonDef might not be found by name lookup (it might have been
8971 // replaced by a more recent declaration in the lookup table), and we
8972 // can't necessarily find it in the redeclaration chain because it might
8973 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008974 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008975 for (auto *CanonMember : CanonDef->decls()) {
8976 if (CanonMember->getCanonicalDecl() == DCanon) {
8977 // This can happen if the declaration is merely mergeable and not
8978 // actually redeclarable (we looked for redeclarations earlier).
8979 //
8980 // FIXME: We should be able to detect this more efficiently, without
8981 // pulling in all of the members of CanonDef.
8982 Found = true;
8983 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008984 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008985 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8986 if (ND->getDeclName() == D->getDeclName())
8987 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008988 }
8989
8990 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008991 // The AST doesn't like TagDecls becoming invalid after they've been
8992 // completed. We only really need to mark FieldDecls as invalid here.
8993 if (!isa<TagDecl>(D))
8994 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008995
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008996 // Ensure we don't accidentally recursively enter deserialization while
8997 // we're producing our diagnostic.
8998 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008999
9000 std::string CanonDefModule =
9001 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9002 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9003 << D << getOwningModuleNameForDiagnostic(D)
9004 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9005
9006 if (Candidates.empty())
9007 Diag(cast<Decl>(CanonDef)->getLocation(),
9008 diag::note_module_odr_violation_no_possible_decls) << D;
9009 else {
9010 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9011 Diag(Candidates[I]->getLocation(),
9012 diag::note_module_odr_violation_possible_decl)
9013 << Candidates[I];
9014 }
9015
9016 DiagnosedOdrMergeFailures.insert(CanonDef);
9017 }
9018 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009019
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009020 if (OdrMergeFailures.empty())
9021 return;
9022
9023 // Ensure we don't accidentally recursively enter deserialization while
9024 // we're producing our diagnostics.
9025 Deserializing RecursionGuard(this);
9026
Richard Smithcd45dbc2014-04-19 03:48:30 +00009027 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009028 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009029 // If we've already pointed out a specific problem with this class, don't
9030 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009031 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009032 continue;
9033
9034 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009035 CXXRecordDecl *FirstRecord = Merge.first;
9036 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9037 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00009038 // Multiple different declarations got merged together; tell the user
9039 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009040 if (FirstRecord == SecondRecord)
9041 continue;
9042
9043 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9044 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9045 DeclHashes FirstHashes;
9046 DeclHashes SecondHashes;
9047 ODRHash Hash;
9048
9049 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9050 CXXRecordDecl *Record) {
9051 for (auto *D : Record->decls()) {
9052 // Due to decl merging, the first CXXRecordDecl is the parent of
9053 // Decls in both records.
9054 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9055 continue;
9056 Hash.clear();
9057 Hash.AddSubDecl(D);
9058 Hashes.emplace_back(D, Hash.CalculateHash());
9059 }
9060 };
9061 PopulateHashes(FirstHashes, FirstRecord);
9062 PopulateHashes(SecondHashes, SecondRecord);
9063
9064 // Used with err_module_odr_violation_mismatch_decl and
9065 // note_module_odr_violation_mismatch_decl
9066 enum {
9067 EndOfClass,
9068 PublicSpecifer,
9069 PrivateSpecifer,
9070 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009071 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009072 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009073 CXXMethod,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009074 Other
9075 } FirstDiffType = Other,
9076 SecondDiffType = Other;
9077
9078 auto DifferenceSelector = [](Decl *D) {
9079 assert(D && "valid Decl required");
9080 switch (D->getKind()) {
9081 default:
9082 return Other;
9083 case Decl::AccessSpec:
9084 switch (D->getAccess()) {
9085 case AS_public:
9086 return PublicSpecifer;
9087 case AS_private:
9088 return PrivateSpecifer;
9089 case AS_protected:
9090 return ProtectedSpecifer;
9091 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009092 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009093 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009094 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009095 case Decl::StaticAssert:
9096 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009097 case Decl::Field:
9098 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009099 case Decl::CXXMethod:
9100 return CXXMethod;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009101 }
9102 };
9103
9104 Decl *FirstDecl = nullptr;
9105 Decl *SecondDecl = nullptr;
9106 auto FirstIt = FirstHashes.begin();
9107 auto SecondIt = SecondHashes.begin();
9108
9109 // If there is a diagnoseable difference, FirstDiffType and
9110 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9111 // filled in if not EndOfClass.
9112 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009113 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9114 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009115 ++FirstIt;
9116 ++SecondIt;
9117 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009118 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009119
Richard Trieue7f7ed22017-02-22 01:11:25 +00009120 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9121 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9122
9123 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9124 SecondDiffType =
9125 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9126
9127 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009128 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009129
9130 if (FirstDiffType == Other || SecondDiffType == Other) {
9131 // Reaching this point means an unexpected Decl was encountered
9132 // or no difference was detected. This causes a generic error
9133 // message to be emitted.
9134 Diag(FirstRecord->getLocation(),
9135 diag::err_module_odr_violation_different_definitions)
9136 << FirstRecord << FirstModule.empty() << FirstModule;
9137
9138 Diag(SecondRecord->getLocation(),
9139 diag::note_module_odr_violation_different_definitions)
9140 << SecondModule;
9141 Diagnosed = true;
9142 break;
9143 }
9144
9145 if (FirstDiffType != SecondDiffType) {
9146 SourceLocation FirstLoc;
9147 SourceRange FirstRange;
9148 if (FirstDiffType == EndOfClass) {
9149 FirstLoc = FirstRecord->getBraceRange().getEnd();
9150 } else {
9151 FirstLoc = FirstIt->first->getLocation();
9152 FirstRange = FirstIt->first->getSourceRange();
9153 }
9154 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9155 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9156 << FirstDiffType;
9157
9158 SourceLocation SecondLoc;
9159 SourceRange SecondRange;
9160 if (SecondDiffType == EndOfClass) {
9161 SecondLoc = SecondRecord->getBraceRange().getEnd();
9162 } else {
9163 SecondLoc = SecondDecl->getLocation();
9164 SecondRange = SecondDecl->getSourceRange();
9165 }
9166 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9167 << SecondModule << SecondRange << SecondDiffType;
9168 Diagnosed = true;
9169 break;
9170 }
9171
Richard Trieu639d7b62017-02-22 22:22:42 +00009172 assert(FirstDiffType == SecondDiffType);
9173
9174 // Used with err_module_odr_violation_mismatch_decl_diff and
9175 // note_module_odr_violation_mismatch_decl_diff
9176 enum ODRDeclDifference{
9177 StaticAssertCondition,
9178 StaticAssertMessage,
9179 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009180 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009181 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009182 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009183 FieldDifferentWidthBitField,
9184 FieldSingleMutable,
9185 FieldSingleInitializer,
9186 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009187 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009188 MethodDeleted,
9189 MethodVirtual,
9190 MethodStatic,
9191 MethodVolatile,
9192 MethodConst,
9193 MethodInline,
Richard Trieu639d7b62017-02-22 22:22:42 +00009194 };
9195
9196 // These lambdas have the common portions of the ODR diagnostics. This
9197 // has the same return as Diag(), so addition parameters can be passed
9198 // in with operator<<
9199 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9200 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9201 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9202 << FirstRecord << FirstModule.empty() << FirstModule << Range
9203 << DiffType;
9204 };
9205 auto ODRDiagNote = [&SecondModule, this](
9206 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9207 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9208 << SecondModule << Range << DiffType;
9209 };
9210
9211 auto ComputeODRHash = [&Hash](const Stmt* S) {
9212 assert(S);
9213 Hash.clear();
9214 Hash.AddStmt(S);
9215 return Hash.CalculateHash();
9216 };
9217
Richard Trieu8459ddf2017-02-24 02:59:12 +00009218 auto ComputeDeclNameODRHash = [&Hash](const DeclarationName Name) {
9219 Hash.clear();
9220 Hash.AddDeclarationName(Name);
9221 return Hash.CalculateHash();
9222 };
9223
Richard Trieu639d7b62017-02-22 22:22:42 +00009224 switch (FirstDiffType) {
9225 case Other:
9226 case EndOfClass:
9227 case PublicSpecifer:
9228 case PrivateSpecifer:
9229 case ProtectedSpecifer:
9230 llvm_unreachable("Invalid diff type");
9231
9232 case StaticAssert: {
9233 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9234 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9235
9236 Expr *FirstExpr = FirstSA->getAssertExpr();
9237 Expr *SecondExpr = SecondSA->getAssertExpr();
9238 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9239 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9240 if (FirstODRHash != SecondODRHash) {
9241 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9242 StaticAssertCondition);
9243 ODRDiagNote(SecondExpr->getLocStart(),
9244 SecondExpr->getSourceRange(), StaticAssertCondition);
9245 Diagnosed = true;
9246 break;
9247 }
9248
9249 StringLiteral *FirstStr = FirstSA->getMessage();
9250 StringLiteral *SecondStr = SecondSA->getMessage();
9251 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9252 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9253 SourceLocation FirstLoc, SecondLoc;
9254 SourceRange FirstRange, SecondRange;
9255 if (FirstStr) {
9256 FirstLoc = FirstStr->getLocStart();
9257 FirstRange = FirstStr->getSourceRange();
9258 } else {
9259 FirstLoc = FirstSA->getLocStart();
9260 FirstRange = FirstSA->getSourceRange();
9261 }
9262 if (SecondStr) {
9263 SecondLoc = SecondStr->getLocStart();
9264 SecondRange = SecondStr->getSourceRange();
9265 } else {
9266 SecondLoc = SecondSA->getLocStart();
9267 SecondRange = SecondSA->getSourceRange();
9268 }
9269 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9270 << (FirstStr == nullptr);
9271 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9272 << (SecondStr == nullptr);
9273 Diagnosed = true;
9274 break;
9275 }
9276
9277 if (FirstStr && SecondStr &&
9278 FirstStr->getString() != SecondStr->getString()) {
9279 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9280 StaticAssertMessage);
9281 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9282 StaticAssertMessage);
9283 Diagnosed = true;
9284 break;
9285 }
9286 break;
9287 }
Richard Trieud0786092017-02-23 00:23:01 +00009288 case Field: {
9289 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9290 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9291 IdentifierInfo *FirstII = FirstField->getIdentifier();
9292 IdentifierInfo *SecondII = SecondField->getIdentifier();
9293 if (FirstII->getName() != SecondII->getName()) {
9294 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9295 FieldName)
9296 << FirstII;
9297 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9298 FieldName)
9299 << SecondII;
9300
9301 Diagnosed = true;
9302 break;
9303 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009304
9305 assert(
9306 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9307
9308 QualType FirstType = FirstField->getType();
9309 QualType SecondType = SecondField->getType();
9310 const TypedefType *FirstTypedef = dyn_cast<TypedefType>(FirstType);
9311 const TypedefType *SecondTypedef = dyn_cast<TypedefType>(SecondType);
9312
9313 if ((FirstTypedef && !SecondTypedef) ||
9314 (!FirstTypedef && SecondTypedef)) {
9315 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9316 FieldTypeName)
9317 << FirstII << FirstType;
9318 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9319 FieldTypeName)
9320 << SecondII << SecondType;
9321
9322 Diagnosed = true;
9323 break;
9324 }
9325
9326 if (FirstTypedef && SecondTypedef) {
9327 unsigned FirstHash = ComputeDeclNameODRHash(
9328 FirstTypedef->getDecl()->getDeclName());
9329 unsigned SecondHash = ComputeDeclNameODRHash(
9330 SecondTypedef->getDecl()->getDeclName());
9331 if (FirstHash != SecondHash) {
9332 ODRDiagError(FirstField->getLocation(),
9333 FirstField->getSourceRange(), FieldTypeName)
9334 << FirstII << FirstType;
9335 ODRDiagNote(SecondField->getLocation(),
9336 SecondField->getSourceRange(), FieldTypeName)
9337 << SecondII << SecondType;
9338
9339 Diagnosed = true;
9340 break;
9341 }
9342 }
9343
Richard Trieu93772fc2017-02-24 20:59:28 +00009344 const bool IsFirstBitField = FirstField->isBitField();
9345 const bool IsSecondBitField = SecondField->isBitField();
9346 if (IsFirstBitField != IsSecondBitField) {
9347 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9348 FieldSingleBitField)
9349 << FirstII << IsFirstBitField;
9350 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9351 FieldSingleBitField)
9352 << SecondII << IsSecondBitField;
9353 Diagnosed = true;
9354 break;
9355 }
9356
9357 if (IsFirstBitField && IsSecondBitField) {
9358 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9359 FieldDifferentWidthBitField)
9360 << FirstII << FirstField->getBitWidth()->getSourceRange();
9361 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9362 FieldDifferentWidthBitField)
9363 << SecondII << SecondField->getBitWidth()->getSourceRange();
9364 Diagnosed = true;
9365 break;
9366 }
9367
Richard Trieu8d543e22017-02-24 23:35:37 +00009368 const bool IsFirstMutable = FirstField->isMutable();
9369 const bool IsSecondMutable = SecondField->isMutable();
9370 if (IsFirstMutable != IsSecondMutable) {
9371 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9372 FieldSingleMutable)
9373 << FirstII << IsFirstMutable;
9374 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9375 FieldSingleMutable)
9376 << SecondII << IsSecondMutable;
9377 Diagnosed = true;
9378 break;
9379 }
9380
9381 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9382 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9383 if ((!FirstInitializer && SecondInitializer) ||
9384 (FirstInitializer && !SecondInitializer)) {
9385 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9386 FieldSingleInitializer)
9387 << FirstII << (FirstInitializer != nullptr);
9388 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9389 FieldSingleInitializer)
9390 << SecondII << (SecondInitializer != nullptr);
9391 Diagnosed = true;
9392 break;
9393 }
9394
9395 if (FirstInitializer && SecondInitializer) {
9396 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9397 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9398 if (FirstInitHash != SecondInitHash) {
9399 ODRDiagError(FirstField->getLocation(),
9400 FirstField->getSourceRange(),
9401 FieldDifferentInitializers)
9402 << FirstII << FirstInitializer->getSourceRange();
9403 ODRDiagNote(SecondField->getLocation(),
9404 SecondField->getSourceRange(),
9405 FieldDifferentInitializers)
9406 << SecondII << SecondInitializer->getSourceRange();
9407 Diagnosed = true;
9408 break;
9409 }
9410 }
9411
Richard Trieud0786092017-02-23 00:23:01 +00009412 break;
9413 }
Richard Trieu48143742017-02-28 21:24:38 +00009414 case CXXMethod: {
9415 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9416 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu583e2c12017-03-04 00:08:58 +00009417 auto FirstName = FirstMethod->getDeclName();
9418 auto SecondName = SecondMethod->getDeclName();
9419 if (FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009420 ODRDiagError(FirstMethod->getLocation(),
9421 FirstMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009422 << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009423 ODRDiagNote(SecondMethod->getLocation(),
9424 SecondMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009425 << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009426
9427 Diagnosed = true;
9428 break;
9429 }
9430
Richard Trieu583e2c12017-03-04 00:08:58 +00009431 const bool FirstDeleted = FirstMethod->isDeleted();
9432 const bool SecondDeleted = SecondMethod->isDeleted();
9433 if (FirstDeleted != SecondDeleted) {
9434 ODRDiagError(FirstMethod->getLocation(),
9435 FirstMethod->getSourceRange(), MethodDeleted)
9436 << FirstName << FirstDeleted;
9437
9438 ODRDiagNote(SecondMethod->getLocation(),
9439 SecondMethod->getSourceRange(), MethodDeleted)
9440 << SecondName << SecondDeleted;
9441 Diagnosed = true;
9442 break;
9443 }
9444
9445 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9446 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9447 const bool FirstPure = FirstMethod->isPure();
9448 const bool SecondPure = SecondMethod->isPure();
9449 if ((FirstVirtual || SecondVirtual) &&
9450 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9451 ODRDiagError(FirstMethod->getLocation(),
9452 FirstMethod->getSourceRange(), MethodVirtual)
9453 << FirstName << FirstPure << FirstVirtual;
9454 ODRDiagNote(SecondMethod->getLocation(),
9455 SecondMethod->getSourceRange(), MethodVirtual)
9456 << SecondName << SecondPure << SecondVirtual;
9457 Diagnosed = true;
9458 break;
9459 }
9460
9461 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9462 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9463 // class needs to be checked instead.
9464 const auto FirstStorage = FirstMethod->getStorageClass();
9465 const auto SecondStorage = SecondMethod->getStorageClass();
9466 const bool FirstStatic = FirstStorage == SC_Static;
9467 const bool SecondStatic = SecondStorage == SC_Static;
9468 if (FirstStatic != SecondStatic) {
9469 ODRDiagError(FirstMethod->getLocation(),
9470 FirstMethod->getSourceRange(), MethodStatic)
9471 << FirstName << FirstStatic;
9472 ODRDiagNote(SecondMethod->getLocation(),
9473 SecondMethod->getSourceRange(), MethodStatic)
9474 << SecondName << SecondStatic;
9475 Diagnosed = true;
9476 break;
9477 }
9478
9479 const bool FirstVolatile = FirstMethod->isVolatile();
9480 const bool SecondVolatile = SecondMethod->isVolatile();
9481 if (FirstVolatile != SecondVolatile) {
9482 ODRDiagError(FirstMethod->getLocation(),
9483 FirstMethod->getSourceRange(), MethodVolatile)
9484 << FirstName << FirstVolatile;
9485 ODRDiagNote(SecondMethod->getLocation(),
9486 SecondMethod->getSourceRange(), MethodVolatile)
9487 << SecondName << SecondVolatile;
9488 Diagnosed = true;
9489 break;
9490 }
9491
9492 const bool FirstConst = FirstMethod->isConst();
9493 const bool SecondConst = SecondMethod->isConst();
9494 if (FirstConst != SecondConst) {
9495 ODRDiagError(FirstMethod->getLocation(),
9496 FirstMethod->getSourceRange(), MethodConst)
9497 << FirstName << FirstConst;
9498 ODRDiagNote(SecondMethod->getLocation(),
9499 SecondMethod->getSourceRange(), MethodConst)
9500 << SecondName << SecondConst;
9501 Diagnosed = true;
9502 break;
9503 }
9504
9505 const bool FirstInline = FirstMethod->isInlineSpecified();
9506 const bool SecondInline = SecondMethod->isInlineSpecified();
9507 if (FirstInline != SecondInline) {
9508 ODRDiagError(FirstMethod->getLocation(),
9509 FirstMethod->getSourceRange(), MethodInline)
9510 << FirstName << FirstInline;
9511 ODRDiagNote(SecondMethod->getLocation(),
9512 SecondMethod->getSourceRange(), MethodInline)
9513 << SecondName << SecondInline;
9514 Diagnosed = true;
9515 break;
9516 }
9517
Richard Trieu48143742017-02-28 21:24:38 +00009518 break;
9519 }
Richard Trieu639d7b62017-02-22 22:22:42 +00009520 }
9521
Richard Trieue7f7ed22017-02-22 01:11:25 +00009522 if (Diagnosed == true)
9523 continue;
9524
9525 Diag(FirstRecord->getLocation(),
9526 diag::err_module_odr_violation_different_definitions)
9527 << FirstRecord << FirstModule.empty() << FirstModule;
9528
9529 Diag(SecondRecord->getLocation(),
9530 diag::note_module_odr_violation_different_definitions)
9531 << SecondModule;
9532 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009533 }
9534
9535 if (!Diagnosed) {
9536 // All definitions are updates to the same declaration. This happens if a
9537 // module instantiates the declaration of a class template specialization
9538 // and two or more other modules instantiate its definition.
9539 //
9540 // FIXME: Indicate which modules had instantiations of this definition.
9541 // FIXME: How can this even happen?
9542 Diag(Merge.first->getLocation(),
9543 diag::err_module_odr_violation_different_instantiations)
9544 << Merge.first;
9545 }
9546 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009547}
9548
Richard Smithce18a182015-07-14 00:26:00 +00009549void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009550 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009551 ReadTimer->startTimer();
9552}
9553
Guy Benyei11169dd2012-12-18 14:30:41 +00009554void ASTReader::FinishedDeserializing() {
9555 assert(NumCurrentElementsDeserializing &&
9556 "FinishedDeserializing not paired with StartedDeserializing");
9557 if (NumCurrentElementsDeserializing == 1) {
9558 // We decrease NumCurrentElementsDeserializing only after pending actions
9559 // are finished, to avoid recursively re-calling finishPendingActions().
9560 finishPendingActions();
9561 }
9562 --NumCurrentElementsDeserializing;
9563
Richard Smitha0ce9c42014-07-29 23:23:27 +00009564 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009565 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009566 while (!PendingExceptionSpecUpdates.empty()) {
9567 auto Updates = std::move(PendingExceptionSpecUpdates);
9568 PendingExceptionSpecUpdates.clear();
9569 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009570 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009571 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009572 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009573 if (auto *Listener = Context.getASTMutationListener())
9574 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009575 for (auto *Redecl : Update.second->redecls())
9576 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009577 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009578 }
9579
Richard Smithce18a182015-07-14 00:26:00 +00009580 if (ReadTimer)
9581 ReadTimer->stopTimer();
9582
Richard Smith0f4e2c42015-08-06 04:23:48 +00009583 diagnoseOdrViolations();
9584
Richard Smith04d05b52014-03-23 00:27:18 +00009585 // We are not in recursive loading, so it's safe to pass the "interesting"
9586 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009587 if (Consumer)
9588 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009589 }
9590}
9591
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009592void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009593 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9594 // Remove any fake results before adding any real ones.
9595 auto It = PendingFakeLookupResults.find(II);
9596 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009597 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009598 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009599 // FIXME: this works around module+PCH performance issue.
9600 // Rather than erase the result from the map, which is O(n), just clear
9601 // the vector of NamedDecls.
9602 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009603 }
9604 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009605
9606 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9607 SemaObj->TUScope->AddDecl(D);
9608 } else if (SemaObj->TUScope) {
9609 // Adding the decl to IdResolver may have failed because it was already in
9610 // (even though it was not added in scope). If it is already in, make sure
9611 // it gets in the scope as well.
9612 if (std::find(SemaObj->IdResolver.begin(Name),
9613 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9614 SemaObj->TUScope->AddDecl(D);
9615 }
9616}
9617
David Blaikie61137e12017-01-05 18:23:18 +00009618ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9619 const PCHContainerReader &PCHContainerRdr,
9620 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9621 StringRef isysroot, bool DisableValidation,
9622 bool AllowASTWithCompilerErrors,
9623 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9624 bool UseGlobalIndex,
9625 std::unique_ptr<llvm::Timer> ReadTimer)
9626 : Listener(DisableValidation
9627 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9628 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009629 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009630 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9631 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9632 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009633 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009634 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9635 AllowConfigurationMismatch(AllowConfigurationMismatch),
9636 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009637 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009638 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009639
9640 for (const auto &Ext : Extensions) {
9641 auto BlockName = Ext->getExtensionMetadata().BlockName;
9642 auto Known = ModuleFileExtensions.find(BlockName);
9643 if (Known != ModuleFileExtensions.end()) {
9644 Diags.Report(diag::warn_duplicate_module_file_extension)
9645 << BlockName;
9646 continue;
9647 }
9648
9649 ModuleFileExtensions.insert({BlockName, Ext});
9650 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009651}
9652
9653ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009654 if (OwnsDeserializationListener)
9655 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009656}
Richard Smith10379092016-05-06 23:14:07 +00009657
9658IdentifierResolver &ASTReader::getIdResolver() {
9659 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9660}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009661
9662unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9663 unsigned AbbrevID) {
9664 Idx = 0;
9665 Record.clear();
9666 return Cursor.readRecord(AbbrevID, Record);
9667}