blob: bb39a436abec9c8eb04eae46f70079ddc63f34df [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +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"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000051#include "llvm/Support/Compression.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000057#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000059#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000061#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000062
63using namespace clang;
64using namespace clang::serialization;
65using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000066using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Ben Langmuircb69b572014-03-07 06:40:32 +000068
69//===----------------------------------------------------------------------===//
70// ChainedASTReaderListener implementation
71//===----------------------------------------------------------------------===//
72
73bool
74ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
75 return First->ReadFullVersionInformation(FullVersion) ||
76 Second->ReadFullVersionInformation(FullVersion);
77}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000078void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
79 First->ReadModuleName(ModuleName);
80 Second->ReadModuleName(ModuleName);
81}
82void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
83 First->ReadModuleMapFile(ModuleMapPath);
84 Second->ReadModuleMapFile(ModuleMapPath);
85}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000086bool
87ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
88 bool Complain,
89 bool AllowCompatibleDifferences) {
90 return First->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences) ||
92 Second->ReadLanguageOptions(LangOpts, Complain,
93 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000094}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000095bool ChainedASTReaderListener::ReadTargetOptions(
96 const TargetOptions &TargetOpts, bool Complain,
97 bool AllowCompatibleDifferences) {
98 return First->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences) ||
100 Second->ReadTargetOptions(TargetOpts, Complain,
101 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000102}
103bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000104 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000105 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
106 Second->ReadDiagnosticOptions(DiagOpts, Complain);
107}
108bool
109ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
110 bool Complain) {
111 return First->ReadFileSystemOptions(FSOpts, Complain) ||
112 Second->ReadFileSystemOptions(FSOpts, Complain);
113}
114
115bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000116 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
117 bool Complain) {
118 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain) ||
120 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
121 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000122}
123bool ChainedASTReaderListener::ReadPreprocessorOptions(
124 const PreprocessorOptions &PPOpts, bool Complain,
125 std::string &SuggestedPredefines) {
126 return First->ReadPreprocessorOptions(PPOpts, Complain,
127 SuggestedPredefines) ||
128 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
129}
130void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
131 unsigned Value) {
132 First->ReadCounter(M, Value);
133 Second->ReadCounter(M, Value);
134}
135bool ChainedASTReaderListener::needsInputFileVisitation() {
136 return First->needsInputFileVisitation() ||
137 Second->needsInputFileVisitation();
138}
139bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
140 return First->needsSystemInputFileVisitation() ||
141 Second->needsSystemInputFileVisitation();
142}
Richard Smith216a3bd2015-08-13 17:57:10 +0000143void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
144 ModuleKind Kind) {
145 First->visitModuleFile(Filename, Kind);
146 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000147}
Ben Langmuircb69b572014-03-07 06:40:32 +0000148bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000149 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000150 bool isOverridden,
151 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000152 bool Continue = false;
153 if (First->needsInputFileVisitation() &&
154 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000155 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
156 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000157 if (Second->needsInputFileVisitation() &&
158 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000159 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
160 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000161 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000162}
163
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000164void ChainedASTReaderListener::readModuleFileExtension(
165 const ModuleFileExtensionMetadata &Metadata) {
166 First->readModuleFileExtension(Metadata);
167 Second->readModuleFileExtension(Metadata);
168}
169
Guy Benyei11169dd2012-12-18 14:30:41 +0000170//===----------------------------------------------------------------------===//
171// PCH validator implementation
172//===----------------------------------------------------------------------===//
173
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000174ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000175
176/// \brief Compare the given set of language options against an existing set of
177/// language options.
178///
179/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000180/// \param AllowCompatibleDifferences If true, differences between compatible
181/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000182///
183/// \returns true if the languagae options mis-match, false otherwise.
184static bool checkLanguageOptions(const LangOptions &LangOpts,
185 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000186 DiagnosticsEngine *Diags,
187 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000188#define LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_mismatch) \
192 << Description << LangOpts.Name << ExistingLangOpts.Name; \
193 return true; \
194 }
195
196#define VALUE_LANGOPT(Name, Bits, Default, Description) \
197 if (ExistingLangOpts.Name != LangOpts.Name) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
204#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
205 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
206 if (Diags) \
207 Diags->Report(diag::err_pch_langopt_value_mismatch) \
208 << Description; \
209 return true; \
210 }
211
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000212#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
213 if (!AllowCompatibleDifferences) \
214 LANGOPT(Name, Bits, Default, Description)
215
216#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
217 if (!AllowCompatibleDifferences) \
218 ENUM_LANGOPT(Name, Bits, Default, Description)
219
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000220#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
221 if (!AllowCompatibleDifferences) \
222 VALUE_LANGOPT(Name, Bits, Default, Description)
223
Guy Benyei11169dd2012-12-18 14:30:41 +0000224#define BENIGN_LANGOPT(Name, Bits, Default, Description)
225#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000226#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000227#include "clang/Basic/LangOptions.def"
228
Ben Langmuircd98cb72015-06-23 18:20:18 +0000229 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
230 if (Diags)
231 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
232 return true;
233 }
234
Guy Benyei11169dd2012-12-18 14:30:41 +0000235 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
236 if (Diags)
237 Diags->Report(diag::err_pch_langopt_value_mismatch)
238 << "target Objective-C runtime";
239 return true;
240 }
241
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000242 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
243 LangOpts.CommentOpts.BlockCommandNames) {
244 if (Diags)
245 Diags->Report(diag::err_pch_langopt_value_mismatch)
246 << "block command names";
247 return true;
248 }
249
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 return false;
251}
252
253/// \brief Compare the given set of target options against an existing set of
254/// target options.
255///
256/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
257///
258/// \returns true if the target options mis-match, false otherwise.
259static bool checkTargetOptions(const TargetOptions &TargetOpts,
260 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261 DiagnosticsEngine *Diags,
262 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000263#define CHECK_TARGET_OPT(Field, Name) \
264 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
265 if (Diags) \
266 Diags->Report(diag::err_pch_targetopt_mismatch) \
267 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
268 return true; \
269 }
270
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000271 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000272 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000273 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000274
275 // We can tolerate different CPUs in many cases, notably when one CPU
276 // supports a strict superset of another. When allowing compatible
277 // differences skip this check.
278 if (!AllowCompatibleDifferences)
279 CHECK_TARGET_OPT(CPU, "target CPU");
280
Guy Benyei11169dd2012-12-18 14:30:41 +0000281#undef CHECK_TARGET_OPT
282
283 // Compare feature sets.
284 SmallVector<StringRef, 4> ExistingFeatures(
285 ExistingTargetOpts.FeaturesAsWritten.begin(),
286 ExistingTargetOpts.FeaturesAsWritten.end());
287 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
288 TargetOpts.FeaturesAsWritten.end());
289 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
290 std::sort(ReadFeatures.begin(), ReadFeatures.end());
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 // We compute the set difference in both directions explicitly so that we can
293 // diagnose the differences differently.
294 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
295 std::set_difference(
296 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
297 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
298 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
299 ExistingFeatures.begin(), ExistingFeatures.end(),
300 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000301
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000302 // If we are allowing compatible differences and the read feature set is
303 // a strict subset of the existing feature set, there is nothing to diagnose.
304 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
305 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000306
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000307 if (Diags) {
308 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 << /* is-existing-feature */ false << Feature;
311 for (StringRef Feature : UnmatchedExistingFeatures)
312 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
313 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 }
315
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000317}
318
319bool
320PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000321 bool Complain,
322 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 const LangOptions &ExistingLangOpts = PP.getLangOpts();
324 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000325 Complain ? &Reader.Diags : nullptr,
326 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000327}
328
329bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000330 bool Complain,
331 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
333 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000334 Complain ? &Reader.Diags : nullptr,
335 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000336}
337
338namespace {
339 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
340 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000341 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
342 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000343}
344
Ben Langmuirb92de022014-04-29 16:25:26 +0000345static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
346 DiagnosticsEngine &Diags,
347 bool Complain) {
348 typedef DiagnosticsEngine::Level Level;
349
350 // Check current mappings for new -Werror mappings, and the stored mappings
351 // for cases that were explicitly mapped to *not* be errors that are now
352 // errors because of options like -Werror.
353 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
354
355 for (DiagnosticsEngine *MappingSource : MappingSources) {
356 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
357 diag::kind DiagID = DiagIDMappingPair.first;
358 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
359 if (CurLevel < DiagnosticsEngine::Error)
360 continue; // not significant
361 Level StoredLevel =
362 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
363 if (StoredLevel < DiagnosticsEngine::Error) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
366 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
367 return true;
368 }
369 }
370 }
371
372 return false;
373}
374
Alp Tokerac4e8e52014-06-22 21:58:33 +0000375static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
376 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
377 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
378 return true;
379 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000380}
381
382static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
383 DiagnosticsEngine &Diags,
384 bool IsSystem, bool Complain) {
385 // Top-level options
386 if (IsSystem) {
387 if (Diags.getSuppressSystemWarnings())
388 return false;
389 // If -Wsystem-headers was not enabled before, be conservative
390 if (StoredDiags.getSuppressSystemWarnings()) {
391 if (Complain)
392 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
393 return true;
394 }
395 }
396
397 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
398 if (Complain)
399 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
400 return true;
401 }
402
403 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
404 !StoredDiags.getEnableAllWarnings()) {
405 if (Complain)
406 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
407 return true;
408 }
409
410 if (isExtHandlingFromDiagsError(Diags) &&
411 !isExtHandlingFromDiagsError(StoredDiags)) {
412 if (Complain)
413 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
414 return true;
415 }
416
417 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
418}
419
420bool PCHValidator::ReadDiagnosticOptions(
421 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
422 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
423 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
424 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000425 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000426 // This should never fail, because we would have processed these options
427 // before writing them to an ASTFile.
428 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
429
430 ModuleManager &ModuleMgr = Reader.getModuleManager();
431 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
432
433 // If the original import came from a file explicitly generated by the user,
434 // don't check the diagnostic mappings.
435 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000436 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000437 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
438 // the transitive closure of its imports, since unrelated modules cannot be
439 // imported until after this module finishes validation.
440 ModuleFile *TopImport = *ModuleMgr.rbegin();
441 while (!TopImport->ImportedBy.empty())
442 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000443 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000444 return false;
445
446 StringRef ModuleName = TopImport->ModuleName;
447 assert(!ModuleName.empty() && "diagnostic options read before module name");
448
449 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
450 assert(M && "missing module");
451
452 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
453 // contains the union of their flags.
454 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
455}
456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457/// \brief Collect the macro definitions provided by the given preprocessor
458/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000459static void
460collectMacroDefinitions(const PreprocessorOptions &PPOpts,
461 MacroDefinitionsMap &Macros,
462 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
464 StringRef Macro = PPOpts.Macros[I].first;
465 bool IsUndef = PPOpts.Macros[I].second;
466
467 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
468 StringRef MacroName = MacroPair.first;
469 StringRef MacroBody = MacroPair.second;
470
471 // For an #undef'd macro, we only care about the name.
472 if (IsUndef) {
473 if (MacroNames && !Macros.count(MacroName))
474 MacroNames->push_back(MacroName);
475
476 Macros[MacroName] = std::make_pair("", true);
477 continue;
478 }
479
480 // For a #define'd macro, figure out the actual definition.
481 if (MacroName.size() == Macro.size())
482 MacroBody = "1";
483 else {
484 // Note: GCC drops anything following an end-of-line character.
485 StringRef::size_type End = MacroBody.find_first_of("\n\r");
486 MacroBody = MacroBody.substr(0, End);
487 }
488
489 if (MacroNames && !Macros.count(MacroName))
490 MacroNames->push_back(MacroName);
491 Macros[MacroName] = std::make_pair(MacroBody, false);
492 }
493}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000494
Guy Benyei11169dd2012-12-18 14:30:41 +0000495/// \brief Check the preprocessor options deserialized from the control block
496/// against the preprocessor options in an existing preprocessor.
497///
498/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000499/// \param Validate If true, validate preprocessor options. If false, allow
500/// macros defined by \p ExistingPPOpts to override those defined by
501/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000502static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
503 const PreprocessorOptions &ExistingPPOpts,
504 DiagnosticsEngine *Diags,
505 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000506 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000507 const LangOptions &LangOpts,
508 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 // Check macro definitions.
510 MacroDefinitionsMap ASTFileMacros;
511 collectMacroDefinitions(PPOpts, ASTFileMacros);
512 MacroDefinitionsMap ExistingMacros;
513 SmallVector<StringRef, 4> ExistingMacroNames;
514 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
515
516 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
517 // Dig out the macro definition in the existing preprocessor options.
518 StringRef MacroName = ExistingMacroNames[I];
519 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
520
521 // Check whether we know anything about this macro name or not.
522 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
523 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000524 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000525 // FIXME: Check whether this identifier was referenced anywhere in the
526 // AST file. If so, we should reject the AST file. Unfortunately, this
527 // information isn't in the control block. What shall we do about it?
528
529 if (Existing.second) {
530 SuggestedPredefines += "#undef ";
531 SuggestedPredefines += MacroName.str();
532 SuggestedPredefines += '\n';
533 } else {
534 SuggestedPredefines += "#define ";
535 SuggestedPredefines += MacroName.str();
536 SuggestedPredefines += ' ';
537 SuggestedPredefines += Existing.first.str();
538 SuggestedPredefines += '\n';
539 }
540 continue;
541 }
542
543 // If the macro was defined in one but undef'd in the other, we have a
544 // conflict.
545 if (Existing.second != Known->second.second) {
546 if (Diags) {
547 Diags->Report(diag::err_pch_macro_def_undef)
548 << MacroName << Known->second.second;
549 }
550 return true;
551 }
552
553 // If the macro was #undef'd in both, or if the macro bodies are identical,
554 // it's fine.
555 if (Existing.second || Existing.first == Known->second.first)
556 continue;
557
558 // The macro bodies differ; complain.
559 if (Diags) {
560 Diags->Report(diag::err_pch_macro_def_conflict)
561 << MacroName << Known->second.first << Existing.first;
562 }
563 return true;
564 }
565
566 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000567 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 if (Diags) {
569 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
570 }
571 return true;
572 }
573
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000574 // Detailed record is important since it is used for the module cache hash.
575 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000576 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000577 if (Diags) {
578 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
579 }
580 return true;
581 }
582
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 // Compute the #include and #include_macros lines we need.
584 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
585 StringRef File = ExistingPPOpts.Includes[I];
586 if (File == ExistingPPOpts.ImplicitPCHInclude)
587 continue;
588
589 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
590 != PPOpts.Includes.end())
591 continue;
592
593 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000594 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000595 SuggestedPredefines += "\"\n";
596 }
597
598 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
599 StringRef File = ExistingPPOpts.MacroIncludes[I];
600 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
601 File)
602 != PPOpts.MacroIncludes.end())
603 continue;
604
605 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000606 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 SuggestedPredefines += "\"\n##\n";
608 }
609
610 return false;
611}
612
613bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
614 bool Complain,
615 std::string &SuggestedPredefines) {
616 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
617
618 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000619 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000621 SuggestedPredefines,
622 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000623}
624
Yaxun Liu43712e02016-09-07 18:40:20 +0000625bool SimpleASTReaderListener::ReadPreprocessorOptions(
626 const PreprocessorOptions &PPOpts,
627 bool Complain,
628 std::string &SuggestedPredefines) {
629 return checkPreprocessorOptions(PPOpts,
630 PP.getPreprocessorOpts(),
631 nullptr,
632 PP.getFileManager(),
633 SuggestedPredefines,
634 PP.getLangOpts(),
635 false);
636}
637
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000638/// Check the header search options deserialized from the control block
639/// against the header search options in an existing preprocessor.
640///
641/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
642static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
643 StringRef SpecificModuleCachePath,
644 StringRef ExistingModuleCachePath,
645 DiagnosticsEngine *Diags,
646 const LangOptions &LangOpts) {
647 if (LangOpts.Modules) {
648 if (SpecificModuleCachePath != ExistingModuleCachePath) {
649 if (Diags)
650 Diags->Report(diag::err_pch_modulecache_mismatch)
651 << SpecificModuleCachePath << ExistingModuleCachePath;
652 return true;
653 }
654 }
655
656 return false;
657}
658
659bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
660 StringRef SpecificModuleCachePath,
661 bool Complain) {
662 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
663 PP.getHeaderSearchInfo().getModuleCachePath(),
664 Complain ? &Reader.Diags : nullptr,
665 PP.getLangOpts());
666}
667
Guy Benyei11169dd2012-12-18 14:30:41 +0000668void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
669 PP.setCounterValue(Value);
670}
671
672//===----------------------------------------------------------------------===//
673// AST reader implementation
674//===----------------------------------------------------------------------===//
675
Nico Weber824285e2014-05-08 04:26:47 +0000676void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
677 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000679 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
682
683
684unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
685 return serialization::ComputeHash(Sel);
686}
687
688
689std::pair<unsigned, unsigned>
690ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
692 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
693 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000694 return std::make_pair(KeyLen, DataLen);
695}
696
697ASTSelectorLookupTrait::internal_key_type
698ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000699 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000700 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000701 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
702 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
703 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 if (N == 0)
705 return SelTable.getNullarySelector(FirstII);
706 else if (N == 1)
707 return SelTable.getUnarySelector(FirstII);
708
709 SmallVector<IdentifierInfo *, 16> Args;
710 Args.push_back(FirstII);
711 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000712 Args.push_back(Reader.getLocalIdentifier(
713 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000714
715 return SelTable.getSelector(N, Args.data());
716}
717
718ASTSelectorLookupTrait::data_type
719ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
720 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000721 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000722
723 data_type Result;
724
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 Result.ID = Reader.getGlobalSelectorID(
726 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000727 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
728 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
729 Result.InstanceBits = FullInstanceBits & 0x3;
730 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
731 Result.FactoryBits = FullFactoryBits & 0x3;
732 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
733 unsigned NumInstanceMethods = FullInstanceBits >> 3;
734 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000735
736 // Load instance methods
737 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000738 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
739 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000740 Result.Instance.push_back(Method);
741 }
742
743 // Load factory methods
744 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000745 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
746 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 Result.Factory.push_back(Method);
748 }
749
750 return Result;
751}
752
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000753unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
754 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000755}
756
757std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000758ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000759 using namespace llvm::support;
760 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
761 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 return std::make_pair(KeyLen, DataLen);
763}
764
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000765ASTIdentifierLookupTraitBase::internal_key_type
766ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000768 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000769}
770
Douglas Gregordcf25082013-02-11 18:16:18 +0000771/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000772static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
773 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000774 return II.hadMacroDefinition() ||
775 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000776 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000777 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000778 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
779 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000780}
781
Richard Smith76c2f2c2015-07-17 20:09:43 +0000782static bool readBit(unsigned &Bits) {
783 bool Value = Bits & 0x1;
784 Bits >>= 1;
785 return Value;
786}
787
Richard Smith79bf9202015-08-24 03:33:22 +0000788IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
789 using namespace llvm::support;
790 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
791 return Reader.getGlobalIdentifierID(F, RawID >> 1);
792}
793
Richard Smitheb4b58f62016-02-05 01:40:54 +0000794static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
795 if (!II.isFromAST()) {
796 II.setIsFromAST();
797 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
798 if (isInterestingIdentifier(Reader, II, IsModule))
799 II.setChangedSinceDeserialization();
800 }
801}
802
Guy Benyei11169dd2012-12-18 14:30:41 +0000803IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
804 const unsigned char* d,
805 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000806 using namespace llvm::support;
807 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 bool IsInteresting = RawID & 0x01;
809
810 // Wipe out the "is interesting" bit.
811 RawID = RawID >> 1;
812
Richard Smith76c2f2c2015-07-17 20:09:43 +0000813 // Build the IdentifierInfo and link the identifier ID with it.
814 IdentifierInfo *II = KnownII;
815 if (!II) {
816 II = &Reader.getIdentifierTable().getOwn(k);
817 KnownII = II;
818 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000819 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 Reader.markIdentifierUpToDate(II);
821
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
823 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824 // For uninteresting identifiers, there's nothing else to do. Just notify
825 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 return II;
828 }
829
Justin Bogner57ba0b22014-03-28 22:03:24 +0000830 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
831 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000832 bool CPlusPlusOperatorKeyword = readBit(Bits);
833 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000834 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000835 bool Poisoned = readBit(Bits);
836 bool ExtensionToken = readBit(Bits);
837 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000838
839 assert(Bits == 0 && "Extra bits in the identifier?");
840 DataLen -= 8;
841
Guy Benyei11169dd2012-12-18 14:30:41 +0000842 // Set or check the various bits in the IdentifierInfo structure.
843 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000844 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000845 II->revertTokenIDToIdentifier();
846 if (!F.isModule())
847 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
848 else if (HasRevertedBuiltin && II->getBuiltinID()) {
849 II->revertBuiltin();
850 assert((II->hasRevertedBuiltin() ||
851 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
852 "Incorrect ObjC keyword or builtin ID");
853 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 assert(II->isExtensionToken() == ExtensionToken &&
855 "Incorrect extension token flag");
856 (void)ExtensionToken;
857 if (Poisoned)
858 II->setIsPoisoned(true);
859 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
860 "Incorrect C++ operator keyword flag");
861 (void)CPlusPlusOperatorKeyword;
862
863 // If this identifier is a macro, deserialize the macro
864 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000865 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000866 uint32_t MacroDirectivesOffset =
867 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000868 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000869
Richard Smithd7329392015-04-21 21:46:32 +0000870 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 }
872
873 Reader.SetIdentifierInfo(ID, II);
874
875 // Read all of the declarations visible at global scope with this
876 // name.
877 if (DataLen > 0) {
878 SmallVector<uint32_t, 4> DeclIDs;
879 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000880 DeclIDs.push_back(Reader.getGlobalDeclID(
881 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000882 Reader.SetGloballyVisibleDecls(II, DeclIDs);
883 }
884
885 return II;
886}
887
Richard Smitha06c7e62015-08-26 23:55:49 +0000888DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
889 : Kind(Name.getNameKind()) {
890 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000891 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000892 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 break;
894 case DeclarationName::ObjCZeroArgSelector:
895 case DeclarationName::ObjCOneArgSelector:
896 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000897 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000898 break;
899 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000900 Data = Name.getCXXOverloadedOperator();
901 break;
902 case DeclarationName::CXXLiteralOperatorName:
903 Data = (uint64_t)Name.getCXXLiteralIdentifier();
904 break;
905 case DeclarationName::CXXConstructorName:
906 case DeclarationName::CXXDestructorName:
907 case DeclarationName::CXXConversionFunctionName:
908 case DeclarationName::CXXUsingDirective:
909 Data = 0;
910 break;
911 }
912}
913
914unsigned DeclarationNameKey::getHash() const {
915 llvm::FoldingSetNodeID ID;
916 ID.AddInteger(Kind);
917
918 switch (Kind) {
919 case DeclarationName::Identifier:
920 case DeclarationName::CXXLiteralOperatorName:
921 ID.AddString(((IdentifierInfo*)Data)->getName());
922 break;
923 case DeclarationName::ObjCZeroArgSelector:
924 case DeclarationName::ObjCOneArgSelector:
925 case DeclarationName::ObjCMultiArgSelector:
926 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
927 break;
928 case DeclarationName::CXXOperatorName:
929 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 break;
931 case DeclarationName::CXXConstructorName:
932 case DeclarationName::CXXDestructorName:
933 case DeclarationName::CXXConversionFunctionName:
934 case DeclarationName::CXXUsingDirective:
935 break;
936 }
937
938 return ID.ComputeHash();
939}
940
Richard Smithd88a7f12015-09-01 20:35:42 +0000941ModuleFile *
942ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
943 using namespace llvm::support;
944 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
945 return Reader.getLocalModuleFile(F, ModuleFileID);
946}
947
Guy Benyei11169dd2012-12-18 14:30:41 +0000948std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000949ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000950 using namespace llvm::support;
951 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
952 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 return std::make_pair(KeyLen, DataLen);
954}
955
Richard Smitha06c7e62015-08-26 23:55:49 +0000956ASTDeclContextNameLookupTrait::internal_key_type
957ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000959
Richard Smitha06c7e62015-08-26 23:55:49 +0000960 auto Kind = (DeclarationName::NameKind)*d++;
961 uint64_t Data;
962 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000964 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000965 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 break;
967 case DeclarationName::ObjCZeroArgSelector:
968 case DeclarationName::ObjCOneArgSelector:
969 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000970 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000971 (uint64_t)Reader.getLocalSelector(
972 F, endian::readNext<uint32_t, little, unaligned>(
973 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 break;
975 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000976 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 break;
978 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000979 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000980 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 break;
982 case DeclarationName::CXXConstructorName:
983 case DeclarationName::CXXDestructorName:
984 case DeclarationName::CXXConversionFunctionName:
985 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000986 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 break;
988 }
989
Richard Smitha06c7e62015-08-26 23:55:49 +0000990 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000991}
992
Richard Smithd88a7f12015-09-01 20:35:42 +0000993void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
994 const unsigned char *d,
995 unsigned DataLen,
996 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000997 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000998 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
999 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1000 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001002}
1003
Richard Smith0f4e2c42015-08-06 04:23:48 +00001004bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1005 BitstreamCursor &Cursor,
1006 uint64_t Offset,
1007 DeclContext *DC) {
1008 assert(Offset != 0);
1009
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001011 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001012
Richard Smith0f4e2c42015-08-06 04:23:48 +00001013 RecordData Record;
1014 StringRef Blob;
1015 unsigned Code = Cursor.ReadCode();
1016 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1017 if (RecCode != DECL_CONTEXT_LEXICAL) {
1018 Error("Expected lexical block");
1019 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 }
1021
Richard Smith82f8fcd2015-08-06 22:07:25 +00001022 assert(!isa<TranslationUnitDecl>(DC) &&
1023 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001024 // If we are handling a C++ class template instantiation, we can see multiple
1025 // lexical updates for the same record. It's important that we select only one
1026 // of them, so that field numbering works properly. Just pick the first one we
1027 // see.
1028 auto &Lex = LexicalDecls[DC];
1029 if (!Lex.first) {
1030 Lex = std::make_pair(
1031 &M, llvm::makeArrayRef(
1032 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1033 Blob.data()),
1034 Blob.size() / 4));
1035 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001036 DC->setHasExternalLexicalStorage(true);
1037 return false;
1038}
Guy Benyei11169dd2012-12-18 14:30:41 +00001039
Richard Smith0f4e2c42015-08-06 04:23:48 +00001040bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1041 BitstreamCursor &Cursor,
1042 uint64_t Offset,
1043 DeclID ID) {
1044 assert(Offset != 0);
1045
1046 SavedStreamPosition SavedPosition(Cursor);
1047 Cursor.JumpToBit(Offset);
1048
1049 RecordData Record;
1050 StringRef Blob;
1051 unsigned Code = Cursor.ReadCode();
1052 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1053 if (RecCode != DECL_CONTEXT_VISIBLE) {
1054 Error("Expected visible lookup table block");
1055 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 }
1057
Richard Smith0f4e2c42015-08-06 04:23:48 +00001058 // We can't safely determine the primary context yet, so delay attaching the
1059 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001060 auto *Data = (const unsigned char*)Blob.data();
1061 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 return false;
1063}
1064
1065void ASTReader::Error(StringRef Msg) {
1066 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001067 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1068 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001069 Diag(diag::note_module_cache_path)
1070 << PP.getHeaderSearchInfo().getModuleCachePath();
1071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001072}
1073
1074void ASTReader::Error(unsigned DiagID,
1075 StringRef Arg1, StringRef Arg2) {
1076 if (Diags.isDiagnosticInFlight())
1077 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1078 else
1079 Diag(DiagID) << Arg1 << Arg2;
1080}
1081
1082//===----------------------------------------------------------------------===//
1083// Source Manager Deserialization
1084//===----------------------------------------------------------------------===//
1085
1086/// \brief Read the line table in the source manager block.
1087/// \returns true if there was an error.
1088bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001089 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001090 unsigned Idx = 0;
1091 LineTableInfo &LineTable = SourceMgr.getLineTable();
1092
1093 // Parse the file names
1094 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001095 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001097 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1099 }
Richard Smith63078492015-09-01 07:41:55 +00001100 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101
1102 // Parse the line entries
1103 std::vector<LineEntry> Entries;
1104 while (Idx < Record.size()) {
1105 int FID = Record[Idx++];
1106 assert(FID >= 0 && "Serialized line entries for non-local file.");
1107 // Remap FileID from 1-based old view.
1108 FID += F.SLocEntryBaseID - 1;
1109
1110 // Extract the line entries
1111 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001112 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 Entries.clear();
1114 Entries.reserve(NumEntries);
1115 for (unsigned I = 0; I != NumEntries; ++I) {
1116 unsigned FileOffset = Record[Idx++];
1117 unsigned LineNo = Record[Idx++];
1118 int FilenameID = FileIDs[Record[Idx++]];
1119 SrcMgr::CharacteristicKind FileKind
1120 = (SrcMgr::CharacteristicKind)Record[Idx++];
1121 unsigned IncludeOffset = Record[Idx++];
1122 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1123 FileKind, IncludeOffset));
1124 }
1125 LineTable.AddEntry(FileID::get(FID), Entries);
1126 }
1127
1128 return false;
1129}
1130
1131/// \brief Read a source manager block
1132bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1133 using namespace SrcMgr;
1134
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001135 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001136
1137 // Set the source-location entry cursor to the current position in
1138 // the stream. This cursor will be used to read the contents of the
1139 // source manager block initially, and then lazily read
1140 // source-location entries as needed.
1141 SLocEntryCursor = F.Stream;
1142
1143 // The stream itself is going to skip over the source manager block.
1144 if (F.Stream.SkipBlock()) {
1145 Error("malformed block record in AST file");
1146 return true;
1147 }
1148
1149 // Enter the source manager block.
1150 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1151 Error("malformed source manager block record in AST file");
1152 return true;
1153 }
1154
1155 RecordData Record;
1156 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001157 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1158
1159 switch (E.Kind) {
1160 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1161 case llvm::BitstreamEntry::Error:
1162 Error("malformed block record in AST file");
1163 return true;
1164 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001166 case llvm::BitstreamEntry::Record:
1167 // The interesting case.
1168 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001170
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001173 StringRef Blob;
1174 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 default: // Default behavior: ignore.
1176 break;
1177
1178 case SM_SLOC_FILE_ENTRY:
1179 case SM_SLOC_BUFFER_ENTRY:
1180 case SM_SLOC_EXPANSION_ENTRY:
1181 // Once we hit one of the source location entries, we're done.
1182 return false;
1183 }
1184 }
1185}
1186
1187/// \brief If a header file is not found at the path that we expect it to be
1188/// and the PCH file was moved from its original location, try to resolve the
1189/// file by assuming that header+PCH were moved together and the header is in
1190/// the same place relative to the PCH.
1191static std::string
1192resolveFileRelativeToOriginalDir(const std::string &Filename,
1193 const std::string &OriginalDir,
1194 const std::string &CurrDir) {
1195 assert(OriginalDir != CurrDir &&
1196 "No point trying to resolve the file if the PCH dir didn't change");
1197 using namespace llvm::sys;
1198 SmallString<128> filePath(Filename);
1199 fs::make_absolute(filePath);
1200 assert(path::is_absolute(OriginalDir));
1201 SmallString<128> currPCHPath(CurrDir);
1202
1203 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1204 fileDirE = path::end(path::parent_path(filePath));
1205 path::const_iterator origDirI = path::begin(OriginalDir),
1206 origDirE = path::end(OriginalDir);
1207 // Skip the common path components from filePath and OriginalDir.
1208 while (fileDirI != fileDirE && origDirI != origDirE &&
1209 *fileDirI == *origDirI) {
1210 ++fileDirI;
1211 ++origDirI;
1212 }
1213 for (; origDirI != origDirE; ++origDirI)
1214 path::append(currPCHPath, "..");
1215 path::append(currPCHPath, fileDirI, fileDirE);
1216 path::append(currPCHPath, path::filename(Filename));
1217 return currPCHPath.str();
1218}
1219
1220bool ASTReader::ReadSLocEntry(int ID) {
1221 if (ID == 0)
1222 return false;
1223
1224 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1225 Error("source location entry ID out-of-range for AST file");
1226 return true;
1227 }
1228
Richard Smithaada85c2016-02-06 02:06:43 +00001229 // Local helper to read the (possibly-compressed) buffer data following the
1230 // entry record.
1231 auto ReadBuffer = [this](
1232 BitstreamCursor &SLocEntryCursor,
1233 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1234 RecordData Record;
1235 StringRef Blob;
1236 unsigned Code = SLocEntryCursor.ReadCode();
1237 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1238
1239 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1240 SmallString<0> Uncompressed;
1241 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1242 llvm::zlib::StatusOK) {
1243 Error("could not decompress embedded file contents");
1244 return nullptr;
1245 }
1246 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1247 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1248 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1249 } else {
1250 Error("AST record has invalid code");
1251 return nullptr;
1252 }
1253 };
1254
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1256 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001257 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 unsigned BaseOffset = F->SLocEntryBaseOffset;
1259
1260 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001261 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1262 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 Error("incorrectly-formatted source location entry in AST file");
1264 return true;
1265 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001266
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001268 StringRef Blob;
1269 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 default:
1271 Error("incorrectly-formatted source location entry in AST file");
1272 return true;
1273
1274 case SM_SLOC_FILE_ENTRY: {
1275 // We will detect whether a file changed and return 'Failure' for it, but
1276 // we will also try to fail gracefully by setting up the SLocEntry.
1277 unsigned InputID = Record[4];
1278 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001279 const FileEntry *File = IF.getFile();
1280 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001281
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001282 // Note that we only check if a File was returned. If it was out-of-date
1283 // we have complained but we will continue creating a FileID to recover
1284 // gracefully.
1285 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 return true;
1287
1288 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1289 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1290 // This is the module's main file.
1291 IncludeLoc = getImportLocation(F);
1292 }
1293 SrcMgr::CharacteristicKind
1294 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1295 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1296 ID, BaseOffset + Record[0]);
1297 SrcMgr::FileInfo &FileInfo =
1298 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1299 FileInfo.NumCreatedFIDs = Record[5];
1300 if (Record[3])
1301 FileInfo.setHasLineDirectives();
1302
1303 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1304 unsigned NumFileDecls = Record[7];
1305 if (NumFileDecls) {
1306 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1307 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1308 NumFileDecls));
1309 }
Richard Smithaada85c2016-02-06 02:06:43 +00001310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 const SrcMgr::ContentCache *ContentCache
1312 = SourceMgr.getOrCreateContentCache(File,
1313 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1314 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001315 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1316 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001317 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1318 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001320 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 }
1322
1323 break;
1324 }
1325
1326 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001327 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 unsigned Offset = Record[0];
1329 SrcMgr::CharacteristicKind
1330 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1331 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001332 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 IncludeLoc = getImportLocation(F);
1334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001335
Richard Smithaada85c2016-02-06 02:06:43 +00001336 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1337 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001339 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001340 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 break;
1342 }
1343
1344 case SM_SLOC_EXPANSION_ENTRY: {
1345 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1346 SourceMgr.createExpansionLoc(SpellingLoc,
1347 ReadSourceLocation(*F, Record[2]),
1348 ReadSourceLocation(*F, Record[3]),
1349 Record[4],
1350 ID,
1351 BaseOffset + Record[0]);
1352 break;
1353 }
1354 }
1355
1356 return false;
1357}
1358
1359std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1360 if (ID == 0)
1361 return std::make_pair(SourceLocation(), "");
1362
1363 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1364 Error("source location entry ID out-of-range for AST file");
1365 return std::make_pair(SourceLocation(), "");
1366 }
1367
1368 // Find which module file this entry lands in.
1369 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001370 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 return std::make_pair(SourceLocation(), "");
1372
1373 // FIXME: Can we map this down to a particular submodule? That would be
1374 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001375 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001376}
1377
1378/// \brief Find the location where the module F is imported.
1379SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1380 if (F->ImportLoc.isValid())
1381 return F->ImportLoc;
1382
1383 // Otherwise we have a PCH. It's considered to be "imported" at the first
1384 // location of its includer.
1385 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001386 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001387 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001388 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 return F->ImportedBy[0]->FirstLoc;
1391}
1392
1393/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1394/// specified cursor. Read the abbreviations that are at the top of the block
1395/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001396bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001397 if (Cursor.EnterSubBlock(BlockID))
1398 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001399
1400 while (true) {
1401 uint64_t Offset = Cursor.GetCurrentBitNo();
1402 unsigned Code = Cursor.ReadCode();
1403
1404 // We expect all abbrevs to be at the start of the block.
1405 if (Code != llvm::bitc::DEFINE_ABBREV) {
1406 Cursor.JumpToBit(Offset);
1407 return false;
1408 }
1409 Cursor.ReadAbbrevRecord();
1410 }
1411}
1412
Richard Smithe40f2ba2013-08-07 21:41:30 +00001413Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001414 unsigned &Idx) {
1415 Token Tok;
1416 Tok.startToken();
1417 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1418 Tok.setLength(Record[Idx++]);
1419 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1420 Tok.setIdentifierInfo(II);
1421 Tok.setKind((tok::TokenKind)Record[Idx++]);
1422 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1423 return Tok;
1424}
1425
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001426MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001427 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001428
1429 // Keep track of where we are in the stream, then jump back there
1430 // after reading this macro.
1431 SavedStreamPosition SavedPosition(Stream);
1432
1433 Stream.JumpToBit(Offset);
1434 RecordData Record;
1435 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001436 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001439 // Advance to the next record, but if we get to the end of the block, don't
1440 // pop it (removing all the abbreviations from the cursor) since we want to
1441 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001442 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001443 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1444
1445 switch (Entry.Kind) {
1446 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1447 case llvm::BitstreamEntry::Error:
1448 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001449 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001450 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001451 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001452 case llvm::BitstreamEntry::Record:
1453 // The interesting case.
1454 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 }
1456
1457 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 Record.clear();
1459 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001460 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001462 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001463 case PP_MACRO_DIRECTIVE_HISTORY:
1464 return Macro;
1465
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 case PP_MACRO_OBJECT_LIKE:
1467 case PP_MACRO_FUNCTION_LIKE: {
1468 // If we already have a macro, that means that we've hit the end
1469 // of the definition of the macro we were looking for. We're
1470 // done.
1471 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001472 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001473
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001474 unsigned NextIndex = 1; // Skip identifier ID.
1475 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001476 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001477 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001478 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001480 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Guy Benyei11169dd2012-12-18 14:30:41 +00001482 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1483 // Decode function-like macro info.
1484 bool isC99VarArgs = Record[NextIndex++];
1485 bool isGNUVarArgs = Record[NextIndex++];
1486 bool hasCommaPasting = Record[NextIndex++];
1487 MacroArgs.clear();
1488 unsigned NumArgs = Record[NextIndex++];
1489 for (unsigned i = 0; i != NumArgs; ++i)
1490 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1491
1492 // Install function-like macro info.
1493 MI->setIsFunctionLike();
1494 if (isC99VarArgs) MI->setIsC99Varargs();
1495 if (isGNUVarArgs) MI->setIsGNUVarargs();
1496 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001497 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 }
1499
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 // Remember that we saw this macro last so that we add the tokens that
1501 // form its body to it.
1502 Macro = MI;
1503
1504 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1505 Record[NextIndex]) {
1506 // We have a macro definition. Register the association
1507 PreprocessedEntityID
1508 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1509 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001510 PreprocessingRecord::PPEntityID PPID =
1511 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1512 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1513 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001514 if (PPDef)
1515 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 }
1517
1518 ++NumMacrosRead;
1519 break;
1520 }
1521
1522 case PP_TOKEN: {
1523 // If we see a TOKEN before a PP_MACRO_*, then the file is
1524 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001525 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001526
John McCallf413f5e2013-05-03 00:10:13 +00001527 unsigned Idx = 0;
1528 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 Macro->AddTokenToBody(Tok);
1530 break;
1531 }
1532 }
1533 }
1534}
1535
1536PreprocessedEntityID
1537ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1538 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1539 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1540 assert(I != M.PreprocessedEntityRemap.end()
1541 && "Invalid index into preprocessed entity index remap");
1542
1543 return LocalID + I->second;
1544}
1545
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001546unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1547 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001548}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001551HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001552 internal_key_type ikey = {FE->getSize(),
1553 M.HasTimestamps ? FE->getModificationTime() : 0,
1554 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555 return ikey;
1556}
Guy Benyei11169dd2012-12-18 14:30:41 +00001557
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001558bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001559 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 return false;
1561
Richard Smith7ed1bc92014-12-05 22:42:13 +00001562 if (llvm::sys::path::is_absolute(a.Filename) &&
1563 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001564 return true;
1565
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001567 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001568 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1569 if (!Key.Imported)
1570 return FileMgr.getFile(Key.Filename);
1571
1572 std::string Resolved = Key.Filename;
1573 Reader.ResolveImportedPath(M, Resolved);
1574 return FileMgr.getFile(Resolved);
1575 };
1576
1577 const FileEntry *FEA = GetFile(a);
1578 const FileEntry *FEB = GetFile(b);
1579 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001580}
1581
1582std::pair<unsigned, unsigned>
1583HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001584 using namespace llvm::support;
1585 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001587 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001588}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001589
1590HeaderFileInfoTrait::internal_key_type
1591HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001592 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001593 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001594 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1595 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001597 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001598 return ikey;
1599}
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001602HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 unsigned DataLen) {
1604 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001605 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 HeaderFileInfo HFI;
1607 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001608 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1609 HFI.isImport |= (Flags >> 4) & 0x01;
1610 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1611 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001613 // FIXME: Find a better way to handle this. Maybe just store a
1614 // "has been included" flag?
1615 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1616 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001617 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1618 M, endian::readNext<uint32_t, little, unaligned>(d));
1619 if (unsigned FrameworkOffset =
1620 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 // The framework offset is 1 greater than the actual offset,
1622 // since 0 is used as an indicator for "no framework name".
1623 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1624 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1625 }
Richard Smith386bb072015-08-18 23:42:23 +00001626
1627 assert((End - d) % 4 == 0 &&
1628 "Wrong data length in HeaderFileInfo deserialization");
1629 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001630 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001631 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1632 LocalSMID >>= 2;
1633
1634 // This header is part of a module. Associate it with the module to enable
1635 // implicit module import.
1636 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1637 Module *Mod = Reader.getSubmodule(GlobalSMID);
1638 FileManager &FileMgr = Reader.getFileManager();
1639 ModuleMap &ModMap =
1640 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1641
1642 std::string Filename = key.Filename;
1643 if (key.Imported)
1644 Reader.ResolveImportedPath(M, Filename);
1645 // FIXME: This is not always the right filename-as-written, but we're not
1646 // going to use this information to rebuild the module, so it doesn't make
1647 // a lot of difference.
1648 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001649 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1650 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001651 }
1652
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 // This HeaderFileInfo was externally loaded.
1654 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001655 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 return HFI;
1657}
1658
Richard Smithd7329392015-04-21 21:46:32 +00001659void ASTReader::addPendingMacro(IdentifierInfo *II,
1660 ModuleFile *M,
1661 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001662 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1663 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001664}
1665
1666void ASTReader::ReadDefinedMacros() {
1667 // Note that we are loading defined macros.
1668 Deserializing Macros(this);
1669
Pete Cooper57d3f142015-07-30 17:22:52 +00001670 for (auto &I : llvm::reverse(ModuleMgr)) {
1671 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001672
1673 // If there was no preprocessor block, skip this file.
1674 if (!MacroCursor.getBitStreamReader())
1675 continue;
1676
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001677 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001678 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001679
1680 RecordData Record;
1681 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001682 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1683
1684 switch (E.Kind) {
1685 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1686 case llvm::BitstreamEntry::Error:
1687 Error("malformed block record in AST file");
1688 return;
1689 case llvm::BitstreamEntry::EndBlock:
1690 goto NextCursor;
1691
1692 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001693 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001694 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001695 default: // Default behavior: ignore.
1696 break;
1697
1698 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001699 case PP_MACRO_FUNCTION_LIKE: {
1700 IdentifierInfo *II = getLocalIdentifier(*I, Record[0]);
1701 if (II->isOutOfDate())
1702 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001703 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001704 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001705
1706 case PP_TOKEN:
1707 // Ignore tokens.
1708 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 break;
1711 }
1712 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001713 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 }
1715}
1716
1717namespace {
1718 /// \brief Visitor class used to look up identifirs in an AST file.
1719 class IdentifierLookupVisitor {
1720 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001721 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001723 unsigned &NumIdentifierLookups;
1724 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001726
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001728 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1729 unsigned &NumIdentifierLookups,
1730 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001731 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1732 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001733 NumIdentifierLookups(NumIdentifierLookups),
1734 NumIdentifierLookupHits(NumIdentifierLookupHits),
1735 Found()
1736 {
1737 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001738
1739 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001741 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001743
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 ASTIdentifierLookupTable *IdTable
1745 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1746 if (!IdTable)
1747 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001748
1749 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001750 Found);
1751 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001752 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001753 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 if (Pos == IdTable->end())
1755 return false;
1756
1757 // Dereferencing the iterator has the effect of building the
1758 // IdentifierInfo node and populating it with the various
1759 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001760 ++NumIdentifierLookupHits;
1761 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 return true;
1763 }
1764
1765 // \brief Retrieve the identifier info found within the module
1766 // files.
1767 IdentifierInfo *getIdentifierInfo() const { return Found; }
1768 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001769}
Guy Benyei11169dd2012-12-18 14:30:41 +00001770
1771void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1772 // Note that we are loading an identifier.
1773 Deserializing AnIdentifier(this);
1774
1775 unsigned PriorGeneration = 0;
1776 if (getContext().getLangOpts().Modules)
1777 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001778
1779 // If there is a global index, look there first to determine which modules
1780 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001781 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001782 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001783 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001784 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1785 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001786 }
1787 }
1788
Douglas Gregor7211ac12013-01-25 23:32:03 +00001789 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001790 NumIdentifierLookups,
1791 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001792 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 markIdentifierUpToDate(&II);
1794}
1795
1796void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1797 if (!II)
1798 return;
1799
1800 II->setOutOfDate(false);
1801
1802 // Update the generation for this identifier.
1803 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001804 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001805}
1806
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1808 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001809 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810
1811 BitstreamCursor &Cursor = M.MacroCursor;
1812 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001813 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001814
Richard Smith713369b2015-04-23 20:40:50 +00001815 struct ModuleMacroRecord {
1816 SubmoduleID SubModID;
1817 MacroInfo *MI;
1818 SmallVector<SubmoduleID, 8> Overrides;
1819 };
1820 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001821
Richard Smithd7329392015-04-21 21:46:32 +00001822 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1823 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1824 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001826 while (true) {
1827 llvm::BitstreamEntry Entry =
1828 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1829 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1830 Error("malformed block record in AST file");
1831 return;
1832 }
1833
1834 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001835 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001836 case PP_MACRO_DIRECTIVE_HISTORY:
1837 break;
1838
1839 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001840 ModuleMacros.push_back(ModuleMacroRecord());
1841 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001842 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1843 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001844 for (int I = 2, N = Record.size(); I != N; ++I)
1845 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001846 continue;
1847 }
1848
1849 default:
1850 Error("malformed block record in AST file");
1851 return;
1852 }
1853
1854 // We found the macro directive history; that's the last record
1855 // for this macro.
1856 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001857 }
1858
Richard Smithd7329392015-04-21 21:46:32 +00001859 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001860 {
1861 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001862 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001863 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001864 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001865 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001866 Module *Mod = getSubmodule(ModID);
1867 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001868 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001869 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001870 }
1871
1872 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001873 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001874 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001875 }
1876 }
1877
1878 // Don't read the directive history for a module; we don't have anywhere
1879 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001880 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001881 return;
1882
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001883 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001884 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001885 unsigned Idx = 0, N = Record.size();
1886 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001887 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001888 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001889 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1890 switch (K) {
1891 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001892 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001893 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001894 break;
1895 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001896 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001897 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001898 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001899 }
1900 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001901 bool isPublic = Record[Idx++];
1902 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1903 break;
1904 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001905
1906 if (!Latest)
1907 Latest = MD;
1908 if (Earliest)
1909 Earliest->setPrevious(MD);
1910 Earliest = MD;
1911 }
1912
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001913 if (Latest)
1914 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001915}
1916
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001917ASTReader::InputFileInfo
1918ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001919 // Go find this input file.
1920 BitstreamCursor &Cursor = F.InputFilesCursor;
1921 SavedStreamPosition SavedPosition(Cursor);
1922 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1923
1924 unsigned Code = Cursor.ReadCode();
1925 RecordData Record;
1926 StringRef Blob;
1927
1928 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1929 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1930 "invalid record type for input file");
1931 (void)Result;
1932
1933 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001934 InputFileInfo R;
1935 R.StoredSize = static_cast<off_t>(Record[1]);
1936 R.StoredTime = static_cast<time_t>(Record[2]);
1937 R.Overridden = static_cast<bool>(Record[3]);
1938 R.Transient = static_cast<bool>(Record[4]);
1939 R.Filename = Blob;
1940 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001941 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001942}
1943
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001944InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 // If this ID is bogus, just return an empty input file.
1946 if (ID == 0 || ID > F.InputFilesLoaded.size())
1947 return InputFile();
1948
1949 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001950 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 return F.InputFilesLoaded[ID-1];
1952
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001953 if (F.InputFilesLoaded[ID-1].isNotFound())
1954 return InputFile();
1955
Guy Benyei11169dd2012-12-18 14:30:41 +00001956 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001957 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001958 SavedStreamPosition SavedPosition(Cursor);
1959 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1960
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001961 InputFileInfo FI = readInputFileInfo(F, ID);
1962 off_t StoredSize = FI.StoredSize;
1963 time_t StoredTime = FI.StoredTime;
1964 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001965 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001966 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001967
Richard Smitha8cfffa2015-11-26 02:04:16 +00001968 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00001969
1970 // If we didn't find the file, resolve it relative to the
1971 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001972 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001973 F.OriginalDir != CurrentDir) {
1974 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1975 F.OriginalDir,
1976 CurrentDir);
1977 if (!Resolved.empty())
1978 File = FileMgr.getFile(Resolved);
1979 }
1980
1981 // For an overridden file, create a virtual file with the stored
1982 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001983 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00001985
Craig Toppera13603a2014-05-22 05:54:18 +00001986 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 if (Complain) {
1988 std::string ErrorStr = "could not find file '";
1989 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001990 ErrorStr += "' referenced by AST file '";
1991 ErrorStr += F.FileName;
1992 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 // Record that we didn't find the file.
1996 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1997 return InputFile();
1998 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 // Check if there was a request to override the contents of the file
2001 // that was part of the precompiled header. Overridding such a file
2002 // can lead to problems when lexing using the source locations from the
2003 // PCH.
2004 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002005 // FIXME: Reject if the overrides are different.
2006 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 if (Complain)
2008 Error(diag::err_fe_pch_file_overridden, Filename);
2009 // After emitting the diagnostic, recover by disabling the override so
2010 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002011 //
2012 // FIXME: This recovery is just as broken as the original state; there may
2013 // be another precompiled module that's using the overridden contents, or
2014 // we might be half way through parsing it. Instead, we should treat the
2015 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 SM.disableFileContentsOverride(File);
2017 // The FileEntry is a virtual file entry with the size of the contents
2018 // that would override the original contents. Set it to the original's
2019 // size/time.
2020 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2021 StoredSize, StoredTime);
2022 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002023
Ben Langmuir198c1682014-03-07 07:27:49 +00002024 bool IsOutOfDate = false;
2025
2026 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002027 if (!Overridden && //
2028 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002029 (StoredTime && StoredTime != File->getModificationTime() &&
2030 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002031 )) {
2032 if (Complain) {
2033 // Build a list of the PCH imports that got us here (in reverse).
2034 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2035 while (ImportStack.back()->ImportedBy.size() > 0)
2036 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002037
Ben Langmuir198c1682014-03-07 07:27:49 +00002038 // The top-level PCH is stale.
2039 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2040 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002041
Ben Langmuir198c1682014-03-07 07:27:49 +00002042 // Print the import stack.
2043 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2044 Diag(diag::note_pch_required_by)
2045 << Filename << ImportStack[0]->FileName;
2046 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002047 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002048 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002049 }
2050
Ben Langmuir198c1682014-03-07 07:27:49 +00002051 if (!Diags.isDiagnosticInFlight())
2052 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002053 }
2054
Ben Langmuir198c1682014-03-07 07:27:49 +00002055 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002057 // FIXME: If the file is overridden and we've already opened it,
2058 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002059
Richard Smitha8cfffa2015-11-26 02:04:16 +00002060 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002061
2062 // Note that we've loaded this input file.
2063 F.InputFilesLoaded[ID-1] = IF;
2064 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002065}
2066
Richard Smith7ed1bc92014-12-05 22:42:13 +00002067/// \brief If we are loading a relocatable PCH or module file, and the filename
2068/// is not an absolute path, add the system or module root to the beginning of
2069/// the file name.
2070void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2071 // Resolve relative to the base directory, if we have one.
2072 if (!M.BaseDirectory.empty())
2073 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002074}
2075
Richard Smith7ed1bc92014-12-05 22:42:13 +00002076void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2078 return;
2079
Richard Smith7ed1bc92014-12-05 22:42:13 +00002080 SmallString<128> Buffer;
2081 llvm::sys::path::append(Buffer, Prefix, Filename);
2082 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002083}
2084
Richard Smith0f99d6a2015-08-09 08:48:41 +00002085static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2086 switch (ARR) {
2087 case ASTReader::Failure: return true;
2088 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2089 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2090 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2091 case ASTReader::ConfigurationMismatch:
2092 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2093 case ASTReader::HadErrors: return true;
2094 case ASTReader::Success: return false;
2095 }
2096
2097 llvm_unreachable("unknown ASTReadResult");
2098}
2099
Richard Smith0516b182015-09-08 19:40:14 +00002100ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2101 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2102 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002103 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002104 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2105 return Failure;
2106
2107 // Read all of the records in the options block.
2108 RecordData Record;
2109 ASTReadResult Result = Success;
2110 while (1) {
2111 llvm::BitstreamEntry Entry = Stream.advance();
2112
2113 switch (Entry.Kind) {
2114 case llvm::BitstreamEntry::Error:
2115 case llvm::BitstreamEntry::SubBlock:
2116 return Failure;
2117
2118 case llvm::BitstreamEntry::EndBlock:
2119 return Result;
2120
2121 case llvm::BitstreamEntry::Record:
2122 // The interesting case.
2123 break;
2124 }
2125
2126 // Read and process a record.
2127 Record.clear();
2128 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2129 case LANGUAGE_OPTIONS: {
2130 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2131 if (ParseLanguageOptions(Record, Complain, Listener,
2132 AllowCompatibleConfigurationMismatch))
2133 Result = ConfigurationMismatch;
2134 break;
2135 }
2136
2137 case TARGET_OPTIONS: {
2138 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2139 if (ParseTargetOptions(Record, Complain, Listener,
2140 AllowCompatibleConfigurationMismatch))
2141 Result = ConfigurationMismatch;
2142 break;
2143 }
2144
2145 case DIAGNOSTIC_OPTIONS: {
2146 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002147 if (ValidateDiagnosticOptions &&
2148 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002149 ParseDiagnosticOptions(Record, Complain, Listener))
2150 return OutOfDate;
2151 break;
2152 }
2153
2154 case FILE_SYSTEM_OPTIONS: {
2155 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2156 if (!AllowCompatibleConfigurationMismatch &&
2157 ParseFileSystemOptions(Record, Complain, Listener))
2158 Result = ConfigurationMismatch;
2159 break;
2160 }
2161
2162 case HEADER_SEARCH_OPTIONS: {
2163 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2164 if (!AllowCompatibleConfigurationMismatch &&
2165 ParseHeaderSearchOptions(Record, Complain, Listener))
2166 Result = ConfigurationMismatch;
2167 break;
2168 }
2169
2170 case PREPROCESSOR_OPTIONS:
2171 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2172 if (!AllowCompatibleConfigurationMismatch &&
2173 ParsePreprocessorOptions(Record, Complain, Listener,
2174 SuggestedPredefines))
2175 Result = ConfigurationMismatch;
2176 break;
2177 }
2178 }
2179}
2180
Guy Benyei11169dd2012-12-18 14:30:41 +00002181ASTReader::ASTReadResult
2182ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002183 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002184 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002186 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002187 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002188
2189 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2190 Error("malformed block record in AST file");
2191 return Failure;
2192 }
2193
2194 // Read all of the records and blocks in the control block.
2195 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002196 unsigned NumInputs = 0;
2197 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002198 while (1) {
2199 llvm::BitstreamEntry Entry = Stream.advance();
2200
2201 switch (Entry.Kind) {
2202 case llvm::BitstreamEntry::Error:
2203 Error("malformed block record in AST file");
2204 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002205 case llvm::BitstreamEntry::EndBlock: {
2206 // Validate input files.
2207 const HeaderSearchOptions &HSOpts =
2208 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002209
Richard Smitha1825302014-10-23 22:18:29 +00002210 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002211 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2212 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002213 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2214 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002216
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002217 // If we are reading a module, we will create a verification timestamp,
2218 // so we verify all input files. Otherwise, verify only user input
2219 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002220
2221 unsigned N = NumUserInputs;
2222 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002223 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002224 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002225 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002226 N = NumInputs;
2227
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002228 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002229 InputFile IF = getInputFile(F, I+1, Complain);
2230 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002232 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002234
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002235 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002236 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002237
Ben Langmuircb69b572014-03-07 06:40:32 +00002238 if (Listener && Listener->needsInputFileVisitation()) {
2239 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2240 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002241 for (unsigned I = 0; I < N; ++I) {
2242 bool IsSystem = I >= NumUserInputs;
2243 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002244 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002245 F.Kind == MK_ExplicitModule ||
2246 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002247 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002248 }
2249
Richard Smith8a308ec2015-11-05 00:54:55 +00002250 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002251 }
2252
Chris Lattnere7b154b2013-01-19 21:39:22 +00002253 case llvm::BitstreamEntry::SubBlock:
2254 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 case INPUT_FILES_BLOCK_ID:
2256 F.InputFilesCursor = Stream;
2257 if (Stream.SkipBlock() || // Skip with the main cursor
2258 // Read the abbreviations
2259 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2260 Error("malformed block record in AST file");
2261 return Failure;
2262 }
2263 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002264
2265 case OPTIONS_BLOCK_ID:
2266 // If we're reading the first module for this group, check its options
2267 // are compatible with ours. For modules it imports, no further checking
2268 // is required, because we checked them when we built it.
2269 if (Listener && !ImportedBy) {
2270 // Should we allow the configuration of the module file to differ from
2271 // the configuration of the current translation unit in a compatible
2272 // way?
2273 //
2274 // FIXME: Allow this for files explicitly specified with -include-pch.
2275 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002276 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002277 const HeaderSearchOptions &HSOpts =
2278 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002279
Richard Smith8a308ec2015-11-05 00:54:55 +00002280 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2281 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002282 *Listener, SuggestedPredefines,
2283 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002284 if (Result == Failure) {
2285 Error("malformed block record in AST file");
2286 return Result;
2287 }
2288
Richard Smith8a308ec2015-11-05 00:54:55 +00002289 if (DisableValidation ||
2290 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2291 Result = Success;
2292
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002293 // If we can't load the module, exit early since we likely
2294 // will rebuild the module anyway. The stream may be in the
2295 // middle of a block.
2296 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002297 return Result;
2298 } else if (Stream.SkipBlock()) {
2299 Error("malformed block record in AST file");
2300 return Failure;
2301 }
2302 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002303
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002305 if (Stream.SkipBlock()) {
2306 Error("malformed block record in AST file");
2307 return Failure;
2308 }
2309 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002311
2312 case llvm::BitstreamEntry::Record:
2313 // The interesting case.
2314 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 }
2316
2317 // Read and process a record.
2318 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002319 StringRef Blob;
2320 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002321 case METADATA: {
2322 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2323 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002324 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2325 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 return VersionMismatch;
2327 }
2328
Richard Smithe75ee0f2015-08-17 07:13:32 +00002329 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2331 Diag(diag::err_pch_with_compiler_errors);
2332 return HadErrors;
2333 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002334 if (hasErrors) {
2335 Diags.ErrorOccurred = true;
2336 Diags.UncompilableErrorOccurred = true;
2337 Diags.UnrecoverableErrorOccurred = true;
2338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002339
2340 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002341 // Relative paths in a relocatable PCH are relative to our sysroot.
2342 if (F.RelocatablePCH)
2343 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002344
Richard Smithe75ee0f2015-08-17 07:13:32 +00002345 F.HasTimestamps = Record[5];
2346
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002348 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2350 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002351 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 return VersionMismatch;
2353 }
2354 break;
2355 }
2356
Ben Langmuir487ea142014-10-23 18:05:36 +00002357 case SIGNATURE:
2358 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2359 F.Signature = Record[0];
2360 break;
2361
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 case IMPORTS: {
2363 // Load each of the imported PCH files.
2364 unsigned Idx = 0, N = Record.size();
2365 while (Idx < N) {
2366 // Read information about the AST file.
2367 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2368 // The import location will be the local one for now; we will adjust
2369 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002370 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002372 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002373 off_t StoredSize = (off_t)Record[Idx++];
2374 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002375 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002376 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002377
Richard Smith0f99d6a2015-08-09 08:48:41 +00002378 // If our client can't cope with us being out of date, we can't cope with
2379 // our dependency being missing.
2380 unsigned Capabilities = ClientLoadCapabilities;
2381 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2382 Capabilities &= ~ARR_Missing;
2383
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002385 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2386 Loaded, StoredSize, StoredModTime,
2387 StoredSignature, Capabilities);
2388
2389 // If we diagnosed a problem, produce a backtrace.
2390 if (isDiagnosedResult(Result, Capabilities))
2391 Diag(diag::note_module_file_imported_by)
2392 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2393
2394 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 case Failure: return Failure;
2396 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002397 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case OutOfDate: return OutOfDate;
2399 case VersionMismatch: return VersionMismatch;
2400 case ConfigurationMismatch: return ConfigurationMismatch;
2401 case HadErrors: return HadErrors;
2402 case Success: break;
2403 }
2404 }
2405 break;
2406 }
2407
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 case ORIGINAL_FILE:
2409 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002410 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002412 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 break;
2414
2415 case ORIGINAL_FILE_ID:
2416 F.OriginalSourceFileID = FileID::get(Record[0]);
2417 break;
2418
2419 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002420 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 break;
2422
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002423 case MODULE_NAME:
2424 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002425 if (Listener)
2426 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002427 break;
2428
Richard Smith223d3f22014-12-06 03:21:08 +00002429 case MODULE_DIRECTORY: {
2430 assert(!F.ModuleName.empty() &&
2431 "MODULE_DIRECTORY found before MODULE_NAME");
2432 // If we've already loaded a module map file covering this module, we may
2433 // have a better path for it (relative to the current build).
2434 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2435 if (M && M->Directory) {
2436 // If we're implicitly loading a module, the base directory can't
2437 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002438 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002439 const DirectoryEntry *BuildDir =
2440 PP.getFileManager().getDirectory(Blob);
2441 if (!BuildDir || BuildDir != M->Directory) {
2442 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2443 Diag(diag::err_imported_module_relocated)
2444 << F.ModuleName << Blob << M->Directory->getName();
2445 return OutOfDate;
2446 }
2447 }
2448 F.BaseDirectory = M->Directory->getName();
2449 } else {
2450 F.BaseDirectory = Blob;
2451 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002452 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002453 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002454
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002455 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002456 if (ASTReadResult Result =
2457 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2458 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002459 break;
2460
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002461 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002462 NumInputs = Record[0];
2463 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002464 F.InputFileOffsets =
2465 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002466 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 break;
2468 }
2469 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002470}
2471
Ben Langmuir2c9af442014-04-10 17:57:43 +00002472ASTReader::ASTReadResult
2473ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002474 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002475
2476 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2477 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002478 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 }
2480
2481 // Read all of the records and blocks for the AST file.
2482 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002483 while (1) {
2484 llvm::BitstreamEntry Entry = Stream.advance();
2485
2486 switch (Entry.Kind) {
2487 case llvm::BitstreamEntry::Error:
2488 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002489 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002490 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002491 // Outside of C++, we do not store a lookup map for the translation unit.
2492 // Instead, mark it as needing a lookup map to be built if this module
2493 // contains any declarations lexically within it (which it always does!).
2494 // This usually has no cost, since we very rarely need the lookup map for
2495 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002497 if (DC->hasExternalLexicalStorage() &&
2498 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002500
Ben Langmuir2c9af442014-04-10 17:57:43 +00002501 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002503 case llvm::BitstreamEntry::SubBlock:
2504 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 case DECLTYPES_BLOCK_ID:
2506 // We lazily load the decls block, but we want to set up the
2507 // DeclsCursor cursor to point into it. Clone our current bitcode
2508 // cursor to it, enter the block and read the abbrevs in that block.
2509 // With the main cursor, we just skip over it.
2510 F.DeclsCursor = Stream;
2511 if (Stream.SkipBlock() || // Skip with the main cursor.
2512 // Read the abbrevs.
2513 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2514 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002515 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 }
2517 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002518
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 case PREPROCESSOR_BLOCK_ID:
2520 F.MacroCursor = Stream;
2521 if (!PP.getExternalSource())
2522 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002523
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 if (Stream.SkipBlock() ||
2525 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2526 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002527 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 }
2529 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2530 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 case PREPROCESSOR_DETAIL_BLOCK_ID:
2533 F.PreprocessorDetailCursor = Stream;
2534 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002535 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002537 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002538 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002541 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2542
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 if (!PP.getPreprocessingRecord())
2544 PP.createPreprocessingRecord();
2545 if (!PP.getPreprocessingRecord()->getExternalSource())
2546 PP.getPreprocessingRecord()->SetExternalSource(*this);
2547 break;
2548
2549 case SOURCE_MANAGER_BLOCK_ID:
2550 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002551 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002555 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2556 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002560 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 if (Stream.SkipBlock() ||
2562 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2563 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002564 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 }
2566 CommentsCursors.push_back(std::make_pair(C, &F));
2567 break;
2568 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002569
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002571 if (Stream.SkipBlock()) {
2572 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002574 }
2575 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 }
2577 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002578
2579 case llvm::BitstreamEntry::Record:
2580 // The interesting case.
2581 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 }
2583
2584 // Read and process a record.
2585 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002586 StringRef Blob;
2587 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 default: // Default behavior: ignore.
2589 break;
2590
2591 case TYPE_OFFSET: {
2592 if (F.LocalNumTypes != 0) {
2593 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002594 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002596 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 F.LocalNumTypes = Record[0];
2598 unsigned LocalBaseTypeIndex = Record[1];
2599 F.BaseTypeIndex = getTotalNumTypes();
2600
2601 if (F.LocalNumTypes > 0) {
2602 // Introduce the global -> local mapping for types within this module.
2603 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2604
2605 // Introduce the local -> global mapping for types within this module.
2606 F.TypeRemap.insertOrReplace(
2607 std::make_pair(LocalBaseTypeIndex,
2608 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002609
2610 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612 break;
2613 }
2614
2615 case DECL_OFFSET: {
2616 if (F.LocalNumDecls != 0) {
2617 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002618 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002620 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 F.LocalNumDecls = Record[0];
2622 unsigned LocalBaseDeclID = Record[1];
2623 F.BaseDeclID = getTotalNumDecls();
2624
2625 if (F.LocalNumDecls > 0) {
2626 // Introduce the global -> local mapping for declarations within this
2627 // module.
2628 GlobalDeclMap.insert(
2629 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2630
2631 // Introduce the local -> global mapping for declarations within this
2632 // module.
2633 F.DeclRemap.insertOrReplace(
2634 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2635
2636 // Introduce the global -> local mapping for declarations within this
2637 // module.
2638 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002639
Ben Langmuir52ca6782014-10-20 16:27:32 +00002640 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 break;
2643 }
2644
2645 case TU_UPDATE_LEXICAL: {
2646 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002647 LexicalContents Contents(
2648 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2649 Blob.data()),
2650 static_cast<unsigned int>(Blob.size() / 4));
2651 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 TU->setHasExternalLexicalStorage(true);
2653 break;
2654 }
2655
2656 case UPDATE_VISIBLE: {
2657 unsigned Idx = 0;
2658 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002659 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002660 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002661 // If we've already loaded the decl, perform the updates when we finish
2662 // loading this block.
2663 if (Decl *D = GetExistingDecl(ID))
2664 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 break;
2666 }
2667
2668 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002669 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002671 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2672 (const unsigned char *)F.IdentifierTableData + Record[0],
2673 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2674 (const unsigned char *)F.IdentifierTableData,
2675 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002676
2677 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2678 }
2679 break;
2680
2681 case IDENTIFIER_OFFSET: {
2682 if (F.LocalNumIdentifiers != 0) {
2683 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002684 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002686 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 F.LocalNumIdentifiers = Record[0];
2688 unsigned LocalBaseIdentifierID = Record[1];
2689 F.BaseIdentifierID = getTotalNumIdentifiers();
2690
2691 if (F.LocalNumIdentifiers > 0) {
2692 // Introduce the global -> local mapping for identifiers within this
2693 // module.
2694 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2695 &F));
2696
2697 // Introduce the local -> global mapping for identifiers within this
2698 // module.
2699 F.IdentifierRemap.insertOrReplace(
2700 std::make_pair(LocalBaseIdentifierID,
2701 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002702
Ben Langmuir52ca6782014-10-20 16:27:32 +00002703 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2704 + F.LocalNumIdentifiers);
2705 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 break;
2707 }
2708
Richard Smith33e0f7e2015-07-22 02:08:40 +00002709 case INTERESTING_IDENTIFIERS:
2710 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2711 break;
2712
Ben Langmuir332aafe2014-01-31 01:06:56 +00002713 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002714 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2715 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002717 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 break;
2719
2720 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002721 if (SpecialTypes.empty()) {
2722 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2723 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2724 break;
2725 }
2726
2727 if (SpecialTypes.size() != Record.size()) {
2728 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002729 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002730 }
2731
2732 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2733 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2734 if (!SpecialTypes[I])
2735 SpecialTypes[I] = ID;
2736 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2737 // merge step?
2738 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 break;
2740
2741 case STATISTICS:
2742 TotalNumStatements += Record[0];
2743 TotalNumMacros += Record[1];
2744 TotalLexicalDeclContexts += Record[2];
2745 TotalVisibleDeclContexts += Record[3];
2746 break;
2747
2748 case UNUSED_FILESCOPED_DECLS:
2749 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2750 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2751 break;
2752
2753 case DELEGATING_CTORS:
2754 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2755 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2756 break;
2757
2758 case WEAK_UNDECLARED_IDENTIFIERS:
2759 if (Record.size() % 4 != 0) {
2760 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002761 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 }
2763
2764 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2765 // files. This isn't the way to do it :)
2766 WeakUndeclaredIdentifiers.clear();
2767
2768 // Translate the weak, undeclared identifiers into global IDs.
2769 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2770 WeakUndeclaredIdentifiers.push_back(
2771 getGlobalIdentifierID(F, Record[I++]));
2772 WeakUndeclaredIdentifiers.push_back(
2773 getGlobalIdentifierID(F, Record[I++]));
2774 WeakUndeclaredIdentifiers.push_back(
2775 ReadSourceLocation(F, Record, I).getRawEncoding());
2776 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2777 }
2778 break;
2779
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002781 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 F.LocalNumSelectors = Record[0];
2783 unsigned LocalBaseSelectorID = Record[1];
2784 F.BaseSelectorID = getTotalNumSelectors();
2785
2786 if (F.LocalNumSelectors > 0) {
2787 // Introduce the global -> local mapping for selectors within this
2788 // module.
2789 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2790
2791 // Introduce the local -> global mapping for selectors within this
2792 // module.
2793 F.SelectorRemap.insertOrReplace(
2794 std::make_pair(LocalBaseSelectorID,
2795 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002796
2797 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 }
2799 break;
2800 }
2801
2802 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002803 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 if (Record[0])
2805 F.SelectorLookupTable
2806 = ASTSelectorLookupTable::Create(
2807 F.SelectorLookupTableData + Record[0],
2808 F.SelectorLookupTableData,
2809 ASTSelectorLookupTrait(*this, F));
2810 TotalNumMethodPoolEntries += Record[1];
2811 break;
2812
2813 case REFERENCED_SELECTOR_POOL:
2814 if (!Record.empty()) {
2815 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2816 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2817 Record[Idx++]));
2818 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2819 getRawEncoding());
2820 }
2821 }
2822 break;
2823
2824 case PP_COUNTER_VALUE:
2825 if (!Record.empty() && Listener)
2826 Listener->ReadCounter(F, Record[0]);
2827 break;
2828
2829 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 F.NumFileSortedDecls = Record[0];
2832 break;
2833
2834 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002835 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 F.LocalNumSLocEntries = Record[0];
2837 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002838 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002839 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002841 if (!F.SLocEntryBaseID) {
2842 Error("ran out of source locations");
2843 break;
2844 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 // Make our entry in the range map. BaseID is negative and growing, so
2846 // we invert it. Because we invert it, though, we need the other end of
2847 // the range.
2848 unsigned RangeStart =
2849 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2850 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2851 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2852
2853 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2854 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2855 GlobalSLocOffsetMap.insert(
2856 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2857 - SLocSpaceSize,&F));
2858
2859 // Initialize the remapping table.
2860 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002861 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002863 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2865
2866 TotalNumSLocEntries += F.LocalNumSLocEntries;
2867 break;
2868 }
2869
2870 case MODULE_OFFSET_MAP: {
2871 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002872 const unsigned char *Data = (const unsigned char*)Blob.data();
2873 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002874
2875 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2876 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2877 F.SLocRemap.insert(std::make_pair(0U, 0));
2878 F.SLocRemap.insert(std::make_pair(2U, 1));
2879 }
2880
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002882 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2883 RemapBuilder;
2884 RemapBuilder SLocRemap(F.SLocRemap);
2885 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2886 RemapBuilder MacroRemap(F.MacroRemap);
2887 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2888 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2889 RemapBuilder SelectorRemap(F.SelectorRemap);
2890 RemapBuilder DeclRemap(F.DeclRemap);
2891 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002892
Richard Smithd8879c82015-08-24 21:59:32 +00002893 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002894 using namespace llvm::support;
2895 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 StringRef Name = StringRef((const char*)Data, Len);
2897 Data += Len;
2898 ModuleFile *OM = ModuleMgr.lookup(Name);
2899 if (!OM) {
2900 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002901 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 }
2903
Justin Bogner57ba0b22014-03-28 22:03:24 +00002904 uint32_t SLocOffset =
2905 endian::readNext<uint32_t, little, unaligned>(Data);
2906 uint32_t IdentifierIDOffset =
2907 endian::readNext<uint32_t, little, unaligned>(Data);
2908 uint32_t MacroIDOffset =
2909 endian::readNext<uint32_t, little, unaligned>(Data);
2910 uint32_t PreprocessedEntityIDOffset =
2911 endian::readNext<uint32_t, little, unaligned>(Data);
2912 uint32_t SubmoduleIDOffset =
2913 endian::readNext<uint32_t, little, unaligned>(Data);
2914 uint32_t SelectorIDOffset =
2915 endian::readNext<uint32_t, little, unaligned>(Data);
2916 uint32_t DeclIDOffset =
2917 endian::readNext<uint32_t, little, unaligned>(Data);
2918 uint32_t TypeIndexOffset =
2919 endian::readNext<uint32_t, little, unaligned>(Data);
2920
Ben Langmuir785180e2014-10-20 16:27:30 +00002921 uint32_t None = std::numeric_limits<uint32_t>::max();
2922
2923 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2924 RemapBuilder &Remap) {
2925 if (Offset != None)
2926 Remap.insert(std::make_pair(Offset,
2927 static_cast<int>(BaseOffset - Offset)));
2928 };
2929 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2930 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2931 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2932 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2933 PreprocessedEntityRemap);
2934 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2935 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2936 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2937 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938
2939 // Global -> local mappings.
2940 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2941 }
2942 break;
2943 }
2944
2945 case SOURCE_MANAGER_LINE_TABLE:
2946 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002947 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 break;
2949
2950 case SOURCE_LOCATION_PRELOADS: {
2951 // Need to transform from the local view (1-based IDs) to the global view,
2952 // which is based off F.SLocEntryBaseID.
2953 if (!F.PreloadSLocEntries.empty()) {
2954 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002955 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 }
2957
2958 F.PreloadSLocEntries.swap(Record);
2959 break;
2960 }
2961
2962 case EXT_VECTOR_DECLS:
2963 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2964 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2965 break;
2966
2967 case VTABLE_USES:
2968 if (Record.size() % 3 != 0) {
2969 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002970 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 }
2972
2973 // Later tables overwrite earlier ones.
2974 // FIXME: Modules will have some trouble with this. This is clearly not
2975 // the right way to do this.
2976 VTableUses.clear();
2977
2978 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2979 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2980 VTableUses.push_back(
2981 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2982 VTableUses.push_back(Record[Idx++]);
2983 }
2984 break;
2985
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 case PENDING_IMPLICIT_INSTANTIATIONS:
2987 if (PendingInstantiations.size() % 2 != 0) {
2988 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002989 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 }
2991
2992 if (Record.size() % 2 != 0) {
2993 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002994 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 }
2996
2997 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2998 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2999 PendingInstantiations.push_back(
3000 ReadSourceLocation(F, Record, I).getRawEncoding());
3001 }
3002 break;
3003
3004 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003005 if (Record.size() != 2) {
3006 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003007 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3010 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3011 break;
3012
3013 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003014 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3015 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3016 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003017
3018 unsigned LocalBasePreprocessedEntityID = Record[0];
3019
3020 unsigned StartingID;
3021 if (!PP.getPreprocessingRecord())
3022 PP.createPreprocessingRecord();
3023 if (!PP.getPreprocessingRecord()->getExternalSource())
3024 PP.getPreprocessingRecord()->SetExternalSource(*this);
3025 StartingID
3026 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003027 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 F.BasePreprocessedEntityID = StartingID;
3029
3030 if (F.NumPreprocessedEntities > 0) {
3031 // Introduce the global -> local mapping for preprocessed entities in
3032 // this module.
3033 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3034
3035 // Introduce the local -> global mapping for preprocessed entities in
3036 // this module.
3037 F.PreprocessedEntityRemap.insertOrReplace(
3038 std::make_pair(LocalBasePreprocessedEntityID,
3039 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3040 }
3041
3042 break;
3043 }
3044
3045 case DECL_UPDATE_OFFSETS: {
3046 if (Record.size() % 2 != 0) {
3047 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003048 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003050 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3051 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3052 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3053
3054 // If we've already loaded the decl, perform the updates when we finish
3055 // loading this block.
3056 if (Decl *D = GetExistingDecl(ID))
3057 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 break;
3060 }
3061
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 case OBJC_CATEGORIES_MAP: {
3063 if (F.LocalNumObjCCategoriesInMap != 0) {
3064 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003065 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 }
3067
3068 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003069 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 break;
3071 }
3072
3073 case OBJC_CATEGORIES:
3074 F.ObjCCategories.swap(Record);
3075 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003076
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 case DIAG_PRAGMA_MAPPINGS:
3078 if (F.PragmaDiagMappings.empty())
3079 F.PragmaDiagMappings.swap(Record);
3080 else
3081 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3082 Record.begin(), Record.end());
3083 break;
3084
3085 case CUDA_SPECIAL_DECL_REFS:
3086 // Later tables overwrite earlier ones.
3087 // FIXME: Modules will have trouble with this.
3088 CUDASpecialDeclRefs.clear();
3089 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3090 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3091 break;
3092
3093 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003094 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 if (Record[0]) {
3097 F.HeaderFileInfoTable
3098 = HeaderFileInfoLookupTable::Create(
3099 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3100 (const unsigned char *)F.HeaderFileInfoTableData,
3101 HeaderFileInfoTrait(*this, F,
3102 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003103 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003104
3105 PP.getHeaderSearchInfo().SetExternalSource(this);
3106 if (!PP.getHeaderSearchInfo().getExternalLookup())
3107 PP.getHeaderSearchInfo().SetExternalLookup(this);
3108 }
3109 break;
3110 }
3111
3112 case FP_PRAGMA_OPTIONS:
3113 // Later tables overwrite earlier ones.
3114 FPPragmaOptions.swap(Record);
3115 break;
3116
3117 case OPENCL_EXTENSIONS:
3118 // Later tables overwrite earlier ones.
3119 OpenCLExtensions.swap(Record);
3120 break;
3121
3122 case TENTATIVE_DEFINITIONS:
3123 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3124 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3125 break;
3126
3127 case KNOWN_NAMESPACES:
3128 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3129 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3130 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003131
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003132 case UNDEFINED_BUT_USED:
3133 if (UndefinedButUsed.size() % 2 != 0) {
3134 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003135 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003136 }
3137
3138 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003139 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003140 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003141 }
3142 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003143 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3144 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003145 ReadSourceLocation(F, Record, I).getRawEncoding());
3146 }
3147 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003148 case DELETE_EXPRS_TO_ANALYZE:
3149 for (unsigned I = 0, N = Record.size(); I != N;) {
3150 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3151 const uint64_t Count = Record[I++];
3152 DelayedDeleteExprs.push_back(Count);
3153 for (uint64_t C = 0; C < Count; ++C) {
3154 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3155 bool IsArrayForm = Record[I++] == 1;
3156 DelayedDeleteExprs.push_back(IsArrayForm);
3157 }
3158 }
3159 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003160
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003162 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 // If we aren't loading a module (which has its own exports), make
3164 // all of the imported modules visible.
3165 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003166 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3167 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3168 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3169 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003170 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 }
3172 }
3173 break;
3174 }
3175
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 case MACRO_OFFSET: {
3177 if (F.LocalNumMacros != 0) {
3178 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003179 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003181 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 F.LocalNumMacros = Record[0];
3183 unsigned LocalBaseMacroID = Record[1];
3184 F.BaseMacroID = getTotalNumMacros();
3185
3186 if (F.LocalNumMacros > 0) {
3187 // Introduce the global -> local mapping for macros within this module.
3188 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3189
3190 // Introduce the local -> global mapping for macros within this module.
3191 F.MacroRemap.insertOrReplace(
3192 std::make_pair(LocalBaseMacroID,
3193 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003194
3195 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 }
3197 break;
3198 }
3199
Richard Smithe40f2ba2013-08-07 21:41:30 +00003200 case LATE_PARSED_TEMPLATE: {
3201 LateParsedTemplates.append(Record.begin(), Record.end());
3202 break;
3203 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003204
3205 case OPTIMIZE_PRAGMA_OPTIONS:
3206 if (Record.size() != 1) {
3207 Error("invalid pragma optimize record");
3208 return Failure;
3209 }
3210 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3211 break;
Nico Weber72889432014-09-06 01:25:55 +00003212
Nico Weber779355f2016-03-02 23:22:00 +00003213 case MSSTRUCT_PRAGMA_OPTIONS:
3214 if (Record.size() != 1) {
3215 Error("invalid pragma ms_struct record");
3216 return Failure;
3217 }
3218 PragmaMSStructState = Record[0];
3219 break;
3220
Nico Weber42932312016-03-03 00:17:35 +00003221 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3222 if (Record.size() != 2) {
3223 Error("invalid pragma ms_struct record");
3224 return Failure;
3225 }
3226 PragmaMSPointersToMembersState = Record[0];
3227 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3228 break;
3229
Nico Weber72889432014-09-06 01:25:55 +00003230 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3231 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3232 UnusedLocalTypedefNameCandidates.push_back(
3233 getGlobalDeclID(F, Record[I]));
3234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 }
3236 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003237}
3238
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003239ASTReader::ASTReadResult
3240ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3241 const ModuleFile *ImportedBy,
3242 unsigned ClientLoadCapabilities) {
3243 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003244 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003245
Manman Ren11f2a472016-08-18 17:42:15 +00003246 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003247 // For an explicitly-loaded module, we don't care whether the original
3248 // module map file exists or matches.
3249 return Success;
3250 }
3251
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003252 // Try to resolve ModuleName in the current header search context and
3253 // verify that it is found in the same module map file as we saved. If the
3254 // top-level AST file is a main file, skip this check because there is no
3255 // usable header search context.
3256 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003257 "MODULE_NAME should come before MODULE_MAP_FILE");
3258 if (F.Kind == MK_ImplicitModule &&
3259 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3260 // An implicitly-loaded module file should have its module listed in some
3261 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003262 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003263 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3264 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3265 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003266 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003267 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3268 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3269 // This module was defined by an imported (explicit) module.
3270 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3271 << ASTFE->getName();
3272 else
3273 // This module was built with a different module map.
3274 Diag(diag::err_imported_module_not_found)
3275 << F.ModuleName << F.FileName << ImportedBy->FileName
3276 << F.ModuleMapPath;
3277 }
3278 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003279 }
3280
Richard Smithe842a472014-10-22 02:05:46 +00003281 assert(M->Name == F.ModuleName && "found module with different name");
3282
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003283 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003284 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003285 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3286 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003287 assert(ImportedBy && "top-level import should be verified");
3288 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3289 Diag(diag::err_imported_module_modmap_changed)
3290 << F.ModuleName << ImportedBy->FileName
3291 << ModMap->getName() << F.ModuleMapPath;
3292 return OutOfDate;
3293 }
3294
3295 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3296 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3297 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003298 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003299 const FileEntry *F =
3300 FileMgr.getFile(Filename, false, false);
3301 if (F == nullptr) {
3302 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3303 Error("could not find file '" + Filename +"' referenced by AST file");
3304 return OutOfDate;
3305 }
3306 AdditionalStoredMaps.insert(F);
3307 }
3308
3309 // Check any additional module map files (e.g. module.private.modulemap)
3310 // that are not in the pcm.
3311 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3312 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3313 // Remove files that match
3314 // Note: SmallPtrSet::erase is really remove
3315 if (!AdditionalStoredMaps.erase(ModMap)) {
3316 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3317 Diag(diag::err_module_different_modmap)
3318 << F.ModuleName << /*new*/0 << ModMap->getName();
3319 return OutOfDate;
3320 }
3321 }
3322 }
3323
3324 // Check any additional module map files that are in the pcm, but not
3325 // found in header search. Cases that match are already removed.
3326 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3327 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3328 Diag(diag::err_module_different_modmap)
3329 << F.ModuleName << /*not new*/1 << ModMap->getName();
3330 return OutOfDate;
3331 }
3332 }
3333
3334 if (Listener)
3335 Listener->ReadModuleMapFile(F.ModuleMapPath);
3336 return Success;
3337}
3338
3339
Douglas Gregorc1489562013-02-12 23:36:21 +00003340/// \brief Move the given method to the back of the global list of methods.
3341static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3342 // Find the entry for this selector in the method pool.
3343 Sema::GlobalMethodPool::iterator Known
3344 = S.MethodPool.find(Method->getSelector());
3345 if (Known == S.MethodPool.end())
3346 return;
3347
3348 // Retrieve the appropriate method list.
3349 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3350 : Known->second.second;
3351 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003352 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003353 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003354 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003355 Found = true;
3356 } else {
3357 // Keep searching.
3358 continue;
3359 }
3360 }
3361
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003362 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003363 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003364 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003365 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003366 }
3367}
3368
Richard Smithde711422015-04-23 21:20:19 +00003369void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003370 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003371 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003372 bool wasHidden = D->Hidden;
3373 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003374
Richard Smith49f906a2014-03-01 00:08:04 +00003375 if (wasHidden && SemaObj) {
3376 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3377 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003378 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 }
3380 }
3381}
3382
Richard Smith49f906a2014-03-01 00:08:04 +00003383void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003384 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003385 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003387 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003388 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003390 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003391
3392 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003393 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 // there is nothing more to do.
3395 continue;
3396 }
Richard Smith49f906a2014-03-01 00:08:04 +00003397
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 if (!Mod->isAvailable()) {
3399 // Modules that aren't available cannot be made visible.
3400 continue;
3401 }
3402
3403 // Update the module's name visibility.
3404 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003405
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 // If we've already deserialized any names from this module,
3407 // mark them as visible.
3408 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3409 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003410 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003412 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003413 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3414 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003416
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003418 SmallVector<Module *, 16> Exports;
3419 Mod->getExportedModules(Exports);
3420 for (SmallVectorImpl<Module *>::iterator
3421 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3422 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003423 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003424 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 }
3426 }
3427}
3428
Douglas Gregore060e572013-01-25 01:03:03 +00003429bool ASTReader::loadGlobalIndex() {
3430 if (GlobalIndex)
3431 return false;
3432
3433 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3434 !Context.getLangOpts().Modules)
3435 return true;
3436
3437 // Try to load the global index.
3438 TriedLoadingGlobalIndex = true;
3439 StringRef ModuleCachePath
3440 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3441 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003442 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003443 if (!Result.first)
3444 return true;
3445
3446 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003447 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003448 return false;
3449}
3450
3451bool ASTReader::isGlobalIndexUnavailable() const {
3452 return Context.getLangOpts().Modules && UseGlobalIndex &&
3453 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3454}
3455
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003456static void updateModuleTimestamp(ModuleFile &MF) {
3457 // Overwrite the timestamp file contents so that file's mtime changes.
3458 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003459 std::error_code EC;
3460 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3461 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003462 return;
3463 OS << "Timestamp file\n";
3464}
3465
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003466/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3467/// cursor into the start of the given block ID, returning false on success and
3468/// true on failure.
3469static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3470 while (1) {
3471 llvm::BitstreamEntry Entry = Cursor.advance();
3472 switch (Entry.Kind) {
3473 case llvm::BitstreamEntry::Error:
3474 case llvm::BitstreamEntry::EndBlock:
3475 return true;
3476
3477 case llvm::BitstreamEntry::Record:
3478 // Ignore top-level records.
3479 Cursor.skipRecord(Entry.ID);
3480 break;
3481
3482 case llvm::BitstreamEntry::SubBlock:
3483 if (Entry.ID == BlockID) {
3484 if (Cursor.EnterSubBlock(BlockID))
3485 return true;
3486 // Found it!
3487 return false;
3488 }
3489
3490 if (Cursor.SkipBlock())
3491 return true;
3492 }
3493 }
3494}
3495
Benjamin Kramer0772c422016-02-13 13:42:54 +00003496ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 ModuleKind Type,
3498 SourceLocation ImportLoc,
3499 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003500 llvm::SaveAndRestore<SourceLocation>
3501 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3502
Richard Smithd1c46742014-04-30 02:24:17 +00003503 // Defer any pending actions until we get to the end of reading the AST file.
3504 Deserializing AnASTFile(this);
3505
Guy Benyei11169dd2012-12-18 14:30:41 +00003506 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003507 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003508
3509 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003510 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003512 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003513 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 ClientLoadCapabilities)) {
3515 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003516 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 case OutOfDate:
3518 case VersionMismatch:
3519 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003520 case HadErrors: {
3521 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3522 for (const ImportedModule &IM : Loaded)
3523 LoadedSet.insert(IM.Mod);
3524
Douglas Gregor7029ce12013-03-19 00:28:20 +00003525 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003526 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003527 Context.getLangOpts().Modules
3528 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003529 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003530
3531 // If we find that any modules are unusable, the global index is going
3532 // to be out-of-date. Just remove it.
3533 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003534 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003536 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 case Success:
3538 break;
3539 }
3540
3541 // Here comes stuff that we only do once the entire chain is loaded.
3542
3543 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003544 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3545 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 M != MEnd; ++M) {
3547 ModuleFile &F = *M->Mod;
3548
3549 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003550 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3551 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003552
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003553 // Read the extension blocks.
3554 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3555 if (ASTReadResult Result = ReadExtensionBlock(F))
3556 return Result;
3557 }
3558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 // Once read, set the ModuleFile bit base offset and update the size in
3560 // bits of all files we've seen.
3561 F.GlobalBitOffset = TotalModulesSizeInBits;
3562 TotalModulesSizeInBits += F.SizeInBits;
3563 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3564
3565 // Preload SLocEntries.
3566 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3567 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3568 // Load it through the SourceManager and don't call ReadSLocEntry()
3569 // directly because the entry may have already been loaded in which case
3570 // calling ReadSLocEntry() directly would trigger an assertion in
3571 // SourceManager.
3572 SourceMgr.getLoadedSLocEntryByID(Index);
3573 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003574
3575 // Preload all the pending interesting identifiers by marking them out of
3576 // date.
3577 for (auto Offset : F.PreloadIdentifierOffsets) {
3578 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3579 F.IdentifierTableData + Offset);
3580
3581 ASTIdentifierLookupTrait Trait(*this, F);
3582 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3583 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003584 auto &II = PP.getIdentifierTable().getOwn(Key);
3585 II.setOutOfDate(true);
3586
3587 // Mark this identifier as being from an AST file so that we can track
3588 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003589 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003590
3591 // Associate the ID with the identifier so that the writer can reuse it.
3592 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3593 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 }
3596
Douglas Gregor603cd862013-03-22 18:50:14 +00003597 // Setup the import locations and notify the module manager that we've
3598 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003599 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3600 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 M != MEnd; ++M) {
3602 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003603
3604 ModuleMgr.moduleFileAccepted(&F);
3605
3606 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003607 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003608 // FIXME: We assume that locations from PCH / preamble do not need
3609 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 if (!M->ImportedBy)
3611 F.ImportLoc = M->ImportLoc;
3612 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003613 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003614 }
3615
Richard Smith33e0f7e2015-07-22 02:08:40 +00003616 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003617 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3618 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003619 // Mark all of the identifiers in the identifier table as being out of date,
3620 // so that various accessors know to check the loaded modules when the
3621 // identifier is used.
3622 //
3623 // For C++ modules, we don't need information on many identifiers (just
3624 // those that provide macros or are poisoned), so we mark all of
3625 // the interesting ones via PreloadIdentifierOffsets.
3626 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3627 IdEnd = PP.getIdentifierTable().end();
3628 Id != IdEnd; ++Id)
3629 Id->second->setOutOfDate(true);
3630 }
Manman Rena0f31a02016-04-29 19:04:05 +00003631 // Mark selectors as out of date.
3632 for (auto Sel : SelectorGeneration)
3633 SelectorOutOfDate[Sel.first] = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003634
3635 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003636 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3637 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3639 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003640
3641 switch (Unresolved.Kind) {
3642 case UnresolvedModuleRef::Conflict:
3643 if (ResolvedMod) {
3644 Module::Conflict Conflict;
3645 Conflict.Other = ResolvedMod;
3646 Conflict.Message = Unresolved.String.str();
3647 Unresolved.Mod->Conflicts.push_back(Conflict);
3648 }
3649 continue;
3650
3651 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003653 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003655
Douglas Gregorfb912652013-03-20 21:10:35 +00003656 case UnresolvedModuleRef::Export:
3657 if (ResolvedMod || Unresolved.IsWildcard)
3658 Unresolved.Mod->Exports.push_back(
3659 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3660 continue;
3661 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003662 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003663 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003664
3665 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3666 // Might be unnecessary as use declarations are only used to build the
3667 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003668
3669 InitializeContext();
3670
Richard Smith3d8e97e2013-10-18 06:54:39 +00003671 if (SemaObj)
3672 UpdateSema();
3673
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 if (DeserializationListener)
3675 DeserializationListener->ReaderInitialized(this);
3676
3677 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003678 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 PrimaryModule.OriginalSourceFileID
3680 = FileID::get(PrimaryModule.SLocEntryBaseID
3681 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3682
3683 // If this AST file is a precompiled preamble, then set the
3684 // preamble file ID of the source manager to the file source file
3685 // from which the preamble was built.
3686 if (Type == MK_Preamble) {
3687 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3688 } else if (Type == MK_MainFile) {
3689 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3690 }
3691 }
3692
3693 // For any Objective-C class definitions we have already loaded, make sure
3694 // that we load any additional categories.
3695 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3696 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3697 ObjCClassesLoaded[I],
3698 PreviousGeneration);
3699 }
Douglas Gregore060e572013-01-25 01:03:03 +00003700
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003701 if (PP.getHeaderSearchInfo()
3702 .getHeaderSearchOpts()
3703 .ModulesValidateOncePerBuildSession) {
3704 // Now we are certain that the module and all modules it depends on are
3705 // up to date. Create or update timestamp files for modules that are
3706 // located in the module cache (not for PCH files that could be anywhere
3707 // in the filesystem).
3708 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3709 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003710 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003711 updateModuleTimestamp(*M.Mod);
3712 }
3713 }
3714 }
3715
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 return Success;
3717}
3718
Ben Langmuir487ea142014-10-23 18:05:36 +00003719static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3720
Ben Langmuir70a1b812015-03-24 04:43:52 +00003721/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3722static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3723 return Stream.Read(8) == 'C' &&
3724 Stream.Read(8) == 'P' &&
3725 Stream.Read(8) == 'C' &&
3726 Stream.Read(8) == 'H';
3727}
3728
Richard Smith0f99d6a2015-08-09 08:48:41 +00003729static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3730 switch (Kind) {
3731 case MK_PCH:
3732 return 0; // PCH
3733 case MK_ImplicitModule:
3734 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003735 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003736 return 1; // module
3737 case MK_MainFile:
3738 case MK_Preamble:
3739 return 2; // main source file
3740 }
3741 llvm_unreachable("unknown module kind");
3742}
3743
Guy Benyei11169dd2012-12-18 14:30:41 +00003744ASTReader::ASTReadResult
3745ASTReader::ReadASTCore(StringRef FileName,
3746 ModuleKind Type,
3747 SourceLocation ImportLoc,
3748 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003749 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003750 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003751 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 unsigned ClientLoadCapabilities) {
3753 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003755 ModuleManager::AddModuleResult AddResult
3756 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003757 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003758 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003759 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003760
Douglas Gregor7029ce12013-03-19 00:28:20 +00003761 switch (AddResult) {
3762 case ModuleManager::AlreadyLoaded:
3763 return Success;
3764
3765 case ModuleManager::NewlyLoaded:
3766 // Load module file below.
3767 break;
3768
3769 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003770 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003771 // it.
3772 if (ClientLoadCapabilities & ARR_Missing)
3773 return Missing;
3774
3775 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003776 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003777 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003778 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003779 return Failure;
3780
3781 case ModuleManager::OutOfDate:
3782 // We couldn't load the module file because it is out-of-date. If the
3783 // client can handle out-of-date, return it.
3784 if (ClientLoadCapabilities & ARR_OutOfDate)
3785 return OutOfDate;
3786
3787 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003788 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003789 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003790 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003791 return Failure;
3792 }
3793
Douglas Gregor7029ce12013-03-19 00:28:20 +00003794 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003795
3796 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3797 // module?
3798 if (FileName != "-") {
3799 CurrentDir = llvm::sys::path::parent_path(FileName);
3800 if (CurrentDir.empty()) CurrentDir = ".";
3801 }
3802
3803 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003804 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003805 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003806 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003807 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3808
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003810 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003811 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3812 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003813 return Failure;
3814 }
3815
3816 // This is used for compatibility with older PCH formats.
3817 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003818 while (1) {
3819 llvm::BitstreamEntry Entry = Stream.advance();
3820
3821 switch (Entry.Kind) {
3822 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003823 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003824 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 Error("invalid record at top-level of AST file");
3826 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003827
3828 case llvm::BitstreamEntry::SubBlock:
3829 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003830 }
3831
Chris Lattnerefa77172013-01-20 00:00:22 +00003832 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 case CONTROL_BLOCK_ID:
3834 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003835 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003837 // Check that we didn't try to load a non-module AST file as a module.
3838 //
3839 // FIXME: Should we also perform the converse check? Loading a module as
3840 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003841 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3842 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003843 F.ModuleName.empty()) {
3844 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3845 if (Result != OutOfDate ||
3846 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3847 Diag(diag::err_module_file_not_module) << FileName;
3848 return Result;
3849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003850 break;
3851
3852 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003853 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 case OutOfDate: return OutOfDate;
3855 case VersionMismatch: return VersionMismatch;
3856 case ConfigurationMismatch: return ConfigurationMismatch;
3857 case HadErrors: return HadErrors;
3858 }
3859 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003860
Guy Benyei11169dd2012-12-18 14:30:41 +00003861 case AST_BLOCK_ID:
3862 if (!HaveReadControlBlock) {
3863 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003864 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 return VersionMismatch;
3866 }
3867
3868 // Record that we've loaded this module.
3869 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3870 return Success;
3871
3872 default:
3873 if (Stream.SkipBlock()) {
3874 Error("malformed block record in AST file");
3875 return Failure;
3876 }
3877 break;
3878 }
3879 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003880
3881 return Success;
3882}
3883
3884/// Parse a record and blob containing module file extension metadata.
3885static bool parseModuleFileExtensionMetadata(
3886 const SmallVectorImpl<uint64_t> &Record,
3887 StringRef Blob,
3888 ModuleFileExtensionMetadata &Metadata) {
3889 if (Record.size() < 4) return true;
3890
3891 Metadata.MajorVersion = Record[0];
3892 Metadata.MinorVersion = Record[1];
3893
3894 unsigned BlockNameLen = Record[2];
3895 unsigned UserInfoLen = Record[3];
3896
3897 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3898
3899 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3900 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3901 Blob.data() + BlockNameLen + UserInfoLen);
3902 return false;
3903}
3904
3905ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3906 BitstreamCursor &Stream = F.Stream;
3907
3908 RecordData Record;
3909 while (true) {
3910 llvm::BitstreamEntry Entry = Stream.advance();
3911 switch (Entry.Kind) {
3912 case llvm::BitstreamEntry::SubBlock:
3913 if (Stream.SkipBlock())
3914 return Failure;
3915
3916 continue;
3917
3918 case llvm::BitstreamEntry::EndBlock:
3919 return Success;
3920
3921 case llvm::BitstreamEntry::Error:
3922 return HadErrors;
3923
3924 case llvm::BitstreamEntry::Record:
3925 break;
3926 }
3927
3928 Record.clear();
3929 StringRef Blob;
3930 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3931 switch (RecCode) {
3932 case EXTENSION_METADATA: {
3933 ModuleFileExtensionMetadata Metadata;
3934 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3935 return Failure;
3936
3937 // Find a module file extension with this block name.
3938 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3939 if (Known == ModuleFileExtensions.end()) break;
3940
3941 // Form a reader.
3942 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3943 F, Stream)) {
3944 F.ExtensionReaders.push_back(std::move(Reader));
3945 }
3946
3947 break;
3948 }
3949 }
3950 }
3951
3952 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003953}
3954
Richard Smitha7e2cc62015-05-01 01:53:09 +00003955void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 // If there's a listener, notify them that we "read" the translation unit.
3957 if (DeserializationListener)
3958 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3959 Context.getTranslationUnitDecl());
3960
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // FIXME: Find a better way to deal with collisions between these
3962 // built-in types. Right now, we just ignore the problem.
3963
3964 // Load the special types.
3965 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3966 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3967 if (!Context.CFConstantStringTypeDecl)
3968 Context.setCFConstantStringType(GetType(String));
3969 }
3970
3971 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3972 QualType FileType = GetType(File);
3973 if (FileType.isNull()) {
3974 Error("FILE type is NULL");
3975 return;
3976 }
3977
3978 if (!Context.FILEDecl) {
3979 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3980 Context.setFILEDecl(Typedef->getDecl());
3981 else {
3982 const TagType *Tag = FileType->getAs<TagType>();
3983 if (!Tag) {
3984 Error("Invalid FILE type in AST file");
3985 return;
3986 }
3987 Context.setFILEDecl(Tag->getDecl());
3988 }
3989 }
3990 }
3991
3992 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3993 QualType Jmp_bufType = GetType(Jmp_buf);
3994 if (Jmp_bufType.isNull()) {
3995 Error("jmp_buf type is NULL");
3996 return;
3997 }
3998
3999 if (!Context.jmp_bufDecl) {
4000 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4001 Context.setjmp_bufDecl(Typedef->getDecl());
4002 else {
4003 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4004 if (!Tag) {
4005 Error("Invalid jmp_buf type in AST file");
4006 return;
4007 }
4008 Context.setjmp_bufDecl(Tag->getDecl());
4009 }
4010 }
4011 }
4012
4013 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4014 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4015 if (Sigjmp_bufType.isNull()) {
4016 Error("sigjmp_buf type is NULL");
4017 return;
4018 }
4019
4020 if (!Context.sigjmp_bufDecl) {
4021 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4022 Context.setsigjmp_bufDecl(Typedef->getDecl());
4023 else {
4024 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4025 assert(Tag && "Invalid sigjmp_buf type in AST file");
4026 Context.setsigjmp_bufDecl(Tag->getDecl());
4027 }
4028 }
4029 }
4030
4031 if (unsigned ObjCIdRedef
4032 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4033 if (Context.ObjCIdRedefinitionType.isNull())
4034 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4035 }
4036
4037 if (unsigned ObjCClassRedef
4038 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4039 if (Context.ObjCClassRedefinitionType.isNull())
4040 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4041 }
4042
4043 if (unsigned ObjCSelRedef
4044 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4045 if (Context.ObjCSelRedefinitionType.isNull())
4046 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4047 }
4048
4049 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4050 QualType Ucontext_tType = GetType(Ucontext_t);
4051 if (Ucontext_tType.isNull()) {
4052 Error("ucontext_t type is NULL");
4053 return;
4054 }
4055
4056 if (!Context.ucontext_tDecl) {
4057 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4058 Context.setucontext_tDecl(Typedef->getDecl());
4059 else {
4060 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4061 assert(Tag && "Invalid ucontext_t type in AST file");
4062 Context.setucontext_tDecl(Tag->getDecl());
4063 }
4064 }
4065 }
4066 }
4067
4068 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4069
4070 // If there were any CUDA special declarations, deserialize them.
4071 if (!CUDASpecialDeclRefs.empty()) {
4072 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4073 Context.setcudaConfigureCallDecl(
4074 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4075 }
Richard Smith56be7542014-03-21 00:33:59 +00004076
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004078 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004079 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004080 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004081 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004082 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004083 if (Import.ImportLoc.isValid())
4084 PP.makeModuleVisible(Imported, Import.ImportLoc);
4085 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 }
4088 ImportedModules.clear();
4089}
4090
4091void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004092 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004093}
4094
Ben Langmuir70a1b812015-03-24 04:43:52 +00004095/// \brief Reads and return the signature record from \p StreamFile's control
4096/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004097static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4098 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004099 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004100 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004101
4102 // Scan for the CONTROL_BLOCK_ID block.
4103 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4104 return 0;
4105
4106 // Scan for SIGNATURE inside the control block.
4107 ASTReader::RecordData Record;
4108 while (1) {
4109 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4110 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4111 Entry.Kind != llvm::BitstreamEntry::Record)
4112 return 0;
4113
4114 Record.clear();
4115 StringRef Blob;
4116 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4117 return Record[0];
4118 }
4119}
4120
Guy Benyei11169dd2012-12-18 14:30:41 +00004121/// \brief Retrieve the name of the original source file name
4122/// directly from the AST file, without actually loading the AST
4123/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004124std::string ASTReader::getOriginalSourceFile(
4125 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004126 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004128 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004130 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4131 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 return std::string();
4133 }
4134
4135 // Initialize the stream
4136 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004137 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004138 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004139
4140 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004141 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4143 return std::string();
4144 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004145
Chris Lattnere7b154b2013-01-19 21:39:22 +00004146 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004147 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004148 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4149 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 // Scan for ORIGINAL_FILE inside the control block.
4153 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004154 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004155 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004156 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4157 return std::string();
4158
4159 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4160 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4161 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004163
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004165 StringRef Blob;
4166 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4167 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171namespace {
4172 class SimplePCHValidator : public ASTReaderListener {
4173 const LangOptions &ExistingLangOpts;
4174 const TargetOptions &ExistingTargetOpts;
4175 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004176 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004178
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 public:
4180 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4181 const TargetOptions &ExistingTargetOpts,
4182 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004183 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 FileManager &FileMgr)
4185 : ExistingLangOpts(ExistingLangOpts),
4186 ExistingTargetOpts(ExistingTargetOpts),
4187 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004188 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 FileMgr(FileMgr)
4190 {
4191 }
4192
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004193 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4194 bool AllowCompatibleDifferences) override {
4195 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4196 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004198 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4199 bool AllowCompatibleDifferences) override {
4200 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4201 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004203 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4204 StringRef SpecificModuleCachePath,
4205 bool Complain) override {
4206 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4207 ExistingModuleCachePath,
4208 nullptr, ExistingLangOpts);
4209 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004210 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4211 bool Complain,
4212 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004213 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004214 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 }
4216 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004217}
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004219bool ASTReader::readASTFileControlBlock(
4220 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004221 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004222 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004223 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004225 // FIXME: This allows use of the VFS; we do not allow use of the
4226 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004227 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 if (!Buffer) {
4229 return true;
4230 }
4231
4232 // Initialize the stream
4233 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004234 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004235 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004236
4237 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004238 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004241 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004242 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004243 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004244
4245 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004246 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004247 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004248 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004249
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004251 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004252 bool DoneWithControlBlock = false;
4253 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004254 llvm::BitstreamEntry Entry = Stream.advance();
4255
4256 switch (Entry.Kind) {
4257 case llvm::BitstreamEntry::SubBlock: {
4258 switch (Entry.ID) {
4259 case OPTIONS_BLOCK_ID: {
4260 std::string IgnoredSuggestedPredefines;
4261 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4262 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004263 Listener, IgnoredSuggestedPredefines,
4264 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004265 return true;
4266 break;
4267 }
4268
4269 case INPUT_FILES_BLOCK_ID:
4270 InputFilesCursor = Stream;
4271 if (Stream.SkipBlock() ||
4272 (NeedsInputFiles &&
4273 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4274 return true;
4275 break;
4276
4277 default:
4278 if (Stream.SkipBlock())
4279 return true;
4280 break;
4281 }
4282
4283 continue;
4284 }
4285
4286 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004287 DoneWithControlBlock = true;
4288 break;
Richard Smith0516b182015-09-08 19:40:14 +00004289
4290 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004292
4293 case llvm::BitstreamEntry::Record:
4294 break;
4295 }
4296
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004297 if (DoneWithControlBlock) break;
4298
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004300 StringRef Blob;
4301 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004302 switch ((ControlRecordTypes)RecCode) {
4303 case METADATA: {
4304 if (Record[0] != VERSION_MAJOR)
4305 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004306
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004307 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004308 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004309
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004310 break;
4311 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004312 case MODULE_NAME:
4313 Listener.ReadModuleName(Blob);
4314 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004315 case MODULE_DIRECTORY:
4316 ModuleDir = Blob;
4317 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004318 case MODULE_MAP_FILE: {
4319 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004320 auto Path = ReadString(Record, Idx);
4321 ResolveImportedPath(Path, ModuleDir);
4322 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004323 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004324 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004325 case INPUT_FILE_OFFSETS: {
4326 if (!NeedsInputFiles)
4327 break;
4328
4329 unsigned NumInputFiles = Record[0];
4330 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004331 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004332 for (unsigned I = 0; I != NumInputFiles; ++I) {
4333 // Go find this input file.
4334 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004335
4336 if (isSystemFile && !NeedsSystemInputFiles)
4337 break; // the rest are system input files
4338
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004339 BitstreamCursor &Cursor = InputFilesCursor;
4340 SavedStreamPosition SavedPosition(Cursor);
4341 Cursor.JumpToBit(InputFileOffs[I]);
4342
4343 unsigned Code = Cursor.ReadCode();
4344 RecordData Record;
4345 StringRef Blob;
4346 bool shouldContinue = false;
4347 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4348 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004349 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004350 std::string Filename = Blob;
4351 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004352 shouldContinue = Listener.visitInputFile(
4353 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004354 break;
4355 }
4356 if (!shouldContinue)
4357 break;
4358 }
4359 break;
4360 }
4361
Richard Smithd4b230b2014-10-27 23:01:16 +00004362 case IMPORTS: {
4363 if (!NeedsImports)
4364 break;
4365
4366 unsigned Idx = 0, N = Record.size();
4367 while (Idx < N) {
4368 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004369 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004370 std::string Filename = ReadString(Record, Idx);
4371 ResolveImportedPath(Filename, ModuleDir);
4372 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004373 }
4374 break;
4375 }
4376
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004377 default:
4378 // No other validation to perform.
4379 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 }
4381 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004382
4383 // Look for module file extension blocks, if requested.
4384 if (FindModuleFileExtensions) {
4385 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4386 bool DoneWithExtensionBlock = false;
4387 while (!DoneWithExtensionBlock) {
4388 llvm::BitstreamEntry Entry = Stream.advance();
4389
4390 switch (Entry.Kind) {
4391 case llvm::BitstreamEntry::SubBlock:
4392 if (Stream.SkipBlock())
4393 return true;
4394
4395 continue;
4396
4397 case llvm::BitstreamEntry::EndBlock:
4398 DoneWithExtensionBlock = true;
4399 continue;
4400
4401 case llvm::BitstreamEntry::Error:
4402 return true;
4403
4404 case llvm::BitstreamEntry::Record:
4405 break;
4406 }
4407
4408 Record.clear();
4409 StringRef Blob;
4410 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4411 switch (RecCode) {
4412 case EXTENSION_METADATA: {
4413 ModuleFileExtensionMetadata Metadata;
4414 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4415 return true;
4416
4417 Listener.readModuleFileExtension(Metadata);
4418 break;
4419 }
4420 }
4421 }
4422 }
4423 }
4424
4425 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004426}
4427
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004428bool ASTReader::isAcceptableASTFile(
4429 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004430 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004431 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4432 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004433 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4434 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004435 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004436 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004437 validator,
4438 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004439}
4440
Ben Langmuir2c9af442014-04-10 17:57:43 +00004441ASTReader::ASTReadResult
4442ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 // Enter the submodule block.
4444 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4445 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004446 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 }
4448
4449 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4450 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004451 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 RecordData Record;
4453 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004454 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4455
4456 switch (Entry.Kind) {
4457 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4458 case llvm::BitstreamEntry::Error:
4459 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004460 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004461 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004462 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004463 case llvm::BitstreamEntry::Record:
4464 // The interesting case.
4465 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004467
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004469 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004471 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4472
4473 if ((Kind == SUBMODULE_METADATA) != First) {
4474 Error("submodule metadata record should be at beginning of block");
4475 return Failure;
4476 }
4477 First = false;
4478
4479 // Submodule information is only valid if we have a current module.
4480 // FIXME: Should we error on these cases?
4481 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4482 Kind != SUBMODULE_DEFINITION)
4483 continue;
4484
4485 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 default: // Default behavior: ignore.
4487 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488
Richard Smith03478d92014-10-23 22:12:14 +00004489 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004490 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
Richard Smith03478d92014-10-23 22:12:14 +00004494
Chris Lattner0e6c9402013-01-20 02:38:54 +00004495 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004496 unsigned Idx = 0;
4497 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4498 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4499 bool IsFramework = Record[Idx++];
4500 bool IsExplicit = Record[Idx++];
4501 bool IsSystem = Record[Idx++];
4502 bool IsExternC = Record[Idx++];
4503 bool InferSubmodules = Record[Idx++];
4504 bool InferExplicitSubmodules = Record[Idx++];
4505 bool InferExportWildcard = Record[Idx++];
4506 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004507
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004508 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004509 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004511
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 // Retrieve this (sub)module from the module map, creating it if
4513 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004514 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004516
4517 // FIXME: set the definition loc for CurrentModule, or call
4518 // ModMap.setInferredModuleAllowedBy()
4519
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4521 if (GlobalIndex >= SubmodulesLoaded.size() ||
4522 SubmodulesLoaded[GlobalIndex]) {
4523 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004524 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004526
Douglas Gregor7029ce12013-03-19 00:28:20 +00004527 if (!ParentModule) {
4528 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4529 if (CurFile != F.File) {
4530 if (!Diags.isDiagnosticInFlight()) {
4531 Diag(diag::err_module_file_conflict)
4532 << CurrentModule->getTopLevelModuleName()
4533 << CurFile->getName()
4534 << F.File->getName();
4535 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004536 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004537 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004538 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004539
4540 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004541 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004542
Adrian Prantl15bcf702015-06-30 17:39:43 +00004543 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 CurrentModule->IsFromModuleFile = true;
4545 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004546 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 CurrentModule->InferSubmodules = InferSubmodules;
4548 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4549 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004550 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 if (DeserializationListener)
4552 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4553
4554 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004555
Richard Smith8a3e39a2016-03-28 21:31:09 +00004556 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004557 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004558 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004559 CurrentModule->UnresolvedConflicts.clear();
4560 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004561
4562 // The module is available unless it's missing a requirement; relevant
4563 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4564 // Missing headers that were present when the module was built do not
4565 // make it unavailable -- if we got this far, this must be an explicitly
4566 // imported module file.
4567 CurrentModule->Requirements.clear();
4568 CurrentModule->MissingHeaders.clear();
4569 CurrentModule->IsMissingRequirement =
4570 ParentModule && ParentModule->IsMissingRequirement;
4571 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 break;
4573 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004574
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004576 std::string Filename = Blob;
4577 ResolveImportedPath(F, Filename);
4578 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004580 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4581 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004582 // This can be a spurious difference caused by changing the VFS to
4583 // point to a different copy of the file, and it is too late to
4584 // to rebuild safely.
4585 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4586 // after input file validation only real problems would remain and we
4587 // could just error. For now, assume it's okay.
4588 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 }
4590 }
4591 break;
4592 }
4593
Richard Smith202210b2014-10-24 20:23:01 +00004594 case SUBMODULE_HEADER:
4595 case SUBMODULE_EXCLUDED_HEADER:
4596 case SUBMODULE_PRIVATE_HEADER:
4597 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004598 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4599 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004600 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004601
Richard Smith202210b2014-10-24 20:23:01 +00004602 case SUBMODULE_TEXTUAL_HEADER:
4603 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4604 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4605 // them here.
4606 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004607
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004609 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 break;
4611 }
4612
4613 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004614 std::string Dirname = Blob;
4615 ResolveImportedPath(F, Dirname);
4616 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004618 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4619 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004620 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4621 Error("mismatched umbrella directories in submodule");
4622 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 }
4624 }
4625 break;
4626 }
4627
4628 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 F.BaseSubmoduleID = getTotalNumSubmodules();
4630 F.LocalNumSubmodules = Record[0];
4631 unsigned LocalBaseSubmoduleID = Record[1];
4632 if (F.LocalNumSubmodules > 0) {
4633 // Introduce the global -> local mapping for submodules within this
4634 // module.
4635 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4636
4637 // Introduce the local -> global mapping for submodules within this
4638 // module.
4639 F.SubmoduleRemap.insertOrReplace(
4640 std::make_pair(LocalBaseSubmoduleID,
4641 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004642
Ben Langmuir52ca6782014-10-20 16:27:32 +00004643 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4644 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 break;
4646 }
4647
4648 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004650 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 Unresolved.File = &F;
4652 Unresolved.Mod = CurrentModule;
4653 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004654 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004656 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 }
4658 break;
4659 }
4660
4661 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004663 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 Unresolved.File = &F;
4665 Unresolved.Mod = CurrentModule;
4666 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004667 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004669 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 }
4671
4672 // Once we've loaded the set of exports, there's no reason to keep
4673 // the parsed, unresolved exports around.
4674 CurrentModule->UnresolvedExports.clear();
4675 break;
4676 }
4677 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004678 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 Context.getTargetInfo());
4680 break;
4681 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004682
4683 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004684 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004685 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004686 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004687
4688 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004689 CurrentModule->ConfigMacros.push_back(Blob.str());
4690 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004691
4692 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004693 UnresolvedModuleRef Unresolved;
4694 Unresolved.File = &F;
4695 Unresolved.Mod = CurrentModule;
4696 Unresolved.ID = Record[0];
4697 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4698 Unresolved.IsWildcard = false;
4699 Unresolved.String = Blob;
4700 UnresolvedModuleRefs.push_back(Unresolved);
4701 break;
4702 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004703
4704 case SUBMODULE_INITIALIZERS:
4705 SmallVector<uint32_t, 16> Inits;
4706 for (auto &ID : Record)
4707 Inits.push_back(getGlobalDeclID(F, ID));
4708 Context.addLazyModuleInitializers(CurrentModule, Inits);
4709 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 }
4711 }
4712}
4713
4714/// \brief Parse the record that corresponds to a LangOptions data
4715/// structure.
4716///
4717/// This routine parses the language options from the AST file and then gives
4718/// them to the AST listener if one is set.
4719///
4720/// \returns true if the listener deems the file unacceptable, false otherwise.
4721bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4722 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004723 ASTReaderListener &Listener,
4724 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 LangOptions LangOpts;
4726 unsigned Idx = 0;
4727#define LANGOPT(Name, Bits, Default, Description) \
4728 LangOpts.Name = Record[Idx++];
4729#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4730 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4731#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004732#define SANITIZER(NAME, ID) \
4733 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004734#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004735
Ben Langmuircd98cb72015-06-23 18:20:18 +00004736 for (unsigned N = Record[Idx++]; N; --N)
4737 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4738
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4740 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4741 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004742
Ben Langmuird4a667a2015-06-23 18:20:23 +00004743 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004744
4745 // Comment options.
4746 for (unsigned N = Record[Idx++]; N; --N) {
4747 LangOpts.CommentOpts.BlockCommandNames.push_back(
4748 ReadString(Record, Idx));
4749 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004750 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004751
Samuel Antaoee8fb302016-01-06 13:42:12 +00004752 // OpenMP offloading options.
4753 for (unsigned N = Record[Idx++]; N; --N) {
4754 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4755 }
4756
4757 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4758
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004759 return Listener.ReadLanguageOptions(LangOpts, Complain,
4760 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761}
4762
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004763bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4764 ASTReaderListener &Listener,
4765 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 unsigned Idx = 0;
4767 TargetOptions TargetOpts;
4768 TargetOpts.Triple = ReadString(Record, Idx);
4769 TargetOpts.CPU = ReadString(Record, Idx);
4770 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 for (unsigned N = Record[Idx++]; N; --N) {
4772 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4773 }
4774 for (unsigned N = Record[Idx++]; N; --N) {
4775 TargetOpts.Features.push_back(ReadString(Record, Idx));
4776 }
4777
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004778 return Listener.ReadTargetOptions(TargetOpts, Complain,
4779 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004780}
4781
4782bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4783 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004784 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004786#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004787#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004788 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004789#include "clang/Basic/DiagnosticOptions.def"
4790
Richard Smith3be1cb22014-08-07 00:24:21 +00004791 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004792 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004793 for (unsigned N = Record[Idx++]; N; --N)
4794 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004795
4796 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4797}
4798
4799bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4800 ASTReaderListener &Listener) {
4801 FileSystemOptions FSOpts;
4802 unsigned Idx = 0;
4803 FSOpts.WorkingDir = ReadString(Record, Idx);
4804 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4805}
4806
4807bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4808 bool Complain,
4809 ASTReaderListener &Listener) {
4810 HeaderSearchOptions HSOpts;
4811 unsigned Idx = 0;
4812 HSOpts.Sysroot = ReadString(Record, Idx);
4813
4814 // Include entries.
4815 for (unsigned N = Record[Idx++]; N; --N) {
4816 std::string Path = ReadString(Record, Idx);
4817 frontend::IncludeDirGroup Group
4818 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 bool IsFramework = Record[Idx++];
4820 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004821 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4822 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 }
4824
4825 // System header prefixes.
4826 for (unsigned N = Record[Idx++]; N; --N) {
4827 std::string Prefix = ReadString(Record, Idx);
4828 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004829 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 }
4831
4832 HSOpts.ResourceDir = ReadString(Record, Idx);
4833 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004834 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 HSOpts.DisableModuleHash = Record[Idx++];
4836 HSOpts.UseBuiltinIncludes = Record[Idx++];
4837 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4838 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4839 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004840 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004841
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004842 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4843 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004844}
4845
4846bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4847 bool Complain,
4848 ASTReaderListener &Listener,
4849 std::string &SuggestedPredefines) {
4850 PreprocessorOptions PPOpts;
4851 unsigned Idx = 0;
4852
4853 // Macro definitions/undefs
4854 for (unsigned N = Record[Idx++]; N; --N) {
4855 std::string Macro = ReadString(Record, Idx);
4856 bool IsUndef = Record[Idx++];
4857 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4858 }
4859
4860 // Includes
4861 for (unsigned N = Record[Idx++]; N; --N) {
4862 PPOpts.Includes.push_back(ReadString(Record, Idx));
4863 }
4864
4865 // Macro Includes
4866 for (unsigned N = Record[Idx++]; N; --N) {
4867 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4868 }
4869
4870 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004871 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4873 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4874 PPOpts.ObjCXXARCStandardLibrary =
4875 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4876 SuggestedPredefines.clear();
4877 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4878 SuggestedPredefines);
4879}
4880
4881std::pair<ModuleFile *, unsigned>
4882ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4883 GlobalPreprocessedEntityMapType::iterator
4884 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4885 assert(I != GlobalPreprocessedEntityMap.end() &&
4886 "Corrupted global preprocessed entity map");
4887 ModuleFile *M = I->second;
4888 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4889 return std::make_pair(M, LocalIndex);
4890}
4891
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004892llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004893ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4894 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4895 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4896 Mod.NumPreprocessedEntities);
4897
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004898 return llvm::make_range(PreprocessingRecord::iterator(),
4899 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004900}
4901
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004902llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004903ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004904 return llvm::make_range(
4905 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4906 ModuleDeclIterator(this, &Mod,
4907 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004908}
4909
4910PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4911 PreprocessedEntityID PPID = Index+1;
4912 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4913 ModuleFile &M = *PPInfo.first;
4914 unsigned LocalIndex = PPInfo.second;
4915 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4916
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 if (!PP.getPreprocessingRecord()) {
4918 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004919 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 }
4921
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004922 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4923 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4924
4925 llvm::BitstreamEntry Entry =
4926 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4927 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004928 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004929
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00004931 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
4932 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004934 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 RecordData Record;
4936 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004937 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4938 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 switch (RecType) {
4940 case PPD_MACRO_EXPANSION: {
4941 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004942 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004943 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 if (isBuiltin)
4945 Name = getLocalIdentifier(M, Record[1]);
4946 else {
Richard Smith66a81862015-05-04 02:25:31 +00004947 PreprocessedEntityID GlobalID =
4948 getGlobalPreprocessedEntityID(M, Record[1]);
4949 Def = cast<MacroDefinitionRecord>(
4950 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 }
4952
4953 MacroExpansion *ME;
4954 if (isBuiltin)
4955 ME = new (PPRec) MacroExpansion(Name, Range);
4956 else
4957 ME = new (PPRec) MacroExpansion(Def, Range);
4958
4959 return ME;
4960 }
4961
4962 case PPD_MACRO_DEFINITION: {
4963 // Decode the identifier info and then check again; if the macro is
4964 // still defined and associated with the identifier,
4965 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004966 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004967
4968 if (DeserializationListener)
4969 DeserializationListener->MacroDefinitionRead(PPID, MD);
4970
4971 return MD;
4972 }
4973
4974 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004975 const char *FullFileNameStart = Blob.data() + Record[0];
4976 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004977 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 if (!FullFileName.empty())
4979 File = PP.getFileManager().getFile(FullFileName);
4980
4981 // FIXME: Stable encoding
4982 InclusionDirective::InclusionKind Kind
4983 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4984 InclusionDirective *ID
4985 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004986 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 Record[1], Record[3],
4988 File,
4989 Range);
4990 return ID;
4991 }
4992 }
4993
4994 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4995}
4996
4997/// \brief \arg SLocMapI points at a chunk of a module that contains no
4998/// preprocessed entities or the entities it contains are not the ones we are
4999/// looking for. Find the next module that contains entities and return the ID
5000/// of the first entry.
5001PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5002 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5003 ++SLocMapI;
5004 for (GlobalSLocOffsetMapType::const_iterator
5005 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5006 ModuleFile &M = *SLocMapI->second;
5007 if (M.NumPreprocessedEntities)
5008 return M.BasePreprocessedEntityID;
5009 }
5010
5011 return getTotalNumPreprocessedEntities();
5012}
5013
5014namespace {
5015
Guy Benyei11169dd2012-12-18 14:30:41 +00005016struct PPEntityComp {
5017 const ASTReader &Reader;
5018 ModuleFile &M;
5019
5020 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5021
5022 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5023 SourceLocation LHS = getLoc(L);
5024 SourceLocation RHS = getLoc(R);
5025 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5026 }
5027
5028 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5029 SourceLocation LHS = getLoc(L);
5030 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5031 }
5032
5033 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5034 SourceLocation RHS = getLoc(R);
5035 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5036 }
5037
5038 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005039 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 }
5041};
5042
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005043}
Guy Benyei11169dd2012-12-18 14:30:41 +00005044
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005045PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5046 bool EndsAfter) const {
5047 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 return getTotalNumPreprocessedEntities();
5049
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005050 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5051 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5053 "Corrupted global sloc offset map");
5054
5055 if (SLocMapI->second->NumPreprocessedEntities == 0)
5056 return findNextPreprocessedEntity(SLocMapI);
5057
5058 ModuleFile &M = *SLocMapI->second;
5059 typedef const PPEntityOffset *pp_iterator;
5060 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5061 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5062
5063 size_t Count = M.NumPreprocessedEntities;
5064 size_t Half;
5065 pp_iterator First = pp_begin;
5066 pp_iterator PPI;
5067
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005068 if (EndsAfter) {
5069 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005070 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005071 } else {
5072 // Do a binary search manually instead of using std::lower_bound because
5073 // The end locations of entities may be unordered (when a macro expansion
5074 // is inside another macro argument), but for this case it is not important
5075 // whether we get the first macro expansion or its containing macro.
5076 while (Count > 0) {
5077 Half = Count / 2;
5078 PPI = First;
5079 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005080 if (SourceMgr.isBeforeInTranslationUnit(
5081 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005082 First = PPI;
5083 ++First;
5084 Count = Count - Half - 1;
5085 } else
5086 Count = Half;
5087 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 }
5089
5090 if (PPI == pp_end)
5091 return findNextPreprocessedEntity(SLocMapI);
5092
5093 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5094}
5095
Guy Benyei11169dd2012-12-18 14:30:41 +00005096/// \brief Returns a pair of [Begin, End) indices of preallocated
5097/// preprocessed entities that \arg Range encompasses.
5098std::pair<unsigned, unsigned>
5099 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5100 if (Range.isInvalid())
5101 return std::make_pair(0,0);
5102 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5103
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005104 PreprocessedEntityID BeginID =
5105 findPreprocessedEntity(Range.getBegin(), false);
5106 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 return std::make_pair(BeginID, EndID);
5108}
5109
5110/// \brief Optionally returns true or false if the preallocated preprocessed
5111/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005112Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 FileID FID) {
5114 if (FID.isInvalid())
5115 return false;
5116
5117 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5118 ModuleFile &M = *PPInfo.first;
5119 unsigned LocalIndex = PPInfo.second;
5120 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5121
Richard Smithcb34bd32016-03-27 07:28:06 +00005122 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005123 if (Loc.isInvalid())
5124 return false;
5125
5126 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5127 return true;
5128 else
5129 return false;
5130}
5131
5132namespace {
5133 /// \brief Visitor used to search for information about a header file.
5134 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 const FileEntry *FE;
5136
David Blaikie05785d12013-02-20 22:23:23 +00005137 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005138
5139 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005140 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5141 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005142
5143 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 HeaderFileInfoLookupTable *Table
5145 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5146 if (!Table)
5147 return false;
5148
5149 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005150 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 if (Pos == Table->end())
5152 return false;
5153
Richard Smithbdf2d932015-07-30 03:37:16 +00005154 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 return true;
5156 }
5157
David Blaikie05785d12013-02-20 22:23:23 +00005158 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005160}
Guy Benyei11169dd2012-12-18 14:30:41 +00005161
5162HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005163 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005164 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005165 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005167
5168 return HeaderFileInfo();
5169}
5170
5171void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5172 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005173 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5175 ModuleFile &F = *(*I);
5176 unsigned Idx = 0;
5177 DiagStates.clear();
5178 assert(!Diag.DiagStates.empty());
5179 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5180 while (Idx < F.PragmaDiagMappings.size()) {
5181 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5182 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5183 if (DiagStateID != 0) {
5184 Diag.DiagStatePoints.push_back(
5185 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5186 FullSourceLoc(Loc, SourceMgr)));
5187 continue;
5188 }
5189
5190 assert(DiagStateID == 0);
5191 // A new DiagState was created here.
5192 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5193 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5194 DiagStates.push_back(NewState);
5195 Diag.DiagStatePoints.push_back(
5196 DiagnosticsEngine::DiagStatePoint(NewState,
5197 FullSourceLoc(Loc, SourceMgr)));
5198 while (1) {
5199 assert(Idx < F.PragmaDiagMappings.size() &&
5200 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5201 if (Idx >= F.PragmaDiagMappings.size()) {
5202 break; // Something is messed up but at least avoid infinite loop in
5203 // release build.
5204 }
5205 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5206 if (DiagID == (unsigned)-1) {
5207 break; // no more diag/map pairs for this location.
5208 }
Alp Tokerc726c362014-06-10 09:31:37 +00005209 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5210 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5211 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 }
5213 }
5214 }
5215}
5216
5217/// \brief Get the correct cursor and offset for loading a type.
5218ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5219 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5220 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5221 ModuleFile *M = I->second;
5222 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5223}
5224
5225/// \brief Read and return the type with the given index..
5226///
5227/// The index is the type ID, shifted and minus the number of predefs. This
5228/// routine actually reads the record corresponding to the type at the given
5229/// location. It is a helper routine for GetType, which deals with reading type
5230/// IDs.
5231QualType ASTReader::readTypeRecord(unsigned Index) {
5232 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005233 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005234
5235 // Keep track of where we are in the stream, then jump back there
5236 // after reading this type.
5237 SavedStreamPosition SavedPosition(DeclsCursor);
5238
5239 ReadingKindTracker ReadingKind(Read_Type, *this);
5240
5241 // Note that we are loading a type record.
5242 Deserializing AType(this);
5243
5244 unsigned Idx = 0;
5245 DeclsCursor.JumpToBit(Loc.Offset);
5246 RecordData Record;
5247 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005248 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005249 case TYPE_EXT_QUAL: {
5250 if (Record.size() != 2) {
5251 Error("Incorrect encoding of extended qualifier type");
5252 return QualType();
5253 }
5254 QualType Base = readType(*Loc.F, Record, Idx);
5255 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5256 return Context.getQualifiedType(Base, Quals);
5257 }
5258
5259 case TYPE_COMPLEX: {
5260 if (Record.size() != 1) {
5261 Error("Incorrect encoding of complex type");
5262 return QualType();
5263 }
5264 QualType ElemType = readType(*Loc.F, Record, Idx);
5265 return Context.getComplexType(ElemType);
5266 }
5267
5268 case TYPE_POINTER: {
5269 if (Record.size() != 1) {
5270 Error("Incorrect encoding of pointer type");
5271 return QualType();
5272 }
5273 QualType PointeeType = readType(*Loc.F, Record, Idx);
5274 return Context.getPointerType(PointeeType);
5275 }
5276
Reid Kleckner8a365022013-06-24 17:51:48 +00005277 case TYPE_DECAYED: {
5278 if (Record.size() != 1) {
5279 Error("Incorrect encoding of decayed type");
5280 return QualType();
5281 }
5282 QualType OriginalType = readType(*Loc.F, Record, Idx);
5283 QualType DT = Context.getAdjustedParameterType(OriginalType);
5284 if (!isa<DecayedType>(DT))
5285 Error("Decayed type does not decay");
5286 return DT;
5287 }
5288
Reid Kleckner0503a872013-12-05 01:23:43 +00005289 case TYPE_ADJUSTED: {
5290 if (Record.size() != 2) {
5291 Error("Incorrect encoding of adjusted type");
5292 return QualType();
5293 }
5294 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5295 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5296 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5297 }
5298
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 case TYPE_BLOCK_POINTER: {
5300 if (Record.size() != 1) {
5301 Error("Incorrect encoding of block pointer type");
5302 return QualType();
5303 }
5304 QualType PointeeType = readType(*Loc.F, Record, Idx);
5305 return Context.getBlockPointerType(PointeeType);
5306 }
5307
5308 case TYPE_LVALUE_REFERENCE: {
5309 if (Record.size() != 2) {
5310 Error("Incorrect encoding of lvalue reference type");
5311 return QualType();
5312 }
5313 QualType PointeeType = readType(*Loc.F, Record, Idx);
5314 return Context.getLValueReferenceType(PointeeType, Record[1]);
5315 }
5316
5317 case TYPE_RVALUE_REFERENCE: {
5318 if (Record.size() != 1) {
5319 Error("Incorrect encoding of rvalue reference type");
5320 return QualType();
5321 }
5322 QualType PointeeType = readType(*Loc.F, Record, Idx);
5323 return Context.getRValueReferenceType(PointeeType);
5324 }
5325
5326 case TYPE_MEMBER_POINTER: {
5327 if (Record.size() != 2) {
5328 Error("Incorrect encoding of member pointer type");
5329 return QualType();
5330 }
5331 QualType PointeeType = readType(*Loc.F, Record, Idx);
5332 QualType ClassType = readType(*Loc.F, Record, Idx);
5333 if (PointeeType.isNull() || ClassType.isNull())
5334 return QualType();
5335
5336 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5337 }
5338
5339 case TYPE_CONSTANT_ARRAY: {
5340 QualType ElementType = readType(*Loc.F, Record, Idx);
5341 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5342 unsigned IndexTypeQuals = Record[2];
5343 unsigned Idx = 3;
5344 llvm::APInt Size = ReadAPInt(Record, Idx);
5345 return Context.getConstantArrayType(ElementType, Size,
5346 ASM, IndexTypeQuals);
5347 }
5348
5349 case TYPE_INCOMPLETE_ARRAY: {
5350 QualType ElementType = readType(*Loc.F, Record, Idx);
5351 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5352 unsigned IndexTypeQuals = Record[2];
5353 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5354 }
5355
5356 case TYPE_VARIABLE_ARRAY: {
5357 QualType ElementType = readType(*Loc.F, Record, Idx);
5358 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5359 unsigned IndexTypeQuals = Record[2];
5360 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5361 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5362 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5363 ASM, IndexTypeQuals,
5364 SourceRange(LBLoc, RBLoc));
5365 }
5366
5367 case TYPE_VECTOR: {
5368 if (Record.size() != 3) {
5369 Error("incorrect encoding of vector type in AST file");
5370 return QualType();
5371 }
5372
5373 QualType ElementType = readType(*Loc.F, Record, Idx);
5374 unsigned NumElements = Record[1];
5375 unsigned VecKind = Record[2];
5376 return Context.getVectorType(ElementType, NumElements,
5377 (VectorType::VectorKind)VecKind);
5378 }
5379
5380 case TYPE_EXT_VECTOR: {
5381 if (Record.size() != 3) {
5382 Error("incorrect encoding of extended vector type in AST file");
5383 return QualType();
5384 }
5385
5386 QualType ElementType = readType(*Loc.F, Record, Idx);
5387 unsigned NumElements = Record[1];
5388 return Context.getExtVectorType(ElementType, NumElements);
5389 }
5390
5391 case TYPE_FUNCTION_NO_PROTO: {
5392 if (Record.size() != 6) {
5393 Error("incorrect encoding of no-proto function type");
5394 return QualType();
5395 }
5396 QualType ResultType = readType(*Loc.F, Record, Idx);
5397 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5398 (CallingConv)Record[4], Record[5]);
5399 return Context.getFunctionNoProtoType(ResultType, Info);
5400 }
5401
5402 case TYPE_FUNCTION_PROTO: {
5403 QualType ResultType = readType(*Loc.F, Record, Idx);
5404
5405 FunctionProtoType::ExtProtoInfo EPI;
5406 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5407 /*hasregparm*/ Record[2],
5408 /*regparm*/ Record[3],
5409 static_cast<CallingConv>(Record[4]),
5410 /*produces*/ Record[5]);
5411
5412 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005413
5414 EPI.Variadic = Record[Idx++];
5415 EPI.HasTrailingReturn = Record[Idx++];
5416 EPI.TypeQuals = Record[Idx++];
5417 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005418 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005419 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005420
5421 unsigned NumParams = Record[Idx++];
5422 SmallVector<QualType, 16> ParamTypes;
5423 for (unsigned I = 0; I != NumParams; ++I)
5424 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5425
John McCall18afab72016-03-01 00:49:02 +00005426 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5427 if (Idx != Record.size()) {
5428 for (unsigned I = 0; I != NumParams; ++I)
5429 ExtParameterInfos.push_back(
5430 FunctionProtoType::ExtParameterInfo
5431 ::getFromOpaqueValue(Record[Idx++]));
5432 EPI.ExtParameterInfos = ExtParameterInfos.data();
5433 }
5434
5435 assert(Idx == Record.size());
5436
Jordan Rose5c382722013-03-08 21:51:21 +00005437 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005438 }
5439
5440 case TYPE_UNRESOLVED_USING: {
5441 unsigned Idx = 0;
5442 return Context.getTypeDeclType(
5443 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5444 }
5445
5446 case TYPE_TYPEDEF: {
5447 if (Record.size() != 2) {
5448 Error("incorrect encoding of typedef type");
5449 return QualType();
5450 }
5451 unsigned Idx = 0;
5452 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5453 QualType Canonical = readType(*Loc.F, Record, Idx);
5454 if (!Canonical.isNull())
5455 Canonical = Context.getCanonicalType(Canonical);
5456 return Context.getTypedefType(Decl, Canonical);
5457 }
5458
5459 case TYPE_TYPEOF_EXPR:
5460 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5461
5462 case TYPE_TYPEOF: {
5463 if (Record.size() != 1) {
5464 Error("incorrect encoding of typeof(type) in AST file");
5465 return QualType();
5466 }
5467 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5468 return Context.getTypeOfType(UnderlyingType);
5469 }
5470
5471 case TYPE_DECLTYPE: {
5472 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5473 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5474 }
5475
5476 case TYPE_UNARY_TRANSFORM: {
5477 QualType BaseType = readType(*Loc.F, Record, Idx);
5478 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5479 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5480 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5481 }
5482
Richard Smith74aeef52013-04-26 16:15:35 +00005483 case TYPE_AUTO: {
5484 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005485 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005486 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005487 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005488 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005489
5490 case TYPE_RECORD: {
5491 if (Record.size() != 2) {
5492 Error("incorrect encoding of record type");
5493 return QualType();
5494 }
5495 unsigned Idx = 0;
5496 bool IsDependent = Record[Idx++];
5497 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5498 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5499 QualType T = Context.getRecordType(RD);
5500 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5501 return T;
5502 }
5503
5504 case TYPE_ENUM: {
5505 if (Record.size() != 2) {
5506 Error("incorrect encoding of enum type");
5507 return QualType();
5508 }
5509 unsigned Idx = 0;
5510 bool IsDependent = Record[Idx++];
5511 QualType T
5512 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5513 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5514 return T;
5515 }
5516
5517 case TYPE_ATTRIBUTED: {
5518 if (Record.size() != 3) {
5519 Error("incorrect encoding of attributed type");
5520 return QualType();
5521 }
5522 QualType modifiedType = readType(*Loc.F, Record, Idx);
5523 QualType equivalentType = readType(*Loc.F, Record, Idx);
5524 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5525 return Context.getAttributedType(kind, modifiedType, equivalentType);
5526 }
5527
5528 case TYPE_PAREN: {
5529 if (Record.size() != 1) {
5530 Error("incorrect encoding of paren type");
5531 return QualType();
5532 }
5533 QualType InnerType = readType(*Loc.F, Record, Idx);
5534 return Context.getParenType(InnerType);
5535 }
5536
5537 case TYPE_PACK_EXPANSION: {
5538 if (Record.size() != 2) {
5539 Error("incorrect encoding of pack expansion type");
5540 return QualType();
5541 }
5542 QualType Pattern = readType(*Loc.F, Record, Idx);
5543 if (Pattern.isNull())
5544 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005545 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 if (Record[1])
5547 NumExpansions = Record[1] - 1;
5548 return Context.getPackExpansionType(Pattern, NumExpansions);
5549 }
5550
5551 case TYPE_ELABORATED: {
5552 unsigned Idx = 0;
5553 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5554 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5555 QualType NamedType = readType(*Loc.F, Record, Idx);
5556 return Context.getElaboratedType(Keyword, NNS, NamedType);
5557 }
5558
5559 case TYPE_OBJC_INTERFACE: {
5560 unsigned Idx = 0;
5561 ObjCInterfaceDecl *ItfD
5562 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5563 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5564 }
5565
5566 case TYPE_OBJC_OBJECT: {
5567 unsigned Idx = 0;
5568 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005569 unsigned NumTypeArgs = Record[Idx++];
5570 SmallVector<QualType, 4> TypeArgs;
5571 for (unsigned I = 0; I != NumTypeArgs; ++I)
5572 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005573 unsigned NumProtos = Record[Idx++];
5574 SmallVector<ObjCProtocolDecl*, 4> Protos;
5575 for (unsigned I = 0; I != NumProtos; ++I)
5576 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005577 bool IsKindOf = Record[Idx++];
5578 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 }
5580
5581 case TYPE_OBJC_OBJECT_POINTER: {
5582 unsigned Idx = 0;
5583 QualType Pointee = readType(*Loc.F, Record, Idx);
5584 return Context.getObjCObjectPointerType(Pointee);
5585 }
5586
5587 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5588 unsigned Idx = 0;
5589 QualType Parm = readType(*Loc.F, Record, Idx);
5590 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005591 return Context.getSubstTemplateTypeParmType(
5592 cast<TemplateTypeParmType>(Parm),
5593 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005594 }
5595
5596 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5597 unsigned Idx = 0;
5598 QualType Parm = readType(*Loc.F, Record, Idx);
5599 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5600 return Context.getSubstTemplateTypeParmPackType(
5601 cast<TemplateTypeParmType>(Parm),
5602 ArgPack);
5603 }
5604
5605 case TYPE_INJECTED_CLASS_NAME: {
5606 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5607 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5608 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5609 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005610 const Type *T = nullptr;
5611 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5612 if (const Type *Existing = DI->getTypeForDecl()) {
5613 T = Existing;
5614 break;
5615 }
5616 }
5617 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005618 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005619 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5620 DI->setTypeForDecl(T);
5621 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005622 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 }
5624
5625 case TYPE_TEMPLATE_TYPE_PARM: {
5626 unsigned Idx = 0;
5627 unsigned Depth = Record[Idx++];
5628 unsigned Index = Record[Idx++];
5629 bool Pack = Record[Idx++];
5630 TemplateTypeParmDecl *D
5631 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5632 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5633 }
5634
5635 case TYPE_DEPENDENT_NAME: {
5636 unsigned Idx = 0;
5637 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5638 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005639 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 QualType Canon = readType(*Loc.F, Record, Idx);
5641 if (!Canon.isNull())
5642 Canon = Context.getCanonicalType(Canon);
5643 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5644 }
5645
5646 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5647 unsigned Idx = 0;
5648 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5649 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005650 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005651 unsigned NumArgs = Record[Idx++];
5652 SmallVector<TemplateArgument, 8> Args;
5653 Args.reserve(NumArgs);
5654 while (NumArgs--)
5655 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5656 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005657 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 }
5659
5660 case TYPE_DEPENDENT_SIZED_ARRAY: {
5661 unsigned Idx = 0;
5662
5663 // ArrayType
5664 QualType ElementType = readType(*Loc.F, Record, Idx);
5665 ArrayType::ArraySizeModifier ASM
5666 = (ArrayType::ArraySizeModifier)Record[Idx++];
5667 unsigned IndexTypeQuals = Record[Idx++];
5668
5669 // DependentSizedArrayType
5670 Expr *NumElts = ReadExpr(*Loc.F);
5671 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5672
5673 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5674 IndexTypeQuals, Brackets);
5675 }
5676
5677 case TYPE_TEMPLATE_SPECIALIZATION: {
5678 unsigned Idx = 0;
5679 bool IsDependent = Record[Idx++];
5680 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5681 SmallVector<TemplateArgument, 8> Args;
5682 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5683 QualType Underlying = readType(*Loc.F, Record, Idx);
5684 QualType T;
5685 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005686 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005687 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005688 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5690 return T;
5691 }
5692
5693 case TYPE_ATOMIC: {
5694 if (Record.size() != 1) {
5695 Error("Incorrect encoding of atomic type");
5696 return QualType();
5697 }
5698 QualType ValueType = readType(*Loc.F, Record, Idx);
5699 return Context.getAtomicType(ValueType);
5700 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005701
5702 case TYPE_PIPE: {
5703 if (Record.size() != 1) {
5704 Error("Incorrect encoding of pipe type");
5705 return QualType();
5706 }
5707
5708 // Reading the pipe element type.
5709 QualType ElementType = readType(*Loc.F, Record, Idx);
5710 return Context.getPipeType(ElementType);
5711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 }
5713 llvm_unreachable("Invalid TypeCode!");
5714}
5715
Richard Smith564417a2014-03-20 21:47:22 +00005716void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5717 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005718 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005719 const RecordData &Record, unsigned &Idx) {
5720 ExceptionSpecificationType EST =
5721 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005722 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005723 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005724 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005725 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005726 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005727 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005728 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005729 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005730 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5731 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005732 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005733 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005734 }
5735}
5736
Guy Benyei11169dd2012-12-18 14:30:41 +00005737class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5738 ASTReader &Reader;
5739 ModuleFile &F;
5740 const ASTReader::RecordData &Record;
5741 unsigned &Idx;
5742
5743 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5744 unsigned &I) {
5745 return Reader.ReadSourceLocation(F, R, I);
5746 }
5747
5748 template<typename T>
5749 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5750 return Reader.ReadDeclAs<T>(F, Record, Idx);
5751 }
5752
5753public:
5754 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5755 const ASTReader::RecordData &Record, unsigned &Idx)
5756 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5757 { }
5758
5759 // We want compile-time assurance that we've enumerated all of
5760 // these, so unfortunately we have to declare them first, then
5761 // define them out-of-line.
5762#define ABSTRACT_TYPELOC(CLASS, PARENT)
5763#define TYPELOC(CLASS, PARENT) \
5764 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5765#include "clang/AST/TypeLocNodes.def"
5766
5767 void VisitFunctionTypeLoc(FunctionTypeLoc);
5768 void VisitArrayTypeLoc(ArrayTypeLoc);
5769};
5770
5771void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5772 // nothing to do
5773}
5774void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5775 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5776 if (TL.needsExtraLocalData()) {
5777 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5778 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5779 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5780 TL.setModeAttr(Record[Idx++]);
5781 }
5782}
5783void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5784 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5787 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5788}
Reid Kleckner8a365022013-06-24 17:51:48 +00005789void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5790 // nothing to do
5791}
Reid Kleckner0503a872013-12-05 01:23:43 +00005792void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5793 // nothing to do
5794}
Guy Benyei11169dd2012-12-18 14:30:41 +00005795void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5796 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5799 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5800}
5801void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5802 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5803}
5804void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5805 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5806 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5807}
5808void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5809 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5810 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5811 if (Record[Idx++])
5812 TL.setSizeExpr(Reader.ReadExpr(F));
5813 else
Craig Toppera13603a2014-05-22 05:54:18 +00005814 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815}
5816void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5817 VisitArrayTypeLoc(TL);
5818}
5819void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5820 VisitArrayTypeLoc(TL);
5821}
5822void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5823 VisitArrayTypeLoc(TL);
5824}
5825void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5826 DependentSizedArrayTypeLoc TL) {
5827 VisitArrayTypeLoc(TL);
5828}
5829void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5830 DependentSizedExtVectorTypeLoc TL) {
5831 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5832}
5833void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5835}
5836void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5837 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5838}
5839void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5840 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5841 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5842 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5843 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005844 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5845 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 }
5847}
5848void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5849 VisitFunctionTypeLoc(TL);
5850}
5851void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5852 VisitFunctionTypeLoc(TL);
5853}
5854void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5855 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5856}
5857void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5858 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5859}
5860void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5861 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5862 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5863 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5864}
5865void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5866 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5867 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5868 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5869 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5870}
5871void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5872 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5873}
5874void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5875 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5876 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5877 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5878 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5879}
5880void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5881 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5882}
5883void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5884 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5885}
5886void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5887 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5888}
5889void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5890 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5891 if (TL.hasAttrOperand()) {
5892 SourceRange range;
5893 range.setBegin(ReadSourceLocation(Record, Idx));
5894 range.setEnd(ReadSourceLocation(Record, Idx));
5895 TL.setAttrOperandParensRange(range);
5896 }
5897 if (TL.hasAttrExprOperand()) {
5898 if (Record[Idx++])
5899 TL.setAttrExprOperand(Reader.ReadExpr(F));
5900 else
Craig Toppera13603a2014-05-22 05:54:18 +00005901 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005902 } else if (TL.hasAttrEnumOperand())
5903 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5904}
5905void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5906 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5907}
5908void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5909 SubstTemplateTypeParmTypeLoc TL) {
5910 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5911}
5912void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5913 SubstTemplateTypeParmPackTypeLoc TL) {
5914 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5915}
5916void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5917 TemplateSpecializationTypeLoc TL) {
5918 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5919 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5920 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5921 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5922 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5923 TL.setArgLocInfo(i,
5924 Reader.GetTemplateArgumentLocInfo(F,
5925 TL.getTypePtr()->getArg(i).getKind(),
5926 Record, Idx));
5927}
5928void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5929 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5930 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5931}
5932void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5933 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5934 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5935}
5936void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5937 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5938}
5939void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5940 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5941 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5942 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5943}
5944void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5945 DependentTemplateSpecializationTypeLoc TL) {
5946 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5947 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5948 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5949 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5950 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5951 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5952 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5953 TL.setArgLocInfo(I,
5954 Reader.GetTemplateArgumentLocInfo(F,
5955 TL.getTypePtr()->getArg(I).getKind(),
5956 Record, Idx));
5957}
5958void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5959 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5960}
5961void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5962 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5963}
5964void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5965 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005966 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5967 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5968 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5969 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5970 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5971 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5973 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5974}
5975void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5976 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5977}
5978void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5979 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5980 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5981 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5982}
Xiuli Pan9c14e282016-01-09 12:53:17 +00005983void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5984 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5985}
Guy Benyei11169dd2012-12-18 14:30:41 +00005986
5987TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5988 const RecordData &Record,
5989 unsigned &Idx) {
5990 QualType InfoTy = readType(F, Record, Idx);
5991 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005992 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005993
5994 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5995 TypeLocReader TLR(*this, F, Record, Idx);
5996 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5997 TLR.Visit(TL);
5998 return TInfo;
5999}
6000
6001QualType ASTReader::GetType(TypeID ID) {
6002 unsigned FastQuals = ID & Qualifiers::FastMask;
6003 unsigned Index = ID >> Qualifiers::FastWidth;
6004
6005 if (Index < NUM_PREDEF_TYPE_IDS) {
6006 QualType T;
6007 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006008 case PREDEF_TYPE_NULL_ID:
6009 return QualType();
6010 case PREDEF_TYPE_VOID_ID:
6011 T = Context.VoidTy;
6012 break;
6013 case PREDEF_TYPE_BOOL_ID:
6014 T = Context.BoolTy;
6015 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006016
6017 case PREDEF_TYPE_CHAR_U_ID:
6018 case PREDEF_TYPE_CHAR_S_ID:
6019 // FIXME: Check that the signedness of CharTy is correct!
6020 T = Context.CharTy;
6021 break;
6022
Alexey Baderbdf7c842015-09-15 12:18:29 +00006023 case PREDEF_TYPE_UCHAR_ID:
6024 T = Context.UnsignedCharTy;
6025 break;
6026 case PREDEF_TYPE_USHORT_ID:
6027 T = Context.UnsignedShortTy;
6028 break;
6029 case PREDEF_TYPE_UINT_ID:
6030 T = Context.UnsignedIntTy;
6031 break;
6032 case PREDEF_TYPE_ULONG_ID:
6033 T = Context.UnsignedLongTy;
6034 break;
6035 case PREDEF_TYPE_ULONGLONG_ID:
6036 T = Context.UnsignedLongLongTy;
6037 break;
6038 case PREDEF_TYPE_UINT128_ID:
6039 T = Context.UnsignedInt128Ty;
6040 break;
6041 case PREDEF_TYPE_SCHAR_ID:
6042 T = Context.SignedCharTy;
6043 break;
6044 case PREDEF_TYPE_WCHAR_ID:
6045 T = Context.WCharTy;
6046 break;
6047 case PREDEF_TYPE_SHORT_ID:
6048 T = Context.ShortTy;
6049 break;
6050 case PREDEF_TYPE_INT_ID:
6051 T = Context.IntTy;
6052 break;
6053 case PREDEF_TYPE_LONG_ID:
6054 T = Context.LongTy;
6055 break;
6056 case PREDEF_TYPE_LONGLONG_ID:
6057 T = Context.LongLongTy;
6058 break;
6059 case PREDEF_TYPE_INT128_ID:
6060 T = Context.Int128Ty;
6061 break;
6062 case PREDEF_TYPE_HALF_ID:
6063 T = Context.HalfTy;
6064 break;
6065 case PREDEF_TYPE_FLOAT_ID:
6066 T = Context.FloatTy;
6067 break;
6068 case PREDEF_TYPE_DOUBLE_ID:
6069 T = Context.DoubleTy;
6070 break;
6071 case PREDEF_TYPE_LONGDOUBLE_ID:
6072 T = Context.LongDoubleTy;
6073 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006074 case PREDEF_TYPE_FLOAT128_ID:
6075 T = Context.Float128Ty;
6076 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006077 case PREDEF_TYPE_OVERLOAD_ID:
6078 T = Context.OverloadTy;
6079 break;
6080 case PREDEF_TYPE_BOUND_MEMBER:
6081 T = Context.BoundMemberTy;
6082 break;
6083 case PREDEF_TYPE_PSEUDO_OBJECT:
6084 T = Context.PseudoObjectTy;
6085 break;
6086 case PREDEF_TYPE_DEPENDENT_ID:
6087 T = Context.DependentTy;
6088 break;
6089 case PREDEF_TYPE_UNKNOWN_ANY:
6090 T = Context.UnknownAnyTy;
6091 break;
6092 case PREDEF_TYPE_NULLPTR_ID:
6093 T = Context.NullPtrTy;
6094 break;
6095 case PREDEF_TYPE_CHAR16_ID:
6096 T = Context.Char16Ty;
6097 break;
6098 case PREDEF_TYPE_CHAR32_ID:
6099 T = Context.Char32Ty;
6100 break;
6101 case PREDEF_TYPE_OBJC_ID:
6102 T = Context.ObjCBuiltinIdTy;
6103 break;
6104 case PREDEF_TYPE_OBJC_CLASS:
6105 T = Context.ObjCBuiltinClassTy;
6106 break;
6107 case PREDEF_TYPE_OBJC_SEL:
6108 T = Context.ObjCBuiltinSelTy;
6109 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006110#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6111 case PREDEF_TYPE_##Id##_ID: \
6112 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006113 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006114#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006115 case PREDEF_TYPE_SAMPLER_ID:
6116 T = Context.OCLSamplerTy;
6117 break;
6118 case PREDEF_TYPE_EVENT_ID:
6119 T = Context.OCLEventTy;
6120 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006121 case PREDEF_TYPE_CLK_EVENT_ID:
6122 T = Context.OCLClkEventTy;
6123 break;
6124 case PREDEF_TYPE_QUEUE_ID:
6125 T = Context.OCLQueueTy;
6126 break;
6127 case PREDEF_TYPE_NDRANGE_ID:
6128 T = Context.OCLNDRangeTy;
6129 break;
6130 case PREDEF_TYPE_RESERVE_ID_ID:
6131 T = Context.OCLReserveIDTy;
6132 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006133 case PREDEF_TYPE_AUTO_DEDUCT:
6134 T = Context.getAutoDeductType();
6135 break;
6136
6137 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6138 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006139 break;
6140
6141 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6142 T = Context.ARCUnbridgedCastTy;
6143 break;
6144
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 case PREDEF_TYPE_BUILTIN_FN:
6146 T = Context.BuiltinFnTy;
6147 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006148
6149 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6150 T = Context.OMPArraySectionTy;
6151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 }
6153
6154 assert(!T.isNull() && "Unknown predefined type");
6155 return T.withFastQualifiers(FastQuals);
6156 }
6157
6158 Index -= NUM_PREDEF_TYPE_IDS;
6159 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6160 if (TypesLoaded[Index].isNull()) {
6161 TypesLoaded[Index] = readTypeRecord(Index);
6162 if (TypesLoaded[Index].isNull())
6163 return QualType();
6164
6165 TypesLoaded[Index]->setFromAST();
6166 if (DeserializationListener)
6167 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6168 TypesLoaded[Index]);
6169 }
6170
6171 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6172}
6173
6174QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6175 return GetType(getGlobalTypeID(F, LocalID));
6176}
6177
6178serialization::TypeID
6179ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6180 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6181 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6182
6183 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6184 return LocalID;
6185
6186 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6187 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6188 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6189
6190 unsigned GlobalIndex = LocalIndex + I->second;
6191 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6192}
6193
6194TemplateArgumentLocInfo
6195ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6196 TemplateArgument::ArgKind Kind,
6197 const RecordData &Record,
6198 unsigned &Index) {
6199 switch (Kind) {
6200 case TemplateArgument::Expression:
6201 return ReadExpr(F);
6202 case TemplateArgument::Type:
6203 return GetTypeSourceInfo(F, Record, Index);
6204 case TemplateArgument::Template: {
6205 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6206 Index);
6207 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6208 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6209 SourceLocation());
6210 }
6211 case TemplateArgument::TemplateExpansion: {
6212 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6213 Index);
6214 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6215 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6216 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6217 EllipsisLoc);
6218 }
6219 case TemplateArgument::Null:
6220 case TemplateArgument::Integral:
6221 case TemplateArgument::Declaration:
6222 case TemplateArgument::NullPtr:
6223 case TemplateArgument::Pack:
6224 // FIXME: Is this right?
6225 return TemplateArgumentLocInfo();
6226 }
6227 llvm_unreachable("unexpected template argument loc");
6228}
6229
6230TemplateArgumentLoc
6231ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6232 const RecordData &Record, unsigned &Index) {
6233 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6234
6235 if (Arg.getKind() == TemplateArgument::Expression) {
6236 if (Record[Index++]) // bool InfoHasSameExpr.
6237 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6238 }
6239 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6240 Record, Index));
6241}
6242
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006243const ASTTemplateArgumentListInfo*
6244ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6245 const RecordData &Record,
6246 unsigned &Index) {
6247 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6248 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6249 unsigned NumArgsAsWritten = Record[Index++];
6250 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6251 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6252 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6253 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6254}
6255
Guy Benyei11169dd2012-12-18 14:30:41 +00006256Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6257 return GetDecl(ID);
6258}
6259
Richard Smith50895422015-01-31 03:04:55 +00006260template<typename TemplateSpecializationDecl>
6261static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6262 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6263 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6264}
6265
Richard Smith053f6c62014-05-16 23:01:30 +00006266void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006267 if (NumCurrentElementsDeserializing) {
6268 // We arrange to not care about the complete redeclaration chain while we're
6269 // deserializing. Just remember that the AST has marked this one as complete
6270 // but that it's not actually complete yet, so we know we still need to
6271 // complete it later.
6272 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6273 return;
6274 }
6275
Richard Smith053f6c62014-05-16 23:01:30 +00006276 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6277
Richard Smith053f6c62014-05-16 23:01:30 +00006278 // If this is a named declaration, complete it by looking it up
6279 // within its context.
6280 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006281 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006282 // all mergeable entities within it.
6283 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6284 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6285 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006286 if (!getContext().getLangOpts().CPlusPlus &&
6287 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006288 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006289 // the identifier instead. (For C++ modules, we don't store decls
6290 // in the serialized identifier table, so we do the lookup in the TU.)
6291 auto *II = Name.getAsIdentifierInfo();
6292 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006293 if (II->isOutOfDate())
6294 updateOutOfDateIdentifier(*II);
6295 } else
6296 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006297 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006298 // Find all declarations of this kind from the relevant context.
6299 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6300 auto *DC = cast<DeclContext>(DCDecl);
6301 SmallVector<Decl*, 8> Decls;
6302 FindExternalLexicalDecls(
6303 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6304 }
Richard Smith053f6c62014-05-16 23:01:30 +00006305 }
6306 }
Richard Smith50895422015-01-31 03:04:55 +00006307
6308 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6309 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6310 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6311 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6312 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6313 if (auto *Template = FD->getPrimaryTemplate())
6314 Template->LoadLazySpecializations();
6315 }
Richard Smith053f6c62014-05-16 23:01:30 +00006316}
6317
Richard Smithc2bb8182015-03-24 06:36:48 +00006318CXXCtorInitializer **
6319ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6320 RecordLocation Loc = getLocalBitOffset(Offset);
6321 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6322 SavedStreamPosition SavedPosition(Cursor);
6323 Cursor.JumpToBit(Loc.Offset);
6324 ReadingKindTracker ReadingKind(Read_Decl, *this);
6325
6326 RecordData Record;
6327 unsigned Code = Cursor.ReadCode();
6328 unsigned RecCode = Cursor.readRecord(Code, Record);
6329 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6330 Error("malformed AST file: missing C++ ctor initializers");
6331 return nullptr;
6332 }
6333
6334 unsigned Idx = 0;
6335 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6336}
6337
Guy Benyei11169dd2012-12-18 14:30:41 +00006338CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6339 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006340 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 SavedStreamPosition SavedPosition(Cursor);
6342 Cursor.JumpToBit(Loc.Offset);
6343 ReadingKindTracker ReadingKind(Read_Decl, *this);
6344 RecordData Record;
6345 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006346 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006348 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006349 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 }
6351
6352 unsigned Idx = 0;
6353 unsigned NumBases = Record[Idx++];
6354 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6355 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6356 for (unsigned I = 0; I != NumBases; ++I)
6357 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6358 return Bases;
6359}
6360
6361serialization::DeclID
6362ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6363 if (LocalID < NUM_PREDEF_DECL_IDS)
6364 return LocalID;
6365
6366 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6367 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6368 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6369
6370 return LocalID + I->second;
6371}
6372
6373bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6374 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006375 // Predefined decls aren't from any module.
6376 if (ID < NUM_PREDEF_DECL_IDS)
6377 return false;
6378
Richard Smithbcda1a92015-07-12 23:51:20 +00006379 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6380 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006381}
6382
Douglas Gregor9f782892013-01-21 15:25:38 +00006383ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006385 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6387 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6388 return I->second;
6389}
6390
6391SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6392 if (ID < NUM_PREDEF_DECL_IDS)
6393 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006394
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6396
6397 if (Index > DeclsLoaded.size()) {
6398 Error("declaration ID out-of-range for AST file");
6399 return SourceLocation();
6400 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006401
Guy Benyei11169dd2012-12-18 14:30:41 +00006402 if (Decl *D = DeclsLoaded[Index])
6403 return D->getLocation();
6404
Richard Smithcb34bd32016-03-27 07:28:06 +00006405 SourceLocation Loc;
6406 DeclCursorForID(ID, Loc);
6407 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006408}
6409
Richard Smithfe620d22015-03-05 23:24:12 +00006410static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6411 switch (ID) {
6412 case PREDEF_DECL_NULL_ID:
6413 return nullptr;
6414
6415 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6416 return Context.getTranslationUnitDecl();
6417
6418 case PREDEF_DECL_OBJC_ID_ID:
6419 return Context.getObjCIdDecl();
6420
6421 case PREDEF_DECL_OBJC_SEL_ID:
6422 return Context.getObjCSelDecl();
6423
6424 case PREDEF_DECL_OBJC_CLASS_ID:
6425 return Context.getObjCClassDecl();
6426
6427 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6428 return Context.getObjCProtocolDecl();
6429
6430 case PREDEF_DECL_INT_128_ID:
6431 return Context.getInt128Decl();
6432
6433 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6434 return Context.getUInt128Decl();
6435
6436 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6437 return Context.getObjCInstanceTypeDecl();
6438
6439 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6440 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006441
Richard Smith9b88a4c2015-07-27 05:40:23 +00006442 case PREDEF_DECL_VA_LIST_TAG:
6443 return Context.getVaListTagDecl();
6444
Charles Davisc7d5c942015-09-17 20:55:33 +00006445 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6446 return Context.getBuiltinMSVaListDecl();
6447
Richard Smithf19e1272015-03-07 00:04:49 +00006448 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6449 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006450
6451 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6452 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006453
6454 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6455 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006456
6457 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6458 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006459
6460 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6461 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006462 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006463 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006464}
6465
Richard Smithcd45dbc2014-04-19 03:48:30 +00006466Decl *ASTReader::GetExistingDecl(DeclID ID) {
6467 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006468 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6469 if (D) {
6470 // Track that we have merged the declaration with ID \p ID into the
6471 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006472 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006473 if (Merged.empty())
6474 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006475 }
Richard Smithfe620d22015-03-05 23:24:12 +00006476 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6480
6481 if (Index >= DeclsLoaded.size()) {
6482 assert(0 && "declaration ID out-of-range for AST file");
6483 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006484 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006486
6487 return DeclsLoaded[Index];
6488}
6489
6490Decl *ASTReader::GetDecl(DeclID ID) {
6491 if (ID < NUM_PREDEF_DECL_IDS)
6492 return GetExistingDecl(ID);
6493
6494 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6495
6496 if (Index >= DeclsLoaded.size()) {
6497 assert(0 && "declaration ID out-of-range for AST file");
6498 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006499 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006500 }
6501
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 if (!DeclsLoaded[Index]) {
6503 ReadDeclRecord(ID);
6504 if (DeserializationListener)
6505 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6506 }
6507
6508 return DeclsLoaded[Index];
6509}
6510
6511DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6512 DeclID GlobalID) {
6513 if (GlobalID < NUM_PREDEF_DECL_IDS)
6514 return GlobalID;
6515
6516 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6517 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6518 ModuleFile *Owner = I->second;
6519
6520 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6521 = M.GlobalToLocalDeclIDs.find(Owner);
6522 if (Pos == M.GlobalToLocalDeclIDs.end())
6523 return 0;
6524
6525 return GlobalID - Owner->BaseDeclID + Pos->second;
6526}
6527
6528serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6529 const RecordData &Record,
6530 unsigned &Idx) {
6531 if (Idx >= Record.size()) {
6532 Error("Corrupted AST file");
6533 return 0;
6534 }
6535
6536 return getGlobalDeclID(F, Record[Idx++]);
6537}
6538
6539/// \brief Resolve the offset of a statement into a statement.
6540///
6541/// This operation will read a new statement from the external
6542/// source each time it is called, and is meant to be used via a
6543/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6544Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6545 // Switch case IDs are per Decl.
6546 ClearSwitchCaseIDs();
6547
6548 // Offset here is a global offset across the entire chain.
6549 RecordLocation Loc = getLocalBitOffset(Offset);
6550 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6551 return ReadStmtFromStream(*Loc.F);
6552}
6553
Richard Smith3cb15722015-08-05 22:41:45 +00006554void ASTReader::FindExternalLexicalDecls(
6555 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6556 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006557 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6558
Richard Smith9ccdd932015-08-06 22:14:12 +00006559 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006560 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6561 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6562 auto K = (Decl::Kind)+LexicalDecls[I];
6563 if (!IsKindWeWant(K))
6564 continue;
6565
6566 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6567
6568 // Don't add predefined declarations to the lexical context more
6569 // than once.
6570 if (ID < NUM_PREDEF_DECL_IDS) {
6571 if (PredefsVisited[ID])
6572 continue;
6573
6574 PredefsVisited[ID] = true;
6575 }
6576
6577 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006578 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006579 if (!DC->isDeclInLexicalTraversal(D))
6580 Decls.push_back(D);
6581 }
6582 }
6583 };
6584
6585 if (isa<TranslationUnitDecl>(DC)) {
6586 for (auto Lexical : TULexicalDecls)
6587 Visit(Lexical.first, Lexical.second);
6588 } else {
6589 auto I = LexicalDecls.find(DC);
6590 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006591 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006592 }
6593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006595}
6596
6597namespace {
6598
6599class DeclIDComp {
6600 ASTReader &Reader;
6601 ModuleFile &Mod;
6602
6603public:
6604 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6605
6606 bool operator()(LocalDeclID L, LocalDeclID R) const {
6607 SourceLocation LHS = getLocation(L);
6608 SourceLocation RHS = getLocation(R);
6609 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6610 }
6611
6612 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6613 SourceLocation RHS = getLocation(R);
6614 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6615 }
6616
6617 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6618 SourceLocation LHS = getLocation(L);
6619 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6620 }
6621
6622 SourceLocation getLocation(LocalDeclID ID) const {
6623 return Reader.getSourceManager().getFileLoc(
6624 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6625 }
6626};
6627
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006628}
Guy Benyei11169dd2012-12-18 14:30:41 +00006629
6630void ASTReader::FindFileRegionDecls(FileID File,
6631 unsigned Offset, unsigned Length,
6632 SmallVectorImpl<Decl *> &Decls) {
6633 SourceManager &SM = getSourceManager();
6634
6635 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6636 if (I == FileDeclIDs.end())
6637 return;
6638
6639 FileDeclsInfo &DInfo = I->second;
6640 if (DInfo.Decls.empty())
6641 return;
6642
6643 SourceLocation
6644 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6645 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6646
6647 DeclIDComp DIDComp(*this, *DInfo.Mod);
6648 ArrayRef<serialization::LocalDeclID>::iterator
6649 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6650 BeginLoc, DIDComp);
6651 if (BeginIt != DInfo.Decls.begin())
6652 --BeginIt;
6653
6654 // If we are pointing at a top-level decl inside an objc container, we need
6655 // to backtrack until we find it otherwise we will fail to report that the
6656 // region overlaps with an objc container.
6657 while (BeginIt != DInfo.Decls.begin() &&
6658 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6659 ->isTopLevelDeclInObjCContainer())
6660 --BeginIt;
6661
6662 ArrayRef<serialization::LocalDeclID>::iterator
6663 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6664 EndLoc, DIDComp);
6665 if (EndIt != DInfo.Decls.end())
6666 ++EndIt;
6667
6668 for (ArrayRef<serialization::LocalDeclID>::iterator
6669 DIt = BeginIt; DIt != EndIt; ++DIt)
6670 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6671}
6672
Richard Smith9ce12e32013-02-07 03:30:24 +00006673bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006674ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6675 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006676 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006677 "DeclContext has no visible decls in storage");
6678 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006679 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006680
Richard Smithd88a7f12015-09-01 20:35:42 +00006681 auto It = Lookups.find(DC);
6682 if (It == Lookups.end())
6683 return false;
6684
Richard Smith8c913ec2014-08-14 02:21:01 +00006685 Deserializing LookupResults(this);
6686
Richard Smithd88a7f12015-09-01 20:35:42 +00006687 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006689 for (DeclID ID : It->second.Table.find(Name)) {
6690 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6691 if (ND->getDeclName() == Name)
6692 Decls.push_back(ND);
6693 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006694
Guy Benyei11169dd2012-12-18 14:30:41 +00006695 ++NumVisibleDeclContextsRead;
6696 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006697 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006698}
6699
Guy Benyei11169dd2012-12-18 14:30:41 +00006700void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6701 if (!DC->hasExternalVisibleStorage())
6702 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006703
6704 auto It = Lookups.find(DC);
6705 assert(It != Lookups.end() &&
6706 "have external visible storage but no lookup tables");
6707
Craig Topper79be4cd2013-07-05 04:33:53 +00006708 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006709
Richard Smithd88a7f12015-09-01 20:35:42 +00006710 for (DeclID ID : It->second.Table.findAll()) {
6711 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6712 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 }
6714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 ++NumVisibleDeclContextsRead;
6716
Craig Topper79be4cd2013-07-05 04:33:53 +00006717 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6719 }
6720 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6721}
6722
Richard Smithd88a7f12015-09-01 20:35:42 +00006723const serialization::reader::DeclContextLookupTable *
6724ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6725 auto I = Lookups.find(Primary);
6726 return I == Lookups.end() ? nullptr : &I->second;
6727}
6728
Guy Benyei11169dd2012-12-18 14:30:41 +00006729/// \brief Under non-PCH compilation the consumer receives the objc methods
6730/// before receiving the implementation, and codegen depends on this.
6731/// We simulate this by deserializing and passing to consumer the methods of the
6732/// implementation before passing the deserialized implementation decl.
6733static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6734 ASTConsumer *Consumer) {
6735 assert(ImplD && Consumer);
6736
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006737 for (auto *I : ImplD->methods())
6738 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006739
6740 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6741}
6742
6743void ASTReader::PassInterestingDeclsToConsumer() {
6744 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006745
6746 if (PassingDeclsToConsumer)
6747 return;
6748
6749 // Guard variable to avoid recursively redoing the process of passing
6750 // decls to consumer.
6751 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6752 true);
6753
Richard Smith9e2341d2015-03-23 03:25:59 +00006754 // Ensure that we've loaded all potentially-interesting declarations
6755 // that need to be eagerly loaded.
6756 for (auto ID : EagerlyDeserializedDecls)
6757 GetDecl(ID);
6758 EagerlyDeserializedDecls.clear();
6759
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 while (!InterestingDecls.empty()) {
6761 Decl *D = InterestingDecls.front();
6762 InterestingDecls.pop_front();
6763
6764 PassInterestingDeclToConsumer(D);
6765 }
6766}
6767
6768void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6769 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6770 PassObjCImplDeclToConsumer(ImplD, Consumer);
6771 else
6772 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6773}
6774
6775void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6776 this->Consumer = Consumer;
6777
Richard Smith9e2341d2015-03-23 03:25:59 +00006778 if (Consumer)
6779 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006780
6781 if (DeserializationListener)
6782 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006783}
6784
6785void ASTReader::PrintStats() {
6786 std::fprintf(stderr, "*** AST File Statistics:\n");
6787
6788 unsigned NumTypesLoaded
6789 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6790 QualType());
6791 unsigned NumDeclsLoaded
6792 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006793 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 unsigned NumIdentifiersLoaded
6795 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6796 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006797 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006798 unsigned NumMacrosLoaded
6799 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6800 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006801 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006802 unsigned NumSelectorsLoaded
6803 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6804 SelectorsLoaded.end(),
6805 Selector());
6806
6807 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6808 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6809 NumSLocEntriesRead, TotalNumSLocEntries,
6810 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6811 if (!TypesLoaded.empty())
6812 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6813 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6814 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6815 if (!DeclsLoaded.empty())
6816 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6817 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6818 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6819 if (!IdentifiersLoaded.empty())
6820 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6821 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6822 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6823 if (!MacrosLoaded.empty())
6824 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6825 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6826 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6827 if (!SelectorsLoaded.empty())
6828 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6829 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6830 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6831 if (TotalNumStatements)
6832 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6833 NumStatementsRead, TotalNumStatements,
6834 ((float)NumStatementsRead/TotalNumStatements * 100));
6835 if (TotalNumMacros)
6836 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6837 NumMacrosRead, TotalNumMacros,
6838 ((float)NumMacrosRead/TotalNumMacros * 100));
6839 if (TotalLexicalDeclContexts)
6840 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6841 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6842 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6843 * 100));
6844 if (TotalVisibleDeclContexts)
6845 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6846 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6847 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6848 * 100));
6849 if (TotalNumMethodPoolEntries) {
6850 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6851 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6852 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6853 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006854 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006855 if (NumMethodPoolLookups) {
6856 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6857 NumMethodPoolHits, NumMethodPoolLookups,
6858 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6859 }
6860 if (NumMethodPoolTableLookups) {
6861 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6862 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6863 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6864 * 100.0));
6865 }
6866
Douglas Gregor00a50f72013-01-25 00:38:33 +00006867 if (NumIdentifierLookupHits) {
6868 std::fprintf(stderr,
6869 " %u / %u identifier table lookups succeeded (%f%%)\n",
6870 NumIdentifierLookupHits, NumIdentifierLookups,
6871 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6872 }
6873
Douglas Gregore060e572013-01-25 01:03:03 +00006874 if (GlobalIndex) {
6875 std::fprintf(stderr, "\n");
6876 GlobalIndex->printStats();
6877 }
6878
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 std::fprintf(stderr, "\n");
6880 dump();
6881 std::fprintf(stderr, "\n");
6882}
6883
6884template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6885static void
6886dumpModuleIDMap(StringRef Name,
6887 const ContinuousRangeMap<Key, ModuleFile *,
6888 InitialCapacity> &Map) {
6889 if (Map.begin() == Map.end())
6890 return;
6891
6892 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6893 llvm::errs() << Name << ":\n";
6894 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6895 I != IEnd; ++I) {
6896 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6897 << "\n";
6898 }
6899}
6900
Yaron Kerencdae9412016-01-29 19:38:18 +00006901LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6903 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6904 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6905 dumpModuleIDMap("Global type map", GlobalTypeMap);
6906 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6907 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6908 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6909 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6910 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6911 dumpModuleIDMap("Global preprocessed entity map",
6912 GlobalPreprocessedEntityMap);
6913
6914 llvm::errs() << "\n*** PCH/Modules Loaded:";
6915 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6916 MEnd = ModuleMgr.end();
6917 M != MEnd; ++M)
6918 (*M)->dump();
6919}
6920
6921/// Return the amount of memory used by memory buffers, breaking down
6922/// by heap-backed versus mmap'ed memory.
6923void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6924 for (ModuleConstIterator I = ModuleMgr.begin(),
6925 E = ModuleMgr.end(); I != E; ++I) {
6926 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6927 size_t bytes = buf->getBufferSize();
6928 switch (buf->getBufferKind()) {
6929 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6930 sizes.malloc_bytes += bytes;
6931 break;
6932 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6933 sizes.mmap_bytes += bytes;
6934 break;
6935 }
6936 }
6937 }
6938}
6939
6940void ASTReader::InitializeSema(Sema &S) {
6941 SemaObj = &S;
6942 S.addExternalSource(this);
6943
6944 // Makes sure any declarations that were deserialized "too early"
6945 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006946 for (uint64_t ID : PreloadedDeclIDs) {
6947 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6948 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006950 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006951
Richard Smith3d8e97e2013-10-18 06:54:39 +00006952 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006953 if (!FPPragmaOptions.empty()) {
6954 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6955 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6956 }
6957
Richard Smith3d8e97e2013-10-18 06:54:39 +00006958 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 if (!OpenCLExtensions.empty()) {
6960 unsigned I = 0;
6961#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6962#include "clang/Basic/OpenCLExtensions.def"
6963
6964 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6965 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006966
6967 UpdateSema();
6968}
6969
6970void ASTReader::UpdateSema() {
6971 assert(SemaObj && "no Sema to update");
6972
6973 // Load the offsets of the declarations that Sema references.
6974 // They will be lazily deserialized when needed.
6975 if (!SemaDeclRefs.empty()) {
6976 assert(SemaDeclRefs.size() % 2 == 0);
6977 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6978 if (!SemaObj->StdNamespace)
6979 SemaObj->StdNamespace = SemaDeclRefs[I];
6980 if (!SemaObj->StdBadAlloc)
6981 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6982 }
6983 SemaDeclRefs.clear();
6984 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006985
Nico Weber779355f2016-03-02 23:22:00 +00006986 // Update the state of pragmas. Use the same API as if we had encountered the
6987 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00006988 if(OptimizeOffPragmaLocation.isValid())
6989 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00006990 if (PragmaMSStructState != -1)
6991 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00006992 if (PointersToMembersPragmaLocation.isValid()) {
6993 SemaObj->ActOnPragmaMSPointersToMembers(
6994 (LangOptions::PragmaMSPointersToMembersKind)
6995 PragmaMSPointersToMembersState,
6996 PointersToMembersPragmaLocation);
6997 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006998}
6999
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007000IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 // Note that we are loading an identifier.
7002 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007003
Douglas Gregor7211ac12013-01-25 23:32:03 +00007004 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007005 NumIdentifierLookups,
7006 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007007
7008 // We don't need to do identifier table lookups in C++ modules (we preload
7009 // all interesting declarations, and don't need to use the scope for name
7010 // lookups). Perform the lookup in PCH files, though, since we don't build
7011 // a complete initial identifier table if we're carrying on from a PCH.
7012 if (Context.getLangOpts().CPlusPlus) {
7013 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007014 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007015 break;
7016 } else {
7017 // If there is a global index, look there first to determine which modules
7018 // provably do not have any results for this identifier.
7019 GlobalModuleIndex::HitSet Hits;
7020 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7021 if (!loadGlobalIndex()) {
7022 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7023 HitsPtr = &Hits;
7024 }
7025 }
7026
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007027 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007028 }
7029
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 IdentifierInfo *II = Visitor.getIdentifierInfo();
7031 markIdentifierUpToDate(II);
7032 return II;
7033}
7034
7035namespace clang {
7036 /// \brief An identifier-lookup iterator that enumerates all of the
7037 /// identifiers stored within a set of AST files.
7038 class ASTIdentifierIterator : public IdentifierIterator {
7039 /// \brief The AST reader whose identifiers are being enumerated.
7040 const ASTReader &Reader;
7041
7042 /// \brief The current index into the chain of AST files stored in
7043 /// the AST reader.
7044 unsigned Index;
7045
7046 /// \brief The current position within the identifier lookup table
7047 /// of the current AST file.
7048 ASTIdentifierLookupTable::key_iterator Current;
7049
7050 /// \brief The end position within the identifier lookup table of
7051 /// the current AST file.
7052 ASTIdentifierLookupTable::key_iterator End;
7053
Ben Langmuir537c5b52016-05-04 00:53:13 +00007054 /// \brief Whether to skip any modules in the ASTReader.
7055 bool SkipModules;
7056
Guy Benyei11169dd2012-12-18 14:30:41 +00007057 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007058 explicit ASTIdentifierIterator(const ASTReader &Reader,
7059 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007060
Craig Topper3e89dfe2014-03-13 02:13:41 +00007061 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007062 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007063}
Guy Benyei11169dd2012-12-18 14:30:41 +00007064
Ben Langmuir537c5b52016-05-04 00:53:13 +00007065ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7066 bool SkipModules)
7067 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007068}
7069
7070StringRef ASTIdentifierIterator::Next() {
7071 while (Current == End) {
7072 // If we have exhausted all of our AST files, we're done.
7073 if (Index == 0)
7074 return StringRef();
7075
7076 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007077 ModuleFile &F = Reader.ModuleMgr[Index];
7078 if (SkipModules && F.isModule())
7079 continue;
7080
7081 ASTIdentifierLookupTable *IdTable =
7082 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007083 Current = IdTable->key_begin();
7084 End = IdTable->key_end();
7085 }
7086
7087 // We have any identifiers remaining in the current AST file; return
7088 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007089 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007090 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007091 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092}
7093
Ben Langmuir537c5b52016-05-04 00:53:13 +00007094namespace {
7095/// A utility for appending two IdentifierIterators.
7096class ChainedIdentifierIterator : public IdentifierIterator {
7097 std::unique_ptr<IdentifierIterator> Current;
7098 std::unique_ptr<IdentifierIterator> Queued;
7099
7100public:
7101 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7102 std::unique_ptr<IdentifierIterator> Second)
7103 : Current(std::move(First)), Queued(std::move(Second)) {}
7104
7105 StringRef Next() override {
7106 if (!Current)
7107 return StringRef();
7108
7109 StringRef result = Current->Next();
7110 if (!result.empty())
7111 return result;
7112
7113 // Try the queued iterator, which may itself be empty.
7114 Current.reset();
7115 std::swap(Current, Queued);
7116 return Next();
7117 }
7118};
7119} // end anonymous namespace.
7120
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007121IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007122 if (!loadGlobalIndex()) {
7123 std::unique_ptr<IdentifierIterator> ReaderIter(
7124 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7125 std::unique_ptr<IdentifierIterator> ModulesIter(
7126 GlobalIndex->createIdentifierIterator());
7127 return new ChainedIdentifierIterator(std::move(ReaderIter),
7128 std::move(ModulesIter));
7129 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007130
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 return new ASTIdentifierIterator(*this);
7132}
7133
7134namespace clang { namespace serialization {
7135 class ReadMethodPoolVisitor {
7136 ASTReader &Reader;
7137 Selector Sel;
7138 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007139 unsigned InstanceBits;
7140 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007141 bool InstanceHasMoreThanOneDecl;
7142 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007143 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7144 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007145
7146 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007147 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007148 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007149 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007150 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7151 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007152
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007153 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 if (!M.SelectorLookupTable)
7155 return false;
7156
7157 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007158 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007159 return true;
7160
Richard Smithbdf2d932015-07-30 03:37:16 +00007161 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 ASTSelectorLookupTable *PoolTable
7163 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007164 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 if (Pos == PoolTable->end())
7166 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007167
Richard Smithbdf2d932015-07-30 03:37:16 +00007168 ++Reader.NumMethodPoolTableHits;
7169 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 // FIXME: Not quite happy with the statistics here. We probably should
7171 // disable this tracking when called via LoadSelector.
7172 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007173 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007175 if (Reader.DeserializationListener)
7176 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007177
Richard Smithbdf2d932015-07-30 03:37:16 +00007178 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7179 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7180 InstanceBits = Data.InstanceBits;
7181 FactoryBits = Data.FactoryBits;
7182 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7183 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 return true;
7185 }
7186
7187 /// \brief Retrieve the instance methods found by this visitor.
7188 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7189 return InstanceMethods;
7190 }
7191
7192 /// \brief Retrieve the instance methods found by this visitor.
7193 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7194 return FactoryMethods;
7195 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007196
7197 unsigned getInstanceBits() const { return InstanceBits; }
7198 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007199 bool instanceHasMoreThanOneDecl() const {
7200 return InstanceHasMoreThanOneDecl;
7201 }
7202 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007204} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007205
7206/// \brief Add the given set of methods to the method list.
7207static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7208 ObjCMethodList &List) {
7209 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7210 S.addMethodToGlobalList(&List, Methods[I]);
7211 }
7212}
7213
7214void ASTReader::ReadMethodPool(Selector Sel) {
7215 // Get the selector generation and update it to the current generation.
7216 unsigned &Generation = SelectorGeneration[Sel];
7217 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007218 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007219 SelectorOutOfDate[Sel] = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007220
7221 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007222 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007224 ModuleMgr.visit(Visitor);
7225
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007227 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007229
7230 ++NumMethodPoolHits;
7231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 if (!getSema())
7233 return;
7234
7235 Sema &S = *getSema();
7236 Sema::GlobalMethodPool::iterator Pos
7237 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007238
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007239 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007240 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007241 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007242 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007243
7244 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7245 // when building a module we keep every method individually and may need to
7246 // update hasMoreThanOneDecl as we add the methods.
7247 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7248 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007249}
7250
Manman Rena0f31a02016-04-29 19:04:05 +00007251void ASTReader::updateOutOfDateSelector(Selector Sel) {
7252 if (SelectorOutOfDate[Sel])
7253 ReadMethodPool(Sel);
7254}
7255
Guy Benyei11169dd2012-12-18 14:30:41 +00007256void ASTReader::ReadKnownNamespaces(
7257 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7258 Namespaces.clear();
7259
7260 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7261 if (NamespaceDecl *Namespace
7262 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7263 Namespaces.push_back(Namespace);
7264 }
7265}
7266
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007267void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007268 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007269 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7270 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007271 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007272 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007273 Undefined.insert(std::make_pair(D, Loc));
7274 }
7275}
Nick Lewycky8334af82013-01-26 00:35:08 +00007276
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007277void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7278 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7279 Exprs) {
7280 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7281 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7282 uint64_t Count = DelayedDeleteExprs[Idx++];
7283 for (uint64_t C = 0; C < Count; ++C) {
7284 SourceLocation DeleteLoc =
7285 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7286 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7287 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7288 }
7289 }
7290}
7291
Guy Benyei11169dd2012-12-18 14:30:41 +00007292void ASTReader::ReadTentativeDefinitions(
7293 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7294 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7295 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7296 if (Var)
7297 TentativeDefs.push_back(Var);
7298 }
7299 TentativeDefinitions.clear();
7300}
7301
7302void ASTReader::ReadUnusedFileScopedDecls(
7303 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7304 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7305 DeclaratorDecl *D
7306 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7307 if (D)
7308 Decls.push_back(D);
7309 }
7310 UnusedFileScopedDecls.clear();
7311}
7312
7313void ASTReader::ReadDelegatingConstructors(
7314 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7315 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7316 CXXConstructorDecl *D
7317 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7318 if (D)
7319 Decls.push_back(D);
7320 }
7321 DelegatingCtorDecls.clear();
7322}
7323
7324void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7325 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7326 TypedefNameDecl *D
7327 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7328 if (D)
7329 Decls.push_back(D);
7330 }
7331 ExtVectorDecls.clear();
7332}
7333
Nico Weber72889432014-09-06 01:25:55 +00007334void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7335 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7336 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7337 ++I) {
7338 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7339 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7340 if (D)
7341 Decls.insert(D);
7342 }
7343 UnusedLocalTypedefNameCandidates.clear();
7344}
7345
Guy Benyei11169dd2012-12-18 14:30:41 +00007346void ASTReader::ReadReferencedSelectors(
7347 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7348 if (ReferencedSelectorsData.empty())
7349 return;
7350
7351 // If there are @selector references added them to its pool. This is for
7352 // implementation of -Wselector.
7353 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7354 unsigned I = 0;
7355 while (I < DataSize) {
7356 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7357 SourceLocation SelLoc
7358 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7359 Sels.push_back(std::make_pair(Sel, SelLoc));
7360 }
7361 ReferencedSelectorsData.clear();
7362}
7363
7364void ASTReader::ReadWeakUndeclaredIdentifiers(
7365 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7366 if (WeakUndeclaredIdentifiers.empty())
7367 return;
7368
7369 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7370 IdentifierInfo *WeakId
7371 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7372 IdentifierInfo *AliasId
7373 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7374 SourceLocation Loc
7375 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7376 bool Used = WeakUndeclaredIdentifiers[I++];
7377 WeakInfo WI(AliasId, Loc);
7378 WI.setUsed(Used);
7379 WeakIDs.push_back(std::make_pair(WeakId, WI));
7380 }
7381 WeakUndeclaredIdentifiers.clear();
7382}
7383
7384void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7385 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7386 ExternalVTableUse VT;
7387 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7388 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7389 VT.DefinitionRequired = VTableUses[Idx++];
7390 VTables.push_back(VT);
7391 }
7392
7393 VTableUses.clear();
7394}
7395
7396void ASTReader::ReadPendingInstantiations(
7397 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7398 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7399 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7400 SourceLocation Loc
7401 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7402
7403 Pending.push_back(std::make_pair(D, Loc));
7404 }
7405 PendingInstantiations.clear();
7406}
7407
Richard Smithe40f2ba2013-08-07 21:41:30 +00007408void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007409 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007410 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7411 /* In loop */) {
7412 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7413
7414 LateParsedTemplate *LT = new LateParsedTemplate;
7415 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7416
7417 ModuleFile *F = getOwningModuleFile(LT->D);
7418 assert(F && "No module");
7419
7420 unsigned TokN = LateParsedTemplates[Idx++];
7421 LT->Toks.reserve(TokN);
7422 for (unsigned T = 0; T < TokN; ++T)
7423 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7424
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007425 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007426 }
7427
7428 LateParsedTemplates.clear();
7429}
7430
Guy Benyei11169dd2012-12-18 14:30:41 +00007431void ASTReader::LoadSelector(Selector Sel) {
7432 // It would be complicated to avoid reading the methods anyway. So don't.
7433 ReadMethodPool(Sel);
7434}
7435
7436void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7437 assert(ID && "Non-zero identifier ID required");
7438 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7439 IdentifiersLoaded[ID - 1] = II;
7440 if (DeserializationListener)
7441 DeserializationListener->IdentifierRead(ID, II);
7442}
7443
7444/// \brief Set the globally-visible declarations associated with the given
7445/// identifier.
7446///
7447/// If the AST reader is currently in a state where the given declaration IDs
7448/// cannot safely be resolved, they are queued until it is safe to resolve
7449/// them.
7450///
7451/// \param II an IdentifierInfo that refers to one or more globally-visible
7452/// declarations.
7453///
7454/// \param DeclIDs the set of declaration IDs with the name @p II that are
7455/// visible at global scope.
7456///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007457/// \param Decls if non-null, this vector will be populated with the set of
7458/// deserialized declarations. These declarations will not be pushed into
7459/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007460void
7461ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7462 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007463 SmallVectorImpl<Decl *> *Decls) {
7464 if (NumCurrentElementsDeserializing && !Decls) {
7465 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007466 return;
7467 }
7468
7469 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007470 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 // Queue this declaration so that it will be added to the
7472 // translation unit scope and identifier's declaration chain
7473 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007474 PreloadedDeclIDs.push_back(DeclIDs[I]);
7475 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007477
7478 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7479
7480 // If we're simply supposed to record the declarations, do so now.
7481 if (Decls) {
7482 Decls->push_back(D);
7483 continue;
7484 }
7485
7486 // Introduce this declaration into the translation-unit scope
7487 // and add it to the declaration chain for this identifier, so
7488 // that (unqualified) name lookup will find it.
7489 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 }
7491}
7492
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007493IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007495 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007496
7497 if (IdentifiersLoaded.empty()) {
7498 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007499 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 }
7501
7502 ID -= 1;
7503 if (!IdentifiersLoaded[ID]) {
7504 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7505 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7506 ModuleFile *M = I->second;
7507 unsigned Index = ID - M->BaseIdentifierID;
7508 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7509
7510 // All of the strings in the AST file are preceded by a 16-bit length.
7511 // Extract that 16-bit length to avoid having to execute strlen().
7512 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7513 // unsigned integers. This is important to avoid integer overflow when
7514 // we cast them to 'unsigned'.
7515 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7516 unsigned StrLen = (((unsigned) StrLenPtr[0])
7517 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007518 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7519 IdentifiersLoaded[ID] = &II;
7520 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007522 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 }
7524
7525 return IdentifiersLoaded[ID];
7526}
7527
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007528IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7529 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007530}
7531
7532IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7533 if (LocalID < NUM_PREDEF_IDENT_IDS)
7534 return LocalID;
7535
7536 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7537 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7538 assert(I != M.IdentifierRemap.end()
7539 && "Invalid index into identifier index remap");
7540
7541 return LocalID + I->second;
7542}
7543
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007544MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007545 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007546 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007547
7548 if (MacrosLoaded.empty()) {
7549 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007550 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 }
7552
7553 ID -= NUM_PREDEF_MACRO_IDS;
7554 if (!MacrosLoaded[ID]) {
7555 GlobalMacroMapType::iterator I
7556 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7557 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7558 ModuleFile *M = I->second;
7559 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007560 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7561
7562 if (DeserializationListener)
7563 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7564 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007565 }
7566
7567 return MacrosLoaded[ID];
7568}
7569
7570MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7571 if (LocalID < NUM_PREDEF_MACRO_IDS)
7572 return LocalID;
7573
7574 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7575 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7576 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7577
7578 return LocalID + I->second;
7579}
7580
7581serialization::SubmoduleID
7582ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7583 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7584 return LocalID;
7585
7586 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7587 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7588 assert(I != M.SubmoduleRemap.end()
7589 && "Invalid index into submodule index remap");
7590
7591 return LocalID + I->second;
7592}
7593
7594Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7595 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7596 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007597 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007598 }
7599
7600 if (GlobalID > SubmodulesLoaded.size()) {
7601 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007602 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007603 }
7604
7605 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7606}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007607
7608Module *ASTReader::getModule(unsigned ID) {
7609 return getSubmodule(ID);
7610}
7611
Richard Smithd88a7f12015-09-01 20:35:42 +00007612ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7613 if (ID & 1) {
7614 // It's a module, look it up by submodule ID.
7615 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7616 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7617 } else {
7618 // It's a prefix (preamble, PCH, ...). Look it up by index.
7619 unsigned IndexFromEnd = ID >> 1;
7620 assert(IndexFromEnd && "got reference to unknown module file");
7621 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7622 }
7623}
7624
7625unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7626 if (!F)
7627 return 1;
7628
7629 // For a file representing a module, use the submodule ID of the top-level
7630 // module as the file ID. For any other kind of file, the number of such
7631 // files loaded beforehand will be the same on reload.
7632 // FIXME: Is this true even if we have an explicit module file and a PCH?
7633 if (F->isModule())
7634 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7635
7636 auto PCHModules = getModuleManager().pch_modules();
7637 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7638 assert(I != PCHModules.end() && "emitting reference to unknown file");
7639 return (I - PCHModules.end()) << 1;
7640}
7641
Adrian Prantl15bcf702015-06-30 17:39:43 +00007642llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7643ASTReader::getSourceDescriptor(unsigned ID) {
7644 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007645 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007646
7647 // If there is only a single PCH, return it instead.
7648 // Chained PCH are not suported.
7649 if (ModuleMgr.size() == 1) {
7650 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007651 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007652 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7653 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7654 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007655 }
7656 return None;
7657}
7658
Guy Benyei11169dd2012-12-18 14:30:41 +00007659Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7660 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7661}
7662
7663Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7664 if (ID == 0)
7665 return Selector();
7666
7667 if (ID > SelectorsLoaded.size()) {
7668 Error("selector ID out of range in AST file");
7669 return Selector();
7670 }
7671
Craig Toppera13603a2014-05-22 05:54:18 +00007672 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 // Load this selector from the selector table.
7674 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7675 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7676 ModuleFile &M = *I->second;
7677 ASTSelectorLookupTrait Trait(*this, M);
7678 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7679 SelectorsLoaded[ID - 1] =
7680 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7681 if (DeserializationListener)
7682 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7683 }
7684
7685 return SelectorsLoaded[ID - 1];
7686}
7687
7688Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7689 return DecodeSelector(ID);
7690}
7691
7692uint32_t ASTReader::GetNumExternalSelectors() {
7693 // ID 0 (the null selector) is considered an external selector.
7694 return getTotalNumSelectors() + 1;
7695}
7696
7697serialization::SelectorID
7698ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7699 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7700 return LocalID;
7701
7702 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7703 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7704 assert(I != M.SelectorRemap.end()
7705 && "Invalid index into selector index remap");
7706
7707 return LocalID + I->second;
7708}
7709
7710DeclarationName
7711ASTReader::ReadDeclarationName(ModuleFile &F,
7712 const RecordData &Record, unsigned &Idx) {
7713 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7714 switch (Kind) {
7715 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007716 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007717
7718 case DeclarationName::ObjCZeroArgSelector:
7719 case DeclarationName::ObjCOneArgSelector:
7720 case DeclarationName::ObjCMultiArgSelector:
7721 return DeclarationName(ReadSelector(F, Record, Idx));
7722
7723 case DeclarationName::CXXConstructorName:
7724 return Context.DeclarationNames.getCXXConstructorName(
7725 Context.getCanonicalType(readType(F, Record, Idx)));
7726
7727 case DeclarationName::CXXDestructorName:
7728 return Context.DeclarationNames.getCXXDestructorName(
7729 Context.getCanonicalType(readType(F, Record, Idx)));
7730
7731 case DeclarationName::CXXConversionFunctionName:
7732 return Context.DeclarationNames.getCXXConversionFunctionName(
7733 Context.getCanonicalType(readType(F, Record, Idx)));
7734
7735 case DeclarationName::CXXOperatorName:
7736 return Context.DeclarationNames.getCXXOperatorName(
7737 (OverloadedOperatorKind)Record[Idx++]);
7738
7739 case DeclarationName::CXXLiteralOperatorName:
7740 return Context.DeclarationNames.getCXXLiteralOperatorName(
7741 GetIdentifierInfo(F, Record, Idx));
7742
7743 case DeclarationName::CXXUsingDirective:
7744 return DeclarationName::getUsingDirectiveName();
7745 }
7746
7747 llvm_unreachable("Invalid NameKind!");
7748}
7749
7750void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7751 DeclarationNameLoc &DNLoc,
7752 DeclarationName Name,
7753 const RecordData &Record, unsigned &Idx) {
7754 switch (Name.getNameKind()) {
7755 case DeclarationName::CXXConstructorName:
7756 case DeclarationName::CXXDestructorName:
7757 case DeclarationName::CXXConversionFunctionName:
7758 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7759 break;
7760
7761 case DeclarationName::CXXOperatorName:
7762 DNLoc.CXXOperatorName.BeginOpNameLoc
7763 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7764 DNLoc.CXXOperatorName.EndOpNameLoc
7765 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7766 break;
7767
7768 case DeclarationName::CXXLiteralOperatorName:
7769 DNLoc.CXXLiteralOperatorName.OpNameLoc
7770 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7771 break;
7772
7773 case DeclarationName::Identifier:
7774 case DeclarationName::ObjCZeroArgSelector:
7775 case DeclarationName::ObjCOneArgSelector:
7776 case DeclarationName::ObjCMultiArgSelector:
7777 case DeclarationName::CXXUsingDirective:
7778 break;
7779 }
7780}
7781
7782void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7783 DeclarationNameInfo &NameInfo,
7784 const RecordData &Record, unsigned &Idx) {
7785 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7786 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7787 DeclarationNameLoc DNLoc;
7788 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7789 NameInfo.setInfo(DNLoc);
7790}
7791
7792void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7793 const RecordData &Record, unsigned &Idx) {
7794 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7795 unsigned NumTPLists = Record[Idx++];
7796 Info.NumTemplParamLists = NumTPLists;
7797 if (NumTPLists) {
7798 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7799 for (unsigned i=0; i != NumTPLists; ++i)
7800 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7801 }
7802}
7803
7804TemplateName
7805ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7806 unsigned &Idx) {
7807 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7808 switch (Kind) {
7809 case TemplateName::Template:
7810 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7811
7812 case TemplateName::OverloadedTemplate: {
7813 unsigned size = Record[Idx++];
7814 UnresolvedSet<8> Decls;
7815 while (size--)
7816 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7817
7818 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7819 }
7820
7821 case TemplateName::QualifiedTemplate: {
7822 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7823 bool hasTemplKeyword = Record[Idx++];
7824 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7825 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7826 }
7827
7828 case TemplateName::DependentTemplate: {
7829 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7830 if (Record[Idx++]) // isIdentifier
7831 return Context.getDependentTemplateName(NNS,
7832 GetIdentifierInfo(F, Record,
7833 Idx));
7834 return Context.getDependentTemplateName(NNS,
7835 (OverloadedOperatorKind)Record[Idx++]);
7836 }
7837
7838 case TemplateName::SubstTemplateTemplateParm: {
7839 TemplateTemplateParmDecl *param
7840 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7841 if (!param) return TemplateName();
7842 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7843 return Context.getSubstTemplateTemplateParm(param, replacement);
7844 }
7845
7846 case TemplateName::SubstTemplateTemplateParmPack: {
7847 TemplateTemplateParmDecl *Param
7848 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7849 if (!Param)
7850 return TemplateName();
7851
7852 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7853 if (ArgPack.getKind() != TemplateArgument::Pack)
7854 return TemplateName();
7855
7856 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7857 }
7858 }
7859
7860 llvm_unreachable("Unhandled template name kind!");
7861}
7862
Richard Smith2bb3c342015-08-09 01:05:31 +00007863TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7864 const RecordData &Record,
7865 unsigned &Idx,
7866 bool Canonicalize) {
7867 if (Canonicalize) {
7868 // The caller wants a canonical template argument. Sometimes the AST only
7869 // wants template arguments in canonical form (particularly as the template
7870 // argument lists of template specializations) so ensure we preserve that
7871 // canonical form across serialization.
7872 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7873 return Context.getCanonicalTemplateArgument(Arg);
7874 }
7875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7877 switch (Kind) {
7878 case TemplateArgument::Null:
7879 return TemplateArgument();
7880 case TemplateArgument::Type:
7881 return TemplateArgument(readType(F, Record, Idx));
7882 case TemplateArgument::Declaration: {
7883 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007884 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 }
7886 case TemplateArgument::NullPtr:
7887 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7888 case TemplateArgument::Integral: {
7889 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7890 QualType T = readType(F, Record, Idx);
7891 return TemplateArgument(Context, Value, T);
7892 }
7893 case TemplateArgument::Template:
7894 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7895 case TemplateArgument::TemplateExpansion: {
7896 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007897 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 if (unsigned NumExpansions = Record[Idx++])
7899 NumTemplateExpansions = NumExpansions - 1;
7900 return TemplateArgument(Name, NumTemplateExpansions);
7901 }
7902 case TemplateArgument::Expression:
7903 return TemplateArgument(ReadExpr(F));
7904 case TemplateArgument::Pack: {
7905 unsigned NumArgs = Record[Idx++];
7906 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7907 for (unsigned I = 0; I != NumArgs; ++I)
7908 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007909 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 }
7911 }
7912
7913 llvm_unreachable("Unhandled template argument kind!");
7914}
7915
7916TemplateParameterList *
7917ASTReader::ReadTemplateParameterList(ModuleFile &F,
7918 const RecordData &Record, unsigned &Idx) {
7919 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7920 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7921 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7922
7923 unsigned NumParams = Record[Idx++];
7924 SmallVector<NamedDecl *, 16> Params;
7925 Params.reserve(NumParams);
7926 while (NumParams--)
7927 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7928
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00007929 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 TemplateParameterList* TemplateParams =
7931 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00007932 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 return TemplateParams;
7934}
7935
7936void
7937ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007938ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007940 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 unsigned NumTemplateArgs = Record[Idx++];
7942 TemplArgs.reserve(NumTemplateArgs);
7943 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007944 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007945}
7946
7947/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007948void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007949 const RecordData &Record, unsigned &Idx) {
7950 unsigned NumDecls = Record[Idx++];
7951 Set.reserve(Context, NumDecls);
7952 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007953 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007955 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007956 }
7957}
7958
7959CXXBaseSpecifier
7960ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7961 const RecordData &Record, unsigned &Idx) {
7962 bool isVirtual = static_cast<bool>(Record[Idx++]);
7963 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7964 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7965 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7966 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7967 SourceRange Range = ReadSourceRange(F, Record, Idx);
7968 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7969 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7970 EllipsisLoc);
7971 Result.setInheritConstructors(inheritConstructors);
7972 return Result;
7973}
7974
Richard Smithc2bb8182015-03-24 06:36:48 +00007975CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007976ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7977 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007979 assert(NumInitializers && "wrote ctor initializers but have no inits");
7980 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7981 for (unsigned i = 0; i != NumInitializers; ++i) {
7982 TypeSourceInfo *TInfo = nullptr;
7983 bool IsBaseVirtual = false;
7984 FieldDecl *Member = nullptr;
7985 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007986
Richard Smithc2bb8182015-03-24 06:36:48 +00007987 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7988 switch (Type) {
7989 case CTOR_INITIALIZER_BASE:
7990 TInfo = GetTypeSourceInfo(F, Record, Idx);
7991 IsBaseVirtual = Record[Idx++];
7992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993
Richard Smithc2bb8182015-03-24 06:36:48 +00007994 case CTOR_INITIALIZER_DELEGATING:
7995 TInfo = GetTypeSourceInfo(F, Record, Idx);
7996 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997
Richard Smithc2bb8182015-03-24 06:36:48 +00007998 case CTOR_INITIALIZER_MEMBER:
7999 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8000 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008001
Richard Smithc2bb8182015-03-24 06:36:48 +00008002 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8003 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8004 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008006
8007 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8008 Expr *Init = ReadExpr(F);
8009 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8010 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8011 bool IsWritten = Record[Idx++];
8012 unsigned SourceOrderOrNumArrayIndices;
8013 SmallVector<VarDecl *, 8> Indices;
8014 if (IsWritten) {
8015 SourceOrderOrNumArrayIndices = Record[Idx++];
8016 } else {
8017 SourceOrderOrNumArrayIndices = Record[Idx++];
8018 Indices.reserve(SourceOrderOrNumArrayIndices);
8019 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
8020 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
8021 }
8022
8023 CXXCtorInitializer *BOMInit;
8024 if (Type == CTOR_INITIALIZER_BASE) {
8025 BOMInit = new (Context)
8026 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8027 RParenLoc, MemberOrEllipsisLoc);
8028 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
8029 BOMInit = new (Context)
8030 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8031 } else if (IsWritten) {
8032 if (Member)
8033 BOMInit = new (Context) CXXCtorInitializer(
8034 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
8035 else
8036 BOMInit = new (Context)
8037 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8038 LParenLoc, Init, RParenLoc);
8039 } else {
8040 if (IndirectMember) {
8041 assert(Indices.empty() && "Indirect field improperly initialized");
8042 BOMInit = new (Context)
8043 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8044 LParenLoc, Init, RParenLoc);
8045 } else {
8046 BOMInit = CXXCtorInitializer::Create(
8047 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8048 Indices.data(), Indices.size());
8049 }
8050 }
8051
8052 if (IsWritten)
8053 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8054 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 }
8056
Richard Smithc2bb8182015-03-24 06:36:48 +00008057 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008058}
8059
8060NestedNameSpecifier *
8061ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8062 const RecordData &Record, unsigned &Idx) {
8063 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008064 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 for (unsigned I = 0; I != N; ++I) {
8066 NestedNameSpecifier::SpecifierKind Kind
8067 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8068 switch (Kind) {
8069 case NestedNameSpecifier::Identifier: {
8070 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8071 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8072 break;
8073 }
8074
8075 case NestedNameSpecifier::Namespace: {
8076 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8077 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8078 break;
8079 }
8080
8081 case NestedNameSpecifier::NamespaceAlias: {
8082 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8083 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8084 break;
8085 }
8086
8087 case NestedNameSpecifier::TypeSpec:
8088 case NestedNameSpecifier::TypeSpecWithTemplate: {
8089 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8090 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008091 return nullptr;
8092
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 bool Template = Record[Idx++];
8094 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8095 break;
8096 }
8097
8098 case NestedNameSpecifier::Global: {
8099 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8100 // No associated value, and there can't be a prefix.
8101 break;
8102 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008103
8104 case NestedNameSpecifier::Super: {
8105 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8106 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8107 break;
8108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 }
8110 Prev = NNS;
8111 }
8112 return NNS;
8113}
8114
8115NestedNameSpecifierLoc
8116ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8117 unsigned &Idx) {
8118 unsigned N = Record[Idx++];
8119 NestedNameSpecifierLocBuilder Builder;
8120 for (unsigned I = 0; I != N; ++I) {
8121 NestedNameSpecifier::SpecifierKind Kind
8122 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8123 switch (Kind) {
8124 case NestedNameSpecifier::Identifier: {
8125 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8126 SourceRange Range = ReadSourceRange(F, Record, Idx);
8127 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8128 break;
8129 }
8130
8131 case NestedNameSpecifier::Namespace: {
8132 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8133 SourceRange Range = ReadSourceRange(F, Record, Idx);
8134 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8135 break;
8136 }
8137
8138 case NestedNameSpecifier::NamespaceAlias: {
8139 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8140 SourceRange Range = ReadSourceRange(F, Record, Idx);
8141 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8142 break;
8143 }
8144
8145 case NestedNameSpecifier::TypeSpec:
8146 case NestedNameSpecifier::TypeSpecWithTemplate: {
8147 bool Template = Record[Idx++];
8148 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8149 if (!T)
8150 return NestedNameSpecifierLoc();
8151 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8152
8153 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8154 Builder.Extend(Context,
8155 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8156 T->getTypeLoc(), ColonColonLoc);
8157 break;
8158 }
8159
8160 case NestedNameSpecifier::Global: {
8161 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8162 Builder.MakeGlobal(Context, ColonColonLoc);
8163 break;
8164 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008165
8166 case NestedNameSpecifier::Super: {
8167 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8168 SourceRange Range = ReadSourceRange(F, Record, Idx);
8169 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8170 break;
8171 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008172 }
8173 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008174
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 return Builder.getWithLocInContext(Context);
8176}
8177
8178SourceRange
8179ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8180 unsigned &Idx) {
8181 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8182 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8183 return SourceRange(beg, end);
8184}
8185
8186/// \brief Read an integral value
8187llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8188 unsigned BitWidth = Record[Idx++];
8189 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8190 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8191 Idx += NumWords;
8192 return Result;
8193}
8194
8195/// \brief Read a signed integral value
8196llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8197 bool isUnsigned = Record[Idx++];
8198 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8199}
8200
8201/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008202llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8203 const llvm::fltSemantics &Sem,
8204 unsigned &Idx) {
8205 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008206}
8207
8208// \brief Read a string
8209std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8210 unsigned Len = Record[Idx++];
8211 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8212 Idx += Len;
8213 return Result;
8214}
8215
Richard Smith7ed1bc92014-12-05 22:42:13 +00008216std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8217 unsigned &Idx) {
8218 std::string Filename = ReadString(Record, Idx);
8219 ResolveImportedPath(F, Filename);
8220 return Filename;
8221}
8222
Guy Benyei11169dd2012-12-18 14:30:41 +00008223VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8224 unsigned &Idx) {
8225 unsigned Major = Record[Idx++];
8226 unsigned Minor = Record[Idx++];
8227 unsigned Subminor = Record[Idx++];
8228 if (Minor == 0)
8229 return VersionTuple(Major);
8230 if (Subminor == 0)
8231 return VersionTuple(Major, Minor - 1);
8232 return VersionTuple(Major, Minor - 1, Subminor - 1);
8233}
8234
8235CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8236 const RecordData &Record,
8237 unsigned &Idx) {
8238 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8239 return CXXTemporary::Create(Context, Decl);
8240}
8241
8242DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008243 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008244}
8245
8246DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8247 return Diags.Report(Loc, DiagID);
8248}
8249
8250/// \brief Retrieve the identifier table associated with the
8251/// preprocessor.
8252IdentifierTable &ASTReader::getIdentifierTable() {
8253 return PP.getIdentifierTable();
8254}
8255
8256/// \brief Record that the given ID maps to the given switch-case
8257/// statement.
8258void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008259 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008260 "Already have a SwitchCase with this ID");
8261 (*CurrSwitchCaseStmts)[ID] = SC;
8262}
8263
8264/// \brief Retrieve the switch-case statement with the given ID.
8265SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008266 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 return (*CurrSwitchCaseStmts)[ID];
8268}
8269
8270void ASTReader::ClearSwitchCaseIDs() {
8271 CurrSwitchCaseStmts->clear();
8272}
8273
8274void ASTReader::ReadComments() {
8275 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008276 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 serialization::ModuleFile *> >::iterator
8278 I = CommentsCursors.begin(),
8279 E = CommentsCursors.end();
8280 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008281 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008282 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 serialization::ModuleFile &F = *I->second;
8284 SavedStreamPosition SavedPosition(Cursor);
8285
8286 RecordData Record;
8287 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008288 llvm::BitstreamEntry Entry =
8289 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008290
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008291 switch (Entry.Kind) {
8292 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8293 case llvm::BitstreamEntry::Error:
8294 Error("malformed block record in AST file");
8295 return;
8296 case llvm::BitstreamEntry::EndBlock:
8297 goto NextCursor;
8298 case llvm::BitstreamEntry::Record:
8299 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008301 }
8302
8303 // Read a record.
8304 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008305 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008306 case COMMENTS_RAW_COMMENT: {
8307 unsigned Idx = 0;
8308 SourceRange SR = ReadSourceRange(F, Record, Idx);
8309 RawComment::CommentKind Kind =
8310 (RawComment::CommentKind) Record[Idx++];
8311 bool IsTrailingComment = Record[Idx++];
8312 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008313 Comments.push_back(new (Context) RawComment(
8314 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8315 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 break;
8317 }
8318 }
8319 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008320 NextCursor:
8321 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008323}
8324
Richard Smithcd45dbc2014-04-19 03:48:30 +00008325std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8326 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008327 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008328 return M->getFullModuleName();
8329
8330 // Otherwise, use the name of the top-level module the decl is within.
8331 if (ModuleFile *M = getOwningModuleFile(D))
8332 return M->ModuleName;
8333
8334 // Not from a module.
8335 return "";
8336}
8337
Guy Benyei11169dd2012-12-18 14:30:41 +00008338void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008339 while (!PendingIdentifierInfos.empty() ||
8340 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008341 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008342 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008343 // If any identifiers with corresponding top-level declarations have
8344 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008345 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8346 TopLevelDeclsMap;
8347 TopLevelDeclsMap TopLevelDecls;
8348
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008350 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008351 SmallVector<uint32_t, 4> DeclIDs =
8352 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008353 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008354
8355 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008357
Richard Smith851072e2014-05-19 20:59:20 +00008358 // For each decl chain that we wanted to complete while deserializing, mark
8359 // it as "still needs to be completed".
8360 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8361 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8362 }
8363 PendingIncompleteDeclChains.clear();
8364
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008366 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008367 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008368 PendingDeclChains.clear();
8369
Douglas Gregor6168bd22013-02-18 15:53:43 +00008370 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008371 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8372 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008373 IdentifierInfo *II = TLD->first;
8374 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008375 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008376 }
8377 }
8378
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 // Load any pending macro definitions.
8380 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008381 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8382 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8383 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8384 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008385 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008386 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008387 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008388 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008389 resolvePendingMacro(II, Info);
8390 }
8391 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008392 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008393 ++IDIdx) {
8394 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008395 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008396 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 }
8398 }
8399 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008400
8401 // Wire up the DeclContexts for Decls that we delayed setting until
8402 // recursive loading is completed.
8403 while (!PendingDeclContextInfos.empty()) {
8404 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8405 PendingDeclContextInfos.pop_front();
8406 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8407 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8408 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8409 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008410
Richard Smithd1c46742014-04-30 02:24:17 +00008411 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008412 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008413 auto Update = PendingUpdateRecords.pop_back_val();
8414 ReadingKindTracker ReadingKind(Read_Decl, *this);
8415 loadDeclUpdateRecords(Update.first, Update.second);
8416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 }
Richard Smith8a639892015-01-24 01:07:20 +00008418
8419 // At this point, all update records for loaded decls are in place, so any
8420 // fake class definitions should have become real.
8421 assert(PendingFakeDefinitionData.empty() &&
8422 "faked up a class definition but never saw the real one");
8423
Guy Benyei11169dd2012-12-18 14:30:41 +00008424 // If we deserialized any C++ or Objective-C class definitions, any
8425 // Objective-C protocol definitions, or any redeclarable templates, make sure
8426 // that all redeclarations point to the definitions. Note that this can only
8427 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008428 for (Decl *D : PendingDefinitions) {
8429 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008430 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008431 // Make sure that the TagType points at the definition.
8432 const_cast<TagType*>(TagT)->decl = TD;
8433 }
Richard Smith8ce51082015-03-11 01:44:51 +00008434
Craig Topperc6914d02014-08-25 04:15:02 +00008435 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008436 for (auto *R = getMostRecentExistingDecl(RD); R;
8437 R = R->getPreviousDecl()) {
8438 assert((R == D) ==
8439 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008440 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008441 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008442 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008443 }
8444
8445 continue;
8446 }
Richard Smith8ce51082015-03-11 01:44:51 +00008447
Craig Topperc6914d02014-08-25 04:15:02 +00008448 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008449 // Make sure that the ObjCInterfaceType points at the definition.
8450 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8451 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008452
8453 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8454 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8455
Guy Benyei11169dd2012-12-18 14:30:41 +00008456 continue;
8457 }
Richard Smith8ce51082015-03-11 01:44:51 +00008458
Craig Topperc6914d02014-08-25 04:15:02 +00008459 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008460 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8461 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8462
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 continue;
8464 }
Richard Smith8ce51082015-03-11 01:44:51 +00008465
Craig Topperc6914d02014-08-25 04:15:02 +00008466 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008467 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8468 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 }
8470 PendingDefinitions.clear();
8471
8472 // Load the bodies of any functions or methods we've encountered. We do
8473 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008474 // have been fully wired up (hasBody relies on this).
8475 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8477 PBEnd = PendingBodies.end();
8478 PB != PBEnd; ++PB) {
8479 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8480 // FIXME: Check for =delete/=default?
8481 // FIXME: Complain about ODR violations here?
8482 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8483 FD->setLazyBody(PB->second);
8484 continue;
8485 }
8486
8487 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8488 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8489 MD->setLazyBody(PB->second);
8490 }
8491 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008492
8493 // Do some cleanup.
8494 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8495 getContext().deduplicateMergedDefinitonsFor(ND);
8496 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008497}
8498
8499void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008500 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8501 return;
8502
Richard Smitha0ce9c42014-07-29 23:23:27 +00008503 // Trigger the import of the full definition of each class that had any
8504 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008505 // These updates may in turn find and diagnose some ODR failures, so take
8506 // ownership of the set first.
8507 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8508 PendingOdrMergeFailures.clear();
8509 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008510 Merge.first->buildLookup();
8511 Merge.first->decls_begin();
8512 Merge.first->bases_begin();
8513 Merge.first->vbases_begin();
8514 for (auto *RD : Merge.second) {
8515 RD->decls_begin();
8516 RD->bases_begin();
8517 RD->vbases_begin();
8518 }
8519 }
8520
8521 // For each declaration from a merged context, check that the canonical
8522 // definition of that context also contains a declaration of the same
8523 // entity.
8524 //
8525 // Caution: this loop does things that might invalidate iterators into
8526 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8527 while (!PendingOdrMergeChecks.empty()) {
8528 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8529
8530 // FIXME: Skip over implicit declarations for now. This matters for things
8531 // like implicitly-declared special member functions. This isn't entirely
8532 // correct; we can end up with multiple unmerged declarations of the same
8533 // implicit entity.
8534 if (D->isImplicit())
8535 continue;
8536
8537 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008538
8539 bool Found = false;
8540 const Decl *DCanon = D->getCanonicalDecl();
8541
Richard Smith01bdb7a2014-08-28 05:44:07 +00008542 for (auto RI : D->redecls()) {
8543 if (RI->getLexicalDeclContext() == CanonDef) {
8544 Found = true;
8545 break;
8546 }
8547 }
8548 if (Found)
8549 continue;
8550
Richard Smith0f4e2c42015-08-06 04:23:48 +00008551 // Quick check failed, time to do the slow thing. Note, we can't just
8552 // look up the name of D in CanonDef here, because the member that is
8553 // in CanonDef might not be found by name lookup (it might have been
8554 // replaced by a more recent declaration in the lookup table), and we
8555 // can't necessarily find it in the redeclaration chain because it might
8556 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008557 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008558 for (auto *CanonMember : CanonDef->decls()) {
8559 if (CanonMember->getCanonicalDecl() == DCanon) {
8560 // This can happen if the declaration is merely mergeable and not
8561 // actually redeclarable (we looked for redeclarations earlier).
8562 //
8563 // FIXME: We should be able to detect this more efficiently, without
8564 // pulling in all of the members of CanonDef.
8565 Found = true;
8566 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008567 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008568 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8569 if (ND->getDeclName() == D->getDeclName())
8570 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008571 }
8572
8573 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008574 // The AST doesn't like TagDecls becoming invalid after they've been
8575 // completed. We only really need to mark FieldDecls as invalid here.
8576 if (!isa<TagDecl>(D))
8577 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008578
8579 // Ensure we don't accidentally recursively enter deserialization while
8580 // we're producing our diagnostic.
8581 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008582
8583 std::string CanonDefModule =
8584 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8585 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8586 << D << getOwningModuleNameForDiagnostic(D)
8587 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8588
8589 if (Candidates.empty())
8590 Diag(cast<Decl>(CanonDef)->getLocation(),
8591 diag::note_module_odr_violation_no_possible_decls) << D;
8592 else {
8593 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8594 Diag(Candidates[I]->getLocation(),
8595 diag::note_module_odr_violation_possible_decl)
8596 << Candidates[I];
8597 }
8598
8599 DiagnosedOdrMergeFailures.insert(CanonDef);
8600 }
8601 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008602
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008603 if (OdrMergeFailures.empty())
8604 return;
8605
8606 // Ensure we don't accidentally recursively enter deserialization while
8607 // we're producing our diagnostics.
8608 Deserializing RecursionGuard(this);
8609
Richard Smithcd45dbc2014-04-19 03:48:30 +00008610 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008611 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008612 // If we've already pointed out a specific problem with this class, don't
8613 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008614 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008615 continue;
8616
8617 bool Diagnosed = false;
8618 for (auto *RD : Merge.second) {
8619 // Multiple different declarations got merged together; tell the user
8620 // where they came from.
8621 if (Merge.first != RD) {
8622 // FIXME: Walk the definition, figure out what's different,
8623 // and diagnose that.
8624 if (!Diagnosed) {
8625 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8626 Diag(Merge.first->getLocation(),
8627 diag::err_module_odr_violation_different_definitions)
8628 << Merge.first << Module.empty() << Module;
8629 Diagnosed = true;
8630 }
8631
8632 Diag(RD->getLocation(),
8633 diag::note_module_odr_violation_different_definitions)
8634 << getOwningModuleNameForDiagnostic(RD);
8635 }
8636 }
8637
8638 if (!Diagnosed) {
8639 // All definitions are updates to the same declaration. This happens if a
8640 // module instantiates the declaration of a class template specialization
8641 // and two or more other modules instantiate its definition.
8642 //
8643 // FIXME: Indicate which modules had instantiations of this definition.
8644 // FIXME: How can this even happen?
8645 Diag(Merge.first->getLocation(),
8646 diag::err_module_odr_violation_different_instantiations)
8647 << Merge.first;
8648 }
8649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008650}
8651
Richard Smithce18a182015-07-14 00:26:00 +00008652void ASTReader::StartedDeserializing() {
8653 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8654 ReadTimer->startTimer();
8655}
8656
Guy Benyei11169dd2012-12-18 14:30:41 +00008657void ASTReader::FinishedDeserializing() {
8658 assert(NumCurrentElementsDeserializing &&
8659 "FinishedDeserializing not paired with StartedDeserializing");
8660 if (NumCurrentElementsDeserializing == 1) {
8661 // We decrease NumCurrentElementsDeserializing only after pending actions
8662 // are finished, to avoid recursively re-calling finishPendingActions().
8663 finishPendingActions();
8664 }
8665 --NumCurrentElementsDeserializing;
8666
Richard Smitha0ce9c42014-07-29 23:23:27 +00008667 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008668 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008669 while (!PendingExceptionSpecUpdates.empty()) {
8670 auto Updates = std::move(PendingExceptionSpecUpdates);
8671 PendingExceptionSpecUpdates.clear();
8672 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008673 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008674 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008675 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008676 if (auto *Listener = Context.getASTMutationListener())
8677 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008678 for (auto *Redecl : Update.second->redecls())
8679 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008680 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008681 }
8682
Richard Smithce18a182015-07-14 00:26:00 +00008683 if (ReadTimer)
8684 ReadTimer->stopTimer();
8685
Richard Smith0f4e2c42015-08-06 04:23:48 +00008686 diagnoseOdrViolations();
8687
Richard Smith04d05b52014-03-23 00:27:18 +00008688 // We are not in recursive loading, so it's safe to pass the "interesting"
8689 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008690 if (Consumer)
8691 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008692 }
8693}
8694
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008695void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008696 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8697 // Remove any fake results before adding any real ones.
8698 auto It = PendingFakeLookupResults.find(II);
8699 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008700 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008701 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008702 // FIXME: this works around module+PCH performance issue.
8703 // Rather than erase the result from the map, which is O(n), just clear
8704 // the vector of NamedDecls.
8705 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008706 }
8707 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008708
8709 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8710 SemaObj->TUScope->AddDecl(D);
8711 } else if (SemaObj->TUScope) {
8712 // Adding the decl to IdResolver may have failed because it was already in
8713 // (even though it was not added in scope). If it is already in, make sure
8714 // it gets in the scope as well.
8715 if (std::find(SemaObj->IdResolver.begin(Name),
8716 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8717 SemaObj->TUScope->AddDecl(D);
8718 }
8719}
8720
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008721ASTReader::ASTReader(
8722 Preprocessor &PP, ASTContext &Context,
8723 const PCHContainerReader &PCHContainerRdr,
8724 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8725 StringRef isysroot, bool DisableValidation,
8726 bool AllowASTWithCompilerErrors,
8727 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8728 bool UseGlobalIndex,
8729 std::unique_ptr<llvm::Timer> ReadTimer)
Yaxun Liu43712e02016-09-07 18:40:20 +00008730 : Listener(DisableValidation ?
8731 cast<ASTReaderListener>(new SimpleASTReaderListener(PP)) :
8732 cast<ASTReaderListener>(new PCHValidator(PP, *this))),
8733 DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008734 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008735 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008736 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008737 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smith10379092016-05-06 23:14:07 +00008738 DummyIdResolver(PP),
Richard Smithce18a182015-07-14 00:26:00 +00008739 ReadTimer(std::move(ReadTimer)),
Nico Weber779355f2016-03-02 23:22:00 +00008740 PragmaMSStructState(-1),
Nico Weber42932312016-03-03 00:17:35 +00008741 PragmaMSPointersToMembersState(-1),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008742 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008743 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8744 AllowConfigurationMismatch(AllowConfigurationMismatch),
8745 ValidateSystemInputs(ValidateSystemInputs),
8746 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008747 ProcessingUpdateRecords(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008748 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8749 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8750 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8751 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008752 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8753 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8754 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8755 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8756 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8757 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008758 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008759 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008760
8761 for (const auto &Ext : Extensions) {
8762 auto BlockName = Ext->getExtensionMetadata().BlockName;
8763 auto Known = ModuleFileExtensions.find(BlockName);
8764 if (Known != ModuleFileExtensions.end()) {
8765 Diags.Report(diag::warn_duplicate_module_file_extension)
8766 << BlockName;
8767 continue;
8768 }
8769
8770 ModuleFileExtensions.insert({BlockName, Ext});
8771 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008772}
8773
8774ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008775 if (OwnsDeserializationListener)
8776 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008777}
Richard Smith10379092016-05-06 23:14:07 +00008778
8779IdentifierResolver &ASTReader::getIdResolver() {
8780 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
8781}