blob: 4838a43e03304dfea46185a1d1bf8e4f0e1fec68 [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"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000094bool ChainedASTReaderListener::ReadTargetOptions(
95 const TargetOptions &TargetOpts, bool Complain,
96 bool AllowCompatibleDifferences) {
97 return First->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences) ||
99 Second->ReadTargetOptions(TargetOpts, Complain,
100 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000101}
102bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000103 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000104 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
105 Second->ReadDiagnosticOptions(DiagOpts, Complain);
106}
107bool
108ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
109 bool Complain) {
110 return First->ReadFileSystemOptions(FSOpts, Complain) ||
111 Second->ReadFileSystemOptions(FSOpts, Complain);
112}
113
114bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000115 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
116 bool Complain) {
117 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain) ||
119 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
120 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000121}
122bool ChainedASTReaderListener::ReadPreprocessorOptions(
123 const PreprocessorOptions &PPOpts, bool Complain,
124 std::string &SuggestedPredefines) {
125 return First->ReadPreprocessorOptions(PPOpts, Complain,
126 SuggestedPredefines) ||
127 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
128}
129void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
130 unsigned Value) {
131 First->ReadCounter(M, Value);
132 Second->ReadCounter(M, Value);
133}
134bool ChainedASTReaderListener::needsInputFileVisitation() {
135 return First->needsInputFileVisitation() ||
136 Second->needsInputFileVisitation();
137}
138bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
139 return First->needsSystemInputFileVisitation() ||
140 Second->needsSystemInputFileVisitation();
141}
Richard Smith216a3bd2015-08-13 17:57:10 +0000142void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
143 ModuleKind Kind) {
144 First->visitModuleFile(Filename, Kind);
145 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000146}
Ben Langmuircb69b572014-03-07 06:40:32 +0000147bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000148 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000149 bool isOverridden,
150 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000151 bool Continue = false;
152 if (First->needsInputFileVisitation() &&
153 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000154 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
155 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000156 if (Second->needsInputFileVisitation() &&
157 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000158 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
159 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000160 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000161}
162
Guy Benyei11169dd2012-12-18 14:30:41 +0000163//===----------------------------------------------------------------------===//
164// PCH validator implementation
165//===----------------------------------------------------------------------===//
166
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000167ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000168
169/// \brief Compare the given set of language options against an existing set of
170/// language options.
171///
172/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173/// \param AllowCompatibleDifferences If true, differences between compatible
174/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000175///
176/// \returns true if the languagae options mis-match, false otherwise.
177static bool checkLanguageOptions(const LangOptions &LangOpts,
178 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000179 DiagnosticsEngine *Diags,
180 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000181#define LANGOPT(Name, Bits, Default, Description) \
182 if (ExistingLangOpts.Name != LangOpts.Name) { \
183 if (Diags) \
184 Diags->Report(diag::err_pch_langopt_mismatch) \
185 << Description << LangOpts.Name << ExistingLangOpts.Name; \
186 return true; \
187 }
188
189#define VALUE_LANGOPT(Name, Bits, Default, Description) \
190 if (ExistingLangOpts.Name != LangOpts.Name) { \
191 if (Diags) \
192 Diags->Report(diag::err_pch_langopt_value_mismatch) \
193 << Description; \
194 return true; \
195 }
196
197#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
198 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
199 if (Diags) \
200 Diags->Report(diag::err_pch_langopt_value_mismatch) \
201 << Description; \
202 return true; \
203 }
204
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000205#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
206 if (!AllowCompatibleDifferences) \
207 LANGOPT(Name, Bits, Default, Description)
208
209#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
210 if (!AllowCompatibleDifferences) \
211 ENUM_LANGOPT(Name, Bits, Default, Description)
212
Guy Benyei11169dd2012-12-18 14:30:41 +0000213#define BENIGN_LANGOPT(Name, Bits, Default, Description)
214#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
215#include "clang/Basic/LangOptions.def"
216
Ben Langmuircd98cb72015-06-23 18:20:18 +0000217 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
218 if (Diags)
219 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
220 return true;
221 }
222
Guy Benyei11169dd2012-12-18 14:30:41 +0000223 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
224 if (Diags)
225 Diags->Report(diag::err_pch_langopt_value_mismatch)
226 << "target Objective-C runtime";
227 return true;
228 }
229
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000230 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
231 LangOpts.CommentOpts.BlockCommandNames) {
232 if (Diags)
233 Diags->Report(diag::err_pch_langopt_value_mismatch)
234 << "block command names";
235 return true;
236 }
237
Guy Benyei11169dd2012-12-18 14:30:41 +0000238 return false;
239}
240
241/// \brief Compare the given set of target options against an existing set of
242/// target options.
243///
244/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
245///
246/// \returns true if the target options mis-match, false otherwise.
247static bool checkTargetOptions(const TargetOptions &TargetOpts,
248 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000249 DiagnosticsEngine *Diags,
250 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000251#define CHECK_TARGET_OPT(Field, Name) \
252 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
253 if (Diags) \
254 Diags->Report(diag::err_pch_targetopt_mismatch) \
255 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
256 return true; \
257 }
258
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000259 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000261 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000262
263 // We can tolerate different CPUs in many cases, notably when one CPU
264 // supports a strict superset of another. When allowing compatible
265 // differences skip this check.
266 if (!AllowCompatibleDifferences)
267 CHECK_TARGET_OPT(CPU, "target CPU");
268
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#undef CHECK_TARGET_OPT
270
271 // Compare feature sets.
272 SmallVector<StringRef, 4> ExistingFeatures(
273 ExistingTargetOpts.FeaturesAsWritten.begin(),
274 ExistingTargetOpts.FeaturesAsWritten.end());
275 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
276 TargetOpts.FeaturesAsWritten.end());
277 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
278 std::sort(ReadFeatures.begin(), ReadFeatures.end());
279
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000280 // We compute the set difference in both directions explicitly so that we can
281 // diagnose the differences differently.
282 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
283 std::set_difference(
284 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
285 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
286 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
287 ExistingFeatures.begin(), ExistingFeatures.end(),
288 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 // If we are allowing compatible differences and the read feature set is
291 // a strict subset of the existing feature set, there is nothing to diagnose.
292 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
293 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000294
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000295 if (Diags) {
296 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000298 << /* is-existing-feature */ false << Feature;
299 for (StringRef Feature : UnmatchedExistingFeatures)
300 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
301 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 }
303
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000305}
306
307bool
308PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000309 bool Complain,
310 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000311 const LangOptions &ExistingLangOpts = PP.getLangOpts();
312 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000313 Complain ? &Reader.Diags : nullptr,
314 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000315}
316
317bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000318 bool Complain,
319 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000320 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
321 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000322 Complain ? &Reader.Diags : nullptr,
323 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000324}
325
326namespace {
327 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
328 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000329 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
330 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000331}
332
Ben Langmuirb92de022014-04-29 16:25:26 +0000333static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
334 DiagnosticsEngine &Diags,
335 bool Complain) {
336 typedef DiagnosticsEngine::Level Level;
337
338 // Check current mappings for new -Werror mappings, and the stored mappings
339 // for cases that were explicitly mapped to *not* be errors that are now
340 // errors because of options like -Werror.
341 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
342
343 for (DiagnosticsEngine *MappingSource : MappingSources) {
344 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
345 diag::kind DiagID = DiagIDMappingPair.first;
346 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
347 if (CurLevel < DiagnosticsEngine::Error)
348 continue; // not significant
349 Level StoredLevel =
350 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
351 if (StoredLevel < DiagnosticsEngine::Error) {
352 if (Complain)
353 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
354 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
355 return true;
356 }
357 }
358 }
359
360 return false;
361}
362
Alp Tokerac4e8e52014-06-22 21:58:33 +0000363static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
364 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
365 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
366 return true;
367 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000368}
369
370static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
371 DiagnosticsEngine &Diags,
372 bool IsSystem, bool Complain) {
373 // Top-level options
374 if (IsSystem) {
375 if (Diags.getSuppressSystemWarnings())
376 return false;
377 // If -Wsystem-headers was not enabled before, be conservative
378 if (StoredDiags.getSuppressSystemWarnings()) {
379 if (Complain)
380 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
381 return true;
382 }
383 }
384
385 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
386 if (Complain)
387 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
388 return true;
389 }
390
391 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
392 !StoredDiags.getEnableAllWarnings()) {
393 if (Complain)
394 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
395 return true;
396 }
397
398 if (isExtHandlingFromDiagsError(Diags) &&
399 !isExtHandlingFromDiagsError(StoredDiags)) {
400 if (Complain)
401 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
402 return true;
403 }
404
405 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
406}
407
408bool PCHValidator::ReadDiagnosticOptions(
409 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
410 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
411 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
412 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000413 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000414 // This should never fail, because we would have processed these options
415 // before writing them to an ASTFile.
416 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
417
418 ModuleManager &ModuleMgr = Reader.getModuleManager();
419 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
420
421 // If the original import came from a file explicitly generated by the user,
422 // don't check the diagnostic mappings.
423 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000424 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000425 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
426 // the transitive closure of its imports, since unrelated modules cannot be
427 // imported until after this module finishes validation.
428 ModuleFile *TopImport = *ModuleMgr.rbegin();
429 while (!TopImport->ImportedBy.empty())
430 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000431 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000432 return false;
433
434 StringRef ModuleName = TopImport->ModuleName;
435 assert(!ModuleName.empty() && "diagnostic options read before module name");
436
437 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
438 assert(M && "missing module");
439
440 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
441 // contains the union of their flags.
442 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
443}
444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445/// \brief Collect the macro definitions provided by the given preprocessor
446/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000447static void
448collectMacroDefinitions(const PreprocessorOptions &PPOpts,
449 MacroDefinitionsMap &Macros,
450 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
452 StringRef Macro = PPOpts.Macros[I].first;
453 bool IsUndef = PPOpts.Macros[I].second;
454
455 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
456 StringRef MacroName = MacroPair.first;
457 StringRef MacroBody = MacroPair.second;
458
459 // For an #undef'd macro, we only care about the name.
460 if (IsUndef) {
461 if (MacroNames && !Macros.count(MacroName))
462 MacroNames->push_back(MacroName);
463
464 Macros[MacroName] = std::make_pair("", true);
465 continue;
466 }
467
468 // For a #define'd macro, figure out the actual definition.
469 if (MacroName.size() == Macro.size())
470 MacroBody = "1";
471 else {
472 // Note: GCC drops anything following an end-of-line character.
473 StringRef::size_type End = MacroBody.find_first_of("\n\r");
474 MacroBody = MacroBody.substr(0, End);
475 }
476
477 if (MacroNames && !Macros.count(MacroName))
478 MacroNames->push_back(MacroName);
479 Macros[MacroName] = std::make_pair(MacroBody, false);
480 }
481}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000482
Guy Benyei11169dd2012-12-18 14:30:41 +0000483/// \brief Check the preprocessor options deserialized from the control block
484/// against the preprocessor options in an existing preprocessor.
485///
486/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
487static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
488 const PreprocessorOptions &ExistingPPOpts,
489 DiagnosticsEngine *Diags,
490 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000491 std::string &SuggestedPredefines,
492 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000493 // Check macro definitions.
494 MacroDefinitionsMap ASTFileMacros;
495 collectMacroDefinitions(PPOpts, ASTFileMacros);
496 MacroDefinitionsMap ExistingMacros;
497 SmallVector<StringRef, 4> ExistingMacroNames;
498 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
499
500 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
501 // Dig out the macro definition in the existing preprocessor options.
502 StringRef MacroName = ExistingMacroNames[I];
503 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
504
505 // Check whether we know anything about this macro name or not.
506 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
507 = ASTFileMacros.find(MacroName);
508 if (Known == ASTFileMacros.end()) {
509 // FIXME: Check whether this identifier was referenced anywhere in the
510 // AST file. If so, we should reject the AST file. Unfortunately, this
511 // information isn't in the control block. What shall we do about it?
512
513 if (Existing.second) {
514 SuggestedPredefines += "#undef ";
515 SuggestedPredefines += MacroName.str();
516 SuggestedPredefines += '\n';
517 } else {
518 SuggestedPredefines += "#define ";
519 SuggestedPredefines += MacroName.str();
520 SuggestedPredefines += ' ';
521 SuggestedPredefines += Existing.first.str();
522 SuggestedPredefines += '\n';
523 }
524 continue;
525 }
526
527 // If the macro was defined in one but undef'd in the other, we have a
528 // conflict.
529 if (Existing.second != Known->second.second) {
530 if (Diags) {
531 Diags->Report(diag::err_pch_macro_def_undef)
532 << MacroName << Known->second.second;
533 }
534 return true;
535 }
536
537 // If the macro was #undef'd in both, or if the macro bodies are identical,
538 // it's fine.
539 if (Existing.second || Existing.first == Known->second.first)
540 continue;
541
542 // The macro bodies differ; complain.
543 if (Diags) {
544 Diags->Report(diag::err_pch_macro_def_conflict)
545 << MacroName << Known->second.first << Existing.first;
546 }
547 return true;
548 }
549
550 // Check whether we're using predefines.
551 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
552 if (Diags) {
553 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
554 }
555 return true;
556 }
557
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000558 // Detailed record is important since it is used for the module cache hash.
559 if (LangOpts.Modules &&
560 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
561 if (Diags) {
562 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
563 }
564 return true;
565 }
566
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 // Compute the #include and #include_macros lines we need.
568 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
569 StringRef File = ExistingPPOpts.Includes[I];
570 if (File == ExistingPPOpts.ImplicitPCHInclude)
571 continue;
572
573 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
574 != PPOpts.Includes.end())
575 continue;
576
577 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n";
580 }
581
582 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
583 StringRef File = ExistingPPOpts.MacroIncludes[I];
584 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
585 File)
586 != PPOpts.MacroIncludes.end())
587 continue;
588
589 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000590 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591 SuggestedPredefines += "\"\n##\n";
592 }
593
594 return false;
595}
596
597bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
598 bool Complain,
599 std::string &SuggestedPredefines) {
600 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
601
602 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000603 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000605 SuggestedPredefines,
606 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000607}
608
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000609/// Check the header search options deserialized from the control block
610/// against the header search options in an existing preprocessor.
611///
612/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
613static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
614 StringRef SpecificModuleCachePath,
615 StringRef ExistingModuleCachePath,
616 DiagnosticsEngine *Diags,
617 const LangOptions &LangOpts) {
618 if (LangOpts.Modules) {
619 if (SpecificModuleCachePath != ExistingModuleCachePath) {
620 if (Diags)
621 Diags->Report(diag::err_pch_modulecache_mismatch)
622 << SpecificModuleCachePath << ExistingModuleCachePath;
623 return true;
624 }
625 }
626
627 return false;
628}
629
630bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
631 StringRef SpecificModuleCachePath,
632 bool Complain) {
633 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
634 PP.getHeaderSearchInfo().getModuleCachePath(),
635 Complain ? &Reader.Diags : nullptr,
636 PP.getLangOpts());
637}
638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
640 PP.setCounterValue(Value);
641}
642
643//===----------------------------------------------------------------------===//
644// AST reader implementation
645//===----------------------------------------------------------------------===//
646
Nico Weber824285e2014-05-08 04:26:47 +0000647void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
648 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000650 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000651}
652
653
654
655unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
656 return serialization::ComputeHash(Sel);
657}
658
659
660std::pair<unsigned, unsigned>
661ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000662 using namespace llvm::support;
663 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
664 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 return std::make_pair(KeyLen, DataLen);
666}
667
668ASTSelectorLookupTrait::internal_key_type
669ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000670 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000672 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
673 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
674 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 if (N == 0)
676 return SelTable.getNullarySelector(FirstII);
677 else if (N == 1)
678 return SelTable.getUnarySelector(FirstII);
679
680 SmallVector<IdentifierInfo *, 16> Args;
681 Args.push_back(FirstII);
682 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000683 Args.push_back(Reader.getLocalIdentifier(
684 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000685
686 return SelTable.getSelector(N, Args.data());
687}
688
689ASTSelectorLookupTrait::data_type
690ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
691 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000692 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000693
694 data_type Result;
695
Justin Bogner57ba0b22014-03-28 22:03:24 +0000696 Result.ID = Reader.getGlobalSelectorID(
697 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000698 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
699 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
700 Result.InstanceBits = FullInstanceBits & 0x3;
701 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
702 Result.FactoryBits = FullFactoryBits & 0x3;
703 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
704 unsigned NumInstanceMethods = FullInstanceBits >> 3;
705 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000706
707 // Load instance methods
708 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000709 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
710 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000711 Result.Instance.push_back(Method);
712 }
713
714 // Load factory methods
715 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000716 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
717 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 Result.Factory.push_back(Method);
719 }
720
721 return Result;
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
725 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000726}
727
728std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000729ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000730 using namespace llvm::support;
731 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
732 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 return std::make_pair(KeyLen, DataLen);
734}
735
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000736ASTIdentifierLookupTraitBase::internal_key_type
737ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000739 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000740}
741
Douglas Gregordcf25082013-02-11 18:16:18 +0000742/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000743static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
744 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000745 return II.hadMacroDefinition() ||
746 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000747 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000748 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000749 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
750 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000751}
752
Richard Smith76c2f2c2015-07-17 20:09:43 +0000753static bool readBit(unsigned &Bits) {
754 bool Value = Bits & 0x1;
755 Bits >>= 1;
756 return Value;
757}
758
Richard Smith79bf9202015-08-24 03:33:22 +0000759IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
760 using namespace llvm::support;
761 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
762 return Reader.getGlobalIdentifierID(F, RawID >> 1);
763}
764
Guy Benyei11169dd2012-12-18 14:30:41 +0000765IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
766 const unsigned char* d,
767 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000768 using namespace llvm::support;
769 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000770 bool IsInteresting = RawID & 0x01;
771
772 // Wipe out the "is interesting" bit.
773 RawID = RawID >> 1;
774
Richard Smith76c2f2c2015-07-17 20:09:43 +0000775 // Build the IdentifierInfo and link the identifier ID with it.
776 IdentifierInfo *II = KnownII;
777 if (!II) {
778 II = &Reader.getIdentifierTable().getOwn(k);
779 KnownII = II;
780 }
781 if (!II->isFromAST()) {
782 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000783 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000784 II->setChangedSinceDeserialization();
785 }
786 Reader.markIdentifierUpToDate(II);
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
789 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 // For uninteresting identifiers, there's nothing else to do. Just notify
791 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 return II;
794 }
795
Justin Bogner57ba0b22014-03-28 22:03:24 +0000796 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
797 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000798 bool CPlusPlusOperatorKeyword = readBit(Bits);
799 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000800 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000801 bool Poisoned = readBit(Bits);
802 bool ExtensionToken = readBit(Bits);
803 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804
805 assert(Bits == 0 && "Extra bits in the identifier?");
806 DataLen -= 8;
807
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 // Set or check the various bits in the IdentifierInfo structure.
809 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000810 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000811 II->revertTokenIDToIdentifier();
812 if (!F.isModule())
813 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
814 else if (HasRevertedBuiltin && II->getBuiltinID()) {
815 II->revertBuiltin();
816 assert((II->hasRevertedBuiltin() ||
817 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
818 "Incorrect ObjC keyword or builtin ID");
819 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000820 assert(II->isExtensionToken() == ExtensionToken &&
821 "Incorrect extension token flag");
822 (void)ExtensionToken;
823 if (Poisoned)
824 II->setIsPoisoned(true);
825 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
826 "Incorrect C++ operator keyword flag");
827 (void)CPlusPlusOperatorKeyword;
828
829 // If this identifier is a macro, deserialize the macro
830 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000831 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 uint32_t MacroDirectivesOffset =
833 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000834 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000835
Richard Smithd7329392015-04-21 21:46:32 +0000836 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 }
838
839 Reader.SetIdentifierInfo(ID, II);
840
841 // Read all of the declarations visible at global scope with this
842 // name.
843 if (DataLen > 0) {
844 SmallVector<uint32_t, 4> DeclIDs;
845 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000846 DeclIDs.push_back(Reader.getGlobalDeclID(
847 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 Reader.SetGloballyVisibleDecls(II, DeclIDs);
849 }
850
851 return II;
852}
853
Richard Smitha06c7e62015-08-26 23:55:49 +0000854DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
855 : Kind(Name.getNameKind()) {
856 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000858 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 break;
860 case DeclarationName::ObjCZeroArgSelector:
861 case DeclarationName::ObjCOneArgSelector:
862 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000863 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 break;
865 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000866 Data = Name.getCXXOverloadedOperator();
867 break;
868 case DeclarationName::CXXLiteralOperatorName:
869 Data = (uint64_t)Name.getCXXLiteralIdentifier();
870 break;
871 case DeclarationName::CXXConstructorName:
872 case DeclarationName::CXXDestructorName:
873 case DeclarationName::CXXConversionFunctionName:
874 case DeclarationName::CXXUsingDirective:
875 Data = 0;
876 break;
877 }
878}
879
880unsigned DeclarationNameKey::getHash() const {
881 llvm::FoldingSetNodeID ID;
882 ID.AddInteger(Kind);
883
884 switch (Kind) {
885 case DeclarationName::Identifier:
886 case DeclarationName::CXXLiteralOperatorName:
887 ID.AddString(((IdentifierInfo*)Data)->getName());
888 break;
889 case DeclarationName::ObjCZeroArgSelector:
890 case DeclarationName::ObjCOneArgSelector:
891 case DeclarationName::ObjCMultiArgSelector:
892 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
893 break;
894 case DeclarationName::CXXOperatorName:
895 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 break;
897 case DeclarationName::CXXConstructorName:
898 case DeclarationName::CXXDestructorName:
899 case DeclarationName::CXXConversionFunctionName:
900 case DeclarationName::CXXUsingDirective:
901 break;
902 }
903
904 return ID.ComputeHash();
905}
906
Richard Smithd88a7f12015-09-01 20:35:42 +0000907ModuleFile *
908ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
909 using namespace llvm::support;
910 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
911 return Reader.getLocalModuleFile(F, ModuleFileID);
912}
913
Guy Benyei11169dd2012-12-18 14:30:41 +0000914std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000915ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
917 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
918 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000919 return std::make_pair(KeyLen, DataLen);
920}
921
Richard Smitha06c7e62015-08-26 23:55:49 +0000922ASTDeclContextNameLookupTrait::internal_key_type
923ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000924 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000925
Richard Smitha06c7e62015-08-26 23:55:49 +0000926 auto Kind = (DeclarationName::NameKind)*d++;
927 uint64_t Data;
928 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000929 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000930 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::ObjCZeroArgSelector:
934 case DeclarationName::ObjCOneArgSelector:
935 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000936 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 (uint64_t)Reader.getLocalSelector(
938 F, endian::readNext<uint32_t, little, unaligned>(
939 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 break;
941 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 break;
944 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000945 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000946 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::CXXConstructorName:
949 case DeclarationName::CXXDestructorName:
950 case DeclarationName::CXXConversionFunctionName:
951 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 break;
954 }
955
Richard Smitha06c7e62015-08-26 23:55:49 +0000956 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000957}
958
Richard Smithd88a7f12015-09-01 20:35:42 +0000959void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
960 const unsigned char *d,
961 unsigned DataLen,
962 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000963 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000964 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
965 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
966 Val.insert(Reader.getGlobalDeclID(F, LocalID));
967 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000968}
969
Richard Smith0f4e2c42015-08-06 04:23:48 +0000970bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
971 BitstreamCursor &Cursor,
972 uint64_t Offset,
973 DeclContext *DC) {
974 assert(Offset != 0);
975
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978
Richard Smith0f4e2c42015-08-06 04:23:48 +0000979 RecordData Record;
980 StringRef Blob;
981 unsigned Code = Cursor.ReadCode();
982 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
983 if (RecCode != DECL_CONTEXT_LEXICAL) {
984 Error("Expected lexical block");
985 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 }
987
Richard Smith82f8fcd2015-08-06 22:07:25 +0000988 assert(!isa<TranslationUnitDecl>(DC) &&
989 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000990 // If we are handling a C++ class template instantiation, we can see multiple
991 // lexical updates for the same record. It's important that we select only one
992 // of them, so that field numbering works properly. Just pick the first one we
993 // see.
994 auto &Lex = LexicalDecls[DC];
995 if (!Lex.first) {
996 Lex = std::make_pair(
997 &M, llvm::makeArrayRef(
998 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
999 Blob.data()),
1000 Blob.size() / 4));
1001 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001002 DC->setHasExternalLexicalStorage(true);
1003 return false;
1004}
Guy Benyei11169dd2012-12-18 14:30:41 +00001005
Richard Smith0f4e2c42015-08-06 04:23:48 +00001006bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1007 BitstreamCursor &Cursor,
1008 uint64_t Offset,
1009 DeclID ID) {
1010 assert(Offset != 0);
1011
1012 SavedStreamPosition SavedPosition(Cursor);
1013 Cursor.JumpToBit(Offset);
1014
1015 RecordData Record;
1016 StringRef Blob;
1017 unsigned Code = Cursor.ReadCode();
1018 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1019 if (RecCode != DECL_CONTEXT_VISIBLE) {
1020 Error("Expected visible lookup table block");
1021 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 }
1023
Richard Smith0f4e2c42015-08-06 04:23:48 +00001024 // We can't safely determine the primary context yet, so delay attaching the
1025 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001026 auto *Data = (const unsigned char*)Blob.data();
1027 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 return false;
1029}
1030
1031void ASTReader::Error(StringRef Msg) {
1032 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001033 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1034 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001035 Diag(diag::note_module_cache_path)
1036 << PP.getHeaderSearchInfo().getModuleCachePath();
1037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001038}
1039
1040void ASTReader::Error(unsigned DiagID,
1041 StringRef Arg1, StringRef Arg2) {
1042 if (Diags.isDiagnosticInFlight())
1043 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1044 else
1045 Diag(DiagID) << Arg1 << Arg2;
1046}
1047
1048//===----------------------------------------------------------------------===//
1049// Source Manager Deserialization
1050//===----------------------------------------------------------------------===//
1051
1052/// \brief Read the line table in the source manager block.
1053/// \returns true if there was an error.
1054bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001055 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001056 unsigned Idx = 0;
1057 LineTableInfo &LineTable = SourceMgr.getLineTable();
1058
1059 // Parse the file names
1060 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001061 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001063 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001064 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1065 }
Richard Smith63078492015-09-01 07:41:55 +00001066 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001067
1068 // Parse the line entries
1069 std::vector<LineEntry> Entries;
1070 while (Idx < Record.size()) {
1071 int FID = Record[Idx++];
1072 assert(FID >= 0 && "Serialized line entries for non-local file.");
1073 // Remap FileID from 1-based old view.
1074 FID += F.SLocEntryBaseID - 1;
1075
1076 // Extract the line entries
1077 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001078 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 Entries.clear();
1080 Entries.reserve(NumEntries);
1081 for (unsigned I = 0; I != NumEntries; ++I) {
1082 unsigned FileOffset = Record[Idx++];
1083 unsigned LineNo = Record[Idx++];
1084 int FilenameID = FileIDs[Record[Idx++]];
1085 SrcMgr::CharacteristicKind FileKind
1086 = (SrcMgr::CharacteristicKind)Record[Idx++];
1087 unsigned IncludeOffset = Record[Idx++];
1088 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1089 FileKind, IncludeOffset));
1090 }
1091 LineTable.AddEntry(FileID::get(FID), Entries);
1092 }
1093
1094 return false;
1095}
1096
1097/// \brief Read a source manager block
1098bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1099 using namespace SrcMgr;
1100
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001101 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
1103 // Set the source-location entry cursor to the current position in
1104 // the stream. This cursor will be used to read the contents of the
1105 // source manager block initially, and then lazily read
1106 // source-location entries as needed.
1107 SLocEntryCursor = F.Stream;
1108
1109 // The stream itself is going to skip over the source manager block.
1110 if (F.Stream.SkipBlock()) {
1111 Error("malformed block record in AST file");
1112 return true;
1113 }
1114
1115 // Enter the source manager block.
1116 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1117 Error("malformed source manager block record in AST file");
1118 return true;
1119 }
1120
1121 RecordData Record;
1122 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001123 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1124
1125 switch (E.Kind) {
1126 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1127 case llvm::BitstreamEntry::Error:
1128 Error("malformed block record in AST file");
1129 return true;
1130 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001132 case llvm::BitstreamEntry::Record:
1133 // The interesting case.
1134 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001136
Guy Benyei11169dd2012-12-18 14:30:41 +00001137 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001139 StringRef Blob;
1140 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 default: // Default behavior: ignore.
1142 break;
1143
1144 case SM_SLOC_FILE_ENTRY:
1145 case SM_SLOC_BUFFER_ENTRY:
1146 case SM_SLOC_EXPANSION_ENTRY:
1147 // Once we hit one of the source location entries, we're done.
1148 return false;
1149 }
1150 }
1151}
1152
1153/// \brief If a header file is not found at the path that we expect it to be
1154/// and the PCH file was moved from its original location, try to resolve the
1155/// file by assuming that header+PCH were moved together and the header is in
1156/// the same place relative to the PCH.
1157static std::string
1158resolveFileRelativeToOriginalDir(const std::string &Filename,
1159 const std::string &OriginalDir,
1160 const std::string &CurrDir) {
1161 assert(OriginalDir != CurrDir &&
1162 "No point trying to resolve the file if the PCH dir didn't change");
1163 using namespace llvm::sys;
1164 SmallString<128> filePath(Filename);
1165 fs::make_absolute(filePath);
1166 assert(path::is_absolute(OriginalDir));
1167 SmallString<128> currPCHPath(CurrDir);
1168
1169 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1170 fileDirE = path::end(path::parent_path(filePath));
1171 path::const_iterator origDirI = path::begin(OriginalDir),
1172 origDirE = path::end(OriginalDir);
1173 // Skip the common path components from filePath and OriginalDir.
1174 while (fileDirI != fileDirE && origDirI != origDirE &&
1175 *fileDirI == *origDirI) {
1176 ++fileDirI;
1177 ++origDirI;
1178 }
1179 for (; origDirI != origDirE; ++origDirI)
1180 path::append(currPCHPath, "..");
1181 path::append(currPCHPath, fileDirI, fileDirE);
1182 path::append(currPCHPath, path::filename(Filename));
1183 return currPCHPath.str();
1184}
1185
1186bool ASTReader::ReadSLocEntry(int ID) {
1187 if (ID == 0)
1188 return false;
1189
1190 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1191 Error("source location entry ID out-of-range for AST file");
1192 return true;
1193 }
1194
1195 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1196 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001197 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 unsigned BaseOffset = F->SLocEntryBaseOffset;
1199
1200 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001201 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1202 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001203 Error("incorrectly-formatted source location entry in AST file");
1204 return true;
1205 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001206
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001208 StringRef Blob;
1209 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 default:
1211 Error("incorrectly-formatted source location entry in AST file");
1212 return true;
1213
1214 case SM_SLOC_FILE_ENTRY: {
1215 // We will detect whether a file changed and return 'Failure' for it, but
1216 // we will also try to fail gracefully by setting up the SLocEntry.
1217 unsigned InputID = Record[4];
1218 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001219 const FileEntry *File = IF.getFile();
1220 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001221
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001222 // Note that we only check if a File was returned. If it was out-of-date
1223 // we have complained but we will continue creating a FileID to recover
1224 // gracefully.
1225 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 return true;
1227
1228 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1229 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1230 // This is the module's main file.
1231 IncludeLoc = getImportLocation(F);
1232 }
1233 SrcMgr::CharacteristicKind
1234 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1235 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1236 ID, BaseOffset + Record[0]);
1237 SrcMgr::FileInfo &FileInfo =
1238 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1239 FileInfo.NumCreatedFIDs = Record[5];
1240 if (Record[3])
1241 FileInfo.setHasLineDirectives();
1242
1243 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1244 unsigned NumFileDecls = Record[7];
1245 if (NumFileDecls) {
1246 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1247 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1248 NumFileDecls));
1249 }
1250
1251 const SrcMgr::ContentCache *ContentCache
1252 = SourceMgr.getOrCreateContentCache(File,
1253 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1254 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1255 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1256 unsigned Code = SLocEntryCursor.ReadCode();
1257 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001258 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001259
1260 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1261 Error("AST record has invalid code");
1262 return true;
1263 }
1264
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001265 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001267 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 }
1269
1270 break;
1271 }
1272
1273 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001274 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001275 unsigned Offset = Record[0];
1276 SrcMgr::CharacteristicKind
1277 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1278 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001279 if (IncludeLoc.isInvalid() &&
1280 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001281 IncludeLoc = getImportLocation(F);
1282 }
1283 unsigned Code = SLocEntryCursor.ReadCode();
1284 Record.clear();
1285 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001286 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001287
1288 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1289 Error("AST record has invalid code");
1290 return true;
1291 }
1292
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001293 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1294 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001295 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001296 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 break;
1298 }
1299
1300 case SM_SLOC_EXPANSION_ENTRY: {
1301 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1302 SourceMgr.createExpansionLoc(SpellingLoc,
1303 ReadSourceLocation(*F, Record[2]),
1304 ReadSourceLocation(*F, Record[3]),
1305 Record[4],
1306 ID,
1307 BaseOffset + Record[0]);
1308 break;
1309 }
1310 }
1311
1312 return false;
1313}
1314
1315std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1316 if (ID == 0)
1317 return std::make_pair(SourceLocation(), "");
1318
1319 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1320 Error("source location entry ID out-of-range for AST file");
1321 return std::make_pair(SourceLocation(), "");
1322 }
1323
1324 // Find which module file this entry lands in.
1325 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001326 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 return std::make_pair(SourceLocation(), "");
1328
1329 // FIXME: Can we map this down to a particular submodule? That would be
1330 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001331 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001332}
1333
1334/// \brief Find the location where the module F is imported.
1335SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1336 if (F->ImportLoc.isValid())
1337 return F->ImportLoc;
1338
1339 // Otherwise we have a PCH. It's considered to be "imported" at the first
1340 // location of its includer.
1341 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001342 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001343 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001344 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 return F->ImportedBy[0]->FirstLoc;
1347}
1348
1349/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1350/// specified cursor. Read the abbreviations that are at the top of the block
1351/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001352bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001353 if (Cursor.EnterSubBlock(BlockID))
1354 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001355
1356 while (true) {
1357 uint64_t Offset = Cursor.GetCurrentBitNo();
1358 unsigned Code = Cursor.ReadCode();
1359
1360 // We expect all abbrevs to be at the start of the block.
1361 if (Code != llvm::bitc::DEFINE_ABBREV) {
1362 Cursor.JumpToBit(Offset);
1363 return false;
1364 }
1365 Cursor.ReadAbbrevRecord();
1366 }
1367}
1368
Richard Smithe40f2ba2013-08-07 21:41:30 +00001369Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001370 unsigned &Idx) {
1371 Token Tok;
1372 Tok.startToken();
1373 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1374 Tok.setLength(Record[Idx++]);
1375 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1376 Tok.setIdentifierInfo(II);
1377 Tok.setKind((tok::TokenKind)Record[Idx++]);
1378 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1379 return Tok;
1380}
1381
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384
1385 // Keep track of where we are in the stream, then jump back there
1386 // after reading this macro.
1387 SavedStreamPosition SavedPosition(Stream);
1388
1389 Stream.JumpToBit(Offset);
1390 RecordData Record;
1391 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001392 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 // Advance to the next record, but if we get to the end of the block, don't
1396 // pop it (removing all the abbreviations from the cursor) since we want to
1397 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001398 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001399 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1400
1401 switch (Entry.Kind) {
1402 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1403 case llvm::BitstreamEntry::Error:
1404 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001408 case llvm::BitstreamEntry::Record:
1409 // The interesting case.
1410 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 }
1412
1413 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 Record.clear();
1415 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001418 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 case PP_MACRO_DIRECTIVE_HISTORY:
1420 return Macro;
1421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 case PP_MACRO_OBJECT_LIKE:
1423 case PP_MACRO_FUNCTION_LIKE: {
1424 // If we already have a macro, that means that we've hit the end
1425 // of the definition of the macro we were looking for. We're
1426 // done.
1427 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 unsigned NextIndex = 1; // Skip identifier ID.
1431 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001433 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001434 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001436 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1439 // Decode function-like macro info.
1440 bool isC99VarArgs = Record[NextIndex++];
1441 bool isGNUVarArgs = Record[NextIndex++];
1442 bool hasCommaPasting = Record[NextIndex++];
1443 MacroArgs.clear();
1444 unsigned NumArgs = Record[NextIndex++];
1445 for (unsigned i = 0; i != NumArgs; ++i)
1446 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1447
1448 // Install function-like macro info.
1449 MI->setIsFunctionLike();
1450 if (isC99VarArgs) MI->setIsC99Varargs();
1451 if (isGNUVarArgs) MI->setIsGNUVarargs();
1452 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001453 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 }
1455
Guy Benyei11169dd2012-12-18 14:30:41 +00001456 // Remember that we saw this macro last so that we add the tokens that
1457 // form its body to it.
1458 Macro = MI;
1459
1460 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1461 Record[NextIndex]) {
1462 // We have a macro definition. Register the association
1463 PreprocessedEntityID
1464 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1465 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001466 PreprocessingRecord::PPEntityID PPID =
1467 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1468 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1469 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001470 if (PPDef)
1471 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 }
1473
1474 ++NumMacrosRead;
1475 break;
1476 }
1477
1478 case PP_TOKEN: {
1479 // If we see a TOKEN before a PP_MACRO_*, then the file is
1480 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001481 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001482
John McCallf413f5e2013-05-03 00:10:13 +00001483 unsigned Idx = 0;
1484 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 Macro->AddTokenToBody(Tok);
1486 break;
1487 }
1488 }
1489 }
1490}
1491
1492PreprocessedEntityID
1493ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1494 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1495 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1496 assert(I != M.PreprocessedEntityRemap.end()
1497 && "Invalid index into preprocessed entity index remap");
1498
1499 return LocalID + I->second;
1500}
1501
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1503 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001504}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001505
Guy Benyei11169dd2012-12-18 14:30:41 +00001506HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001507HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001508 internal_key_type ikey = {FE->getSize(),
1509 M.HasTimestamps ? FE->getModificationTime() : 0,
1510 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001511 return ikey;
1512}
Guy Benyei11169dd2012-12-18 14:30:41 +00001513
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001515 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 return false;
1517
Richard Smith7ed1bc92014-12-05 22:42:13 +00001518 if (llvm::sys::path::is_absolute(a.Filename) &&
1519 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 return true;
1521
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001523 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001524 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1525 if (!Key.Imported)
1526 return FileMgr.getFile(Key.Filename);
1527
1528 std::string Resolved = Key.Filename;
1529 Reader.ResolveImportedPath(M, Resolved);
1530 return FileMgr.getFile(Resolved);
1531 };
1532
1533 const FileEntry *FEA = GetFile(a);
1534 const FileEntry *FEB = GetFile(b);
1535 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001536}
1537
1538std::pair<unsigned, unsigned>
1539HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001540 using namespace llvm::support;
1541 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001543 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001544}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001545
1546HeaderFileInfoTrait::internal_key_type
1547HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001548 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001549 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1551 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001552 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001553 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001554 return ikey;
1555}
1556
Guy Benyei11169dd2012-12-18 14:30:41 +00001557HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001558HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001559 unsigned DataLen) {
1560 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001561 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 HeaderFileInfo HFI;
1563 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001564 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1565 HFI.isImport |= (Flags >> 4) & 0x01;
1566 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1567 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001568 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001569 // FIXME: Find a better way to handle this. Maybe just store a
1570 // "has been included" flag?
1571 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1572 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001573 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1574 M, endian::readNext<uint32_t, little, unaligned>(d));
1575 if (unsigned FrameworkOffset =
1576 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001577 // The framework offset is 1 greater than the actual offset,
1578 // since 0 is used as an indicator for "no framework name".
1579 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1580 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1581 }
Richard Smith386bb072015-08-18 23:42:23 +00001582
1583 assert((End - d) % 4 == 0 &&
1584 "Wrong data length in HeaderFileInfo deserialization");
1585 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001586 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001587 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1588 LocalSMID >>= 2;
1589
1590 // This header is part of a module. Associate it with the module to enable
1591 // implicit module import.
1592 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1593 Module *Mod = Reader.getSubmodule(GlobalSMID);
1594 FileManager &FileMgr = Reader.getFileManager();
1595 ModuleMap &ModMap =
1596 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1597
1598 std::string Filename = key.Filename;
1599 if (key.Imported)
1600 Reader.ResolveImportedPath(M, Filename);
1601 // FIXME: This is not always the right filename-as-written, but we're not
1602 // going to use this information to rebuild the module, so it doesn't make
1603 // a lot of difference.
1604 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001605 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1606 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001607 }
1608
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 // This HeaderFileInfo was externally loaded.
1610 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001611 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 return HFI;
1613}
1614
Richard Smithd7329392015-04-21 21:46:32 +00001615void ASTReader::addPendingMacro(IdentifierInfo *II,
1616 ModuleFile *M,
1617 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001618 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1619 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001620}
1621
1622void ASTReader::ReadDefinedMacros() {
1623 // Note that we are loading defined macros.
1624 Deserializing Macros(this);
1625
Pete Cooper57d3f142015-07-30 17:22:52 +00001626 for (auto &I : llvm::reverse(ModuleMgr)) {
1627 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628
1629 // If there was no preprocessor block, skip this file.
1630 if (!MacroCursor.getBitStreamReader())
1631 continue;
1632
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001633 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001634 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001635
1636 RecordData Record;
1637 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001638 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1639
1640 switch (E.Kind) {
1641 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1642 case llvm::BitstreamEntry::Error:
1643 Error("malformed block record in AST file");
1644 return;
1645 case llvm::BitstreamEntry::EndBlock:
1646 goto NextCursor;
1647
1648 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001649 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001650 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001651 default: // Default behavior: ignore.
1652 break;
1653
1654 case PP_MACRO_OBJECT_LIKE:
1655 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001656 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001657 break;
1658
1659 case PP_TOKEN:
1660 // Ignore tokens.
1661 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 break;
1664 }
1665 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001666 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 }
1668}
1669
1670namespace {
1671 /// \brief Visitor class used to look up identifirs in an AST file.
1672 class IdentifierLookupVisitor {
1673 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001674 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001675 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001676 unsigned &NumIdentifierLookups;
1677 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001681 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1682 unsigned &NumIdentifierLookups,
1683 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001684 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1685 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001686 NumIdentifierLookups(NumIdentifierLookups),
1687 NumIdentifierLookupHits(NumIdentifierLookupHits),
1688 Found()
1689 {
1690 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001691
1692 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001694 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001696
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 ASTIdentifierLookupTable *IdTable
1698 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1699 if (!IdTable)
1700 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001701
1702 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001703 Found);
1704 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001705 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001706 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 if (Pos == IdTable->end())
1708 return false;
1709
1710 // Dereferencing the iterator has the effect of building the
1711 // IdentifierInfo node and populating it with the various
1712 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001713 ++NumIdentifierLookupHits;
1714 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 return true;
1716 }
1717
1718 // \brief Retrieve the identifier info found within the module
1719 // files.
1720 IdentifierInfo *getIdentifierInfo() const { return Found; }
1721 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001722}
Guy Benyei11169dd2012-12-18 14:30:41 +00001723
1724void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1725 // Note that we are loading an identifier.
1726 Deserializing AnIdentifier(this);
1727
1728 unsigned PriorGeneration = 0;
1729 if (getContext().getLangOpts().Modules)
1730 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001731
1732 // If there is a global index, look there first to determine which modules
1733 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001734 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001735 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001736 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001737 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1738 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001739 }
1740 }
1741
Douglas Gregor7211ac12013-01-25 23:32:03 +00001742 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001743 NumIdentifierLookups,
1744 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001745 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001746 markIdentifierUpToDate(&II);
1747}
1748
1749void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1750 if (!II)
1751 return;
1752
1753 II->setOutOfDate(false);
1754
1755 // Update the generation for this identifier.
1756 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001757 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001758}
1759
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001760void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1761 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001762 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001763
1764 BitstreamCursor &Cursor = M.MacroCursor;
1765 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001766 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001767
Richard Smith713369b2015-04-23 20:40:50 +00001768 struct ModuleMacroRecord {
1769 SubmoduleID SubModID;
1770 MacroInfo *MI;
1771 SmallVector<SubmoduleID, 8> Overrides;
1772 };
1773 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001774
Richard Smithd7329392015-04-21 21:46:32 +00001775 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1776 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1777 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001778 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001779 while (true) {
1780 llvm::BitstreamEntry Entry =
1781 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1782 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1783 Error("malformed block record in AST file");
1784 return;
1785 }
1786
1787 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001788 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001789 case PP_MACRO_DIRECTIVE_HISTORY:
1790 break;
1791
1792 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001793 ModuleMacros.push_back(ModuleMacroRecord());
1794 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001795 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1796 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001797 for (int I = 2, N = Record.size(); I != N; ++I)
1798 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001799 continue;
1800 }
1801
1802 default:
1803 Error("malformed block record in AST file");
1804 return;
1805 }
1806
1807 // We found the macro directive history; that's the last record
1808 // for this macro.
1809 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810 }
1811
Richard Smithd7329392015-04-21 21:46:32 +00001812 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001813 {
1814 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001815 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001816 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001817 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001818 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001819 Module *Mod = getSubmodule(ModID);
1820 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001821 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001822 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001823 }
1824
1825 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001826 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001827 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001828 }
1829 }
1830
1831 // Don't read the directive history for a module; we don't have anywhere
1832 // to put it.
1833 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1834 return;
1835
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001836 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001837 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001838 unsigned Idx = 0, N = Record.size();
1839 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001840 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001841 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001842 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1843 switch (K) {
1844 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001845 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001846 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001847 break;
1848 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001849 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001850 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001851 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001852 }
1853 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001854 bool isPublic = Record[Idx++];
1855 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1856 break;
1857 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858
1859 if (!Latest)
1860 Latest = MD;
1861 if (Earliest)
1862 Earliest->setPrevious(MD);
1863 Earliest = MD;
1864 }
1865
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001866 if (Latest)
1867 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001868}
1869
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001870ASTReader::InputFileInfo
1871ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001872 // Go find this input file.
1873 BitstreamCursor &Cursor = F.InputFilesCursor;
1874 SavedStreamPosition SavedPosition(Cursor);
1875 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1876
1877 unsigned Code = Cursor.ReadCode();
1878 RecordData Record;
1879 StringRef Blob;
1880
1881 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1882 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1883 "invalid record type for input file");
1884 (void)Result;
1885
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001886 std::string Filename;
1887 off_t StoredSize;
1888 time_t StoredTime;
1889 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001890
Ben Langmuir198c1682014-03-07 07:27:49 +00001891 assert(Record[0] == ID && "Bogus stored ID or offset");
1892 StoredSize = static_cast<off_t>(Record[1]);
1893 StoredTime = static_cast<time_t>(Record[2]);
1894 Overridden = static_cast<bool>(Record[3]);
1895 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001896 ResolveImportedPath(F, Filename);
1897
Hans Wennborg73945142014-03-14 17:45:06 +00001898 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1899 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001900}
1901
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001902InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 // If this ID is bogus, just return an empty input file.
1904 if (ID == 0 || ID > F.InputFilesLoaded.size())
1905 return InputFile();
1906
1907 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001908 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 return F.InputFilesLoaded[ID-1];
1910
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001911 if (F.InputFilesLoaded[ID-1].isNotFound())
1912 return InputFile();
1913
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001915 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 SavedStreamPosition SavedPosition(Cursor);
1917 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1918
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001919 InputFileInfo FI = readInputFileInfo(F, ID);
1920 off_t StoredSize = FI.StoredSize;
1921 time_t StoredTime = FI.StoredTime;
1922 bool Overridden = FI.Overridden;
1923 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001924
Ben Langmuir198c1682014-03-07 07:27:49 +00001925 const FileEntry *File
1926 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1927 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1928
1929 // If we didn't find the file, resolve it relative to the
1930 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001931 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 F.OriginalDir != CurrentDir) {
1933 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1934 F.OriginalDir,
1935 CurrentDir);
1936 if (!Resolved.empty())
1937 File = FileMgr.getFile(Resolved);
1938 }
1939
1940 // For an overridden file, create a virtual file with the stored
1941 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001942 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001943 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1944 }
1945
Craig Toppera13603a2014-05-22 05:54:18 +00001946 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001947 if (Complain) {
1948 std::string ErrorStr = "could not find file '";
1949 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001950 ErrorStr += "' referenced by AST file '";
1951 ErrorStr += F.FileName;
1952 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001953 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001954 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001955 // Record that we didn't find the file.
1956 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1957 return InputFile();
1958 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001959
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 // Check if there was a request to override the contents of the file
1961 // that was part of the precompiled header. Overridding such a file
1962 // can lead to problems when lexing using the source locations from the
1963 // PCH.
1964 SourceManager &SM = getSourceManager();
1965 if (!Overridden && SM.isFileOverridden(File)) {
1966 if (Complain)
1967 Error(diag::err_fe_pch_file_overridden, Filename);
1968 // After emitting the diagnostic, recover by disabling the override so
1969 // that the original file will be used.
1970 SM.disableFileContentsOverride(File);
1971 // The FileEntry is a virtual file entry with the size of the contents
1972 // that would override the original contents. Set it to the original's
1973 // size/time.
1974 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1975 StoredSize, StoredTime);
1976 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001977
Ben Langmuir198c1682014-03-07 07:27:49 +00001978 bool IsOutOfDate = false;
1979
1980 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001981 if (!Overridden && //
1982 (StoredSize != File->getSize() ||
1983#if defined(LLVM_ON_WIN32)
1984 false
1985#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001986 // In our regression testing, the Windows file system seems to
1987 // have inconsistent modification times that sometimes
1988 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001989 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001990 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1991 (StoredTime && StoredTime != File->getModificationTime() &&
1992 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001993#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 )) {
1995 if (Complain) {
1996 // Build a list of the PCH imports that got us here (in reverse).
1997 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1998 while (ImportStack.back()->ImportedBy.size() > 0)
1999 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002000
Ben Langmuir198c1682014-03-07 07:27:49 +00002001 // The top-level PCH is stale.
2002 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2003 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002004
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 // Print the import stack.
2006 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2007 Diag(diag::note_pch_required_by)
2008 << Filename << ImportStack[0]->FileName;
2009 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002010 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002011 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002012 }
2013
Ben Langmuir198c1682014-03-07 07:27:49 +00002014 if (!Diags.isDiagnosticInFlight())
2015 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 }
2017
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 }
2020
Ben Langmuir198c1682014-03-07 07:27:49 +00002021 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2022
2023 // Note that we've loaded this input file.
2024 F.InputFilesLoaded[ID-1] = IF;
2025 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026}
2027
Richard Smith7ed1bc92014-12-05 22:42:13 +00002028/// \brief If we are loading a relocatable PCH or module file, and the filename
2029/// is not an absolute path, add the system or module root to the beginning of
2030/// the file name.
2031void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2032 // Resolve relative to the base directory, if we have one.
2033 if (!M.BaseDirectory.empty())
2034 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002035}
2036
Richard Smith7ed1bc92014-12-05 22:42:13 +00002037void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2039 return;
2040
Richard Smith7ed1bc92014-12-05 22:42:13 +00002041 SmallString<128> Buffer;
2042 llvm::sys::path::append(Buffer, Prefix, Filename);
2043 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002044}
2045
Richard Smith0f99d6a2015-08-09 08:48:41 +00002046static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2047 switch (ARR) {
2048 case ASTReader::Failure: return true;
2049 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2050 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2051 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2052 case ASTReader::ConfigurationMismatch:
2053 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2054 case ASTReader::HadErrors: return true;
2055 case ASTReader::Success: return false;
2056 }
2057
2058 llvm_unreachable("unknown ASTReadResult");
2059}
2060
Richard Smith0516b182015-09-08 19:40:14 +00002061ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2062 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2063 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2064 std::string &SuggestedPredefines) {
2065 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2066 return Failure;
2067
2068 // Read all of the records in the options block.
2069 RecordData Record;
2070 ASTReadResult Result = Success;
2071 while (1) {
2072 llvm::BitstreamEntry Entry = Stream.advance();
2073
2074 switch (Entry.Kind) {
2075 case llvm::BitstreamEntry::Error:
2076 case llvm::BitstreamEntry::SubBlock:
2077 return Failure;
2078
2079 case llvm::BitstreamEntry::EndBlock:
2080 return Result;
2081
2082 case llvm::BitstreamEntry::Record:
2083 // The interesting case.
2084 break;
2085 }
2086
2087 // Read and process a record.
2088 Record.clear();
2089 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2090 case LANGUAGE_OPTIONS: {
2091 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2092 if (ParseLanguageOptions(Record, Complain, Listener,
2093 AllowCompatibleConfigurationMismatch))
2094 Result = ConfigurationMismatch;
2095 break;
2096 }
2097
2098 case TARGET_OPTIONS: {
2099 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2100 if (ParseTargetOptions(Record, Complain, Listener,
2101 AllowCompatibleConfigurationMismatch))
2102 Result = ConfigurationMismatch;
2103 break;
2104 }
2105
2106 case DIAGNOSTIC_OPTIONS: {
2107 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2108 if (!AllowCompatibleConfigurationMismatch &&
2109 ParseDiagnosticOptions(Record, Complain, Listener))
2110 return OutOfDate;
2111 break;
2112 }
2113
2114 case FILE_SYSTEM_OPTIONS: {
2115 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2116 if (!AllowCompatibleConfigurationMismatch &&
2117 ParseFileSystemOptions(Record, Complain, Listener))
2118 Result = ConfigurationMismatch;
2119 break;
2120 }
2121
2122 case HEADER_SEARCH_OPTIONS: {
2123 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2124 if (!AllowCompatibleConfigurationMismatch &&
2125 ParseHeaderSearchOptions(Record, Complain, Listener))
2126 Result = ConfigurationMismatch;
2127 break;
2128 }
2129
2130 case PREPROCESSOR_OPTIONS:
2131 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2132 if (!AllowCompatibleConfigurationMismatch &&
2133 ParsePreprocessorOptions(Record, Complain, Listener,
2134 SuggestedPredefines))
2135 Result = ConfigurationMismatch;
2136 break;
2137 }
2138 }
2139}
2140
Guy Benyei11169dd2012-12-18 14:30:41 +00002141ASTReader::ASTReadResult
2142ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002143 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002144 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002146 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002147
2148 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2149 Error("malformed block record in AST file");
2150 return Failure;
2151 }
2152
2153 // Read all of the records and blocks in the control block.
2154 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002155 unsigned NumInputs = 0;
2156 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002157 while (1) {
2158 llvm::BitstreamEntry Entry = Stream.advance();
2159
2160 switch (Entry.Kind) {
2161 case llvm::BitstreamEntry::Error:
2162 Error("malformed block record in AST file");
2163 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002164 case llvm::BitstreamEntry::EndBlock: {
2165 // Validate input files.
2166 const HeaderSearchOptions &HSOpts =
2167 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002168
Richard Smitha1825302014-10-23 22:18:29 +00002169 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002170 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2171 // loaded module files, ignore missing inputs.
2172 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002173 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002174
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002175 // If we are reading a module, we will create a verification timestamp,
2176 // so we verify all input files. Otherwise, verify only user input
2177 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002178
2179 unsigned N = NumUserInputs;
2180 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002181 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002182 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002183 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002184 N = NumInputs;
2185
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002186 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002187 InputFile IF = getInputFile(F, I+1, Complain);
2188 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002189 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002190 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002192
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002193 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002194 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002195
Ben Langmuircb69b572014-03-07 06:40:32 +00002196 if (Listener && Listener->needsInputFileVisitation()) {
2197 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2198 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002199 for (unsigned I = 0; I < N; ++I) {
2200 bool IsSystem = I >= NumUserInputs;
2201 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002202 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2203 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002204 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002205 }
2206
Guy Benyei11169dd2012-12-18 14:30:41 +00002207 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002208 }
2209
Chris Lattnere7b154b2013-01-19 21:39:22 +00002210 case llvm::BitstreamEntry::SubBlock:
2211 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 case INPUT_FILES_BLOCK_ID:
2213 F.InputFilesCursor = Stream;
2214 if (Stream.SkipBlock() || // Skip with the main cursor
2215 // Read the abbreviations
2216 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2217 Error("malformed block record in AST file");
2218 return Failure;
2219 }
2220 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002221
2222 case OPTIONS_BLOCK_ID:
2223 // If we're reading the first module for this group, check its options
2224 // are compatible with ours. For modules it imports, no further checking
2225 // is required, because we checked them when we built it.
2226 if (Listener && !ImportedBy) {
2227 // Should we allow the configuration of the module file to differ from
2228 // the configuration of the current translation unit in a compatible
2229 // way?
2230 //
2231 // FIXME: Allow this for files explicitly specified with -include-pch.
2232 bool AllowCompatibleConfigurationMismatch =
2233 F.Kind == MK_ExplicitModule;
2234
2235 auto Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2236 AllowCompatibleConfigurationMismatch,
2237 *Listener, SuggestedPredefines);
2238 if (Result == Failure) {
2239 Error("malformed block record in AST file");
2240 return Result;
2241 }
2242
2243 if (!DisableValidation && Result != Success &&
2244 (Result != ConfigurationMismatch || !AllowConfigurationMismatch))
2245 return Result;
2246 } else if (Stream.SkipBlock()) {
2247 Error("malformed block record in AST file");
2248 return Failure;
2249 }
2250 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002251
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002253 if (Stream.SkipBlock()) {
2254 Error("malformed block record in AST file");
2255 return Failure;
2256 }
2257 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002259
2260 case llvm::BitstreamEntry::Record:
2261 // The interesting case.
2262 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 }
2264
2265 // Read and process a record.
2266 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002267 StringRef Blob;
2268 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 case METADATA: {
2270 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2271 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002272 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2273 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 return VersionMismatch;
2275 }
2276
Richard Smithe75ee0f2015-08-17 07:13:32 +00002277 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2279 Diag(diag::err_pch_with_compiler_errors);
2280 return HadErrors;
2281 }
2282
2283 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002284 // Relative paths in a relocatable PCH are relative to our sysroot.
2285 if (F.RelocatablePCH)
2286 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002287
Richard Smithe75ee0f2015-08-17 07:13:32 +00002288 F.HasTimestamps = Record[5];
2289
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002291 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2293 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002294 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 return VersionMismatch;
2296 }
2297 break;
2298 }
2299
Ben Langmuir487ea142014-10-23 18:05:36 +00002300 case SIGNATURE:
2301 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2302 F.Signature = Record[0];
2303 break;
2304
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 case IMPORTS: {
2306 // Load each of the imported PCH files.
2307 unsigned Idx = 0, N = Record.size();
2308 while (Idx < N) {
2309 // Read information about the AST file.
2310 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2311 // The import location will be the local one for now; we will adjust
2312 // all import locations of module imports after the global source
2313 // location info are setup.
2314 SourceLocation ImportLoc =
2315 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002316 off_t StoredSize = (off_t)Record[Idx++];
2317 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002318 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002319 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002320
Richard Smith0f99d6a2015-08-09 08:48:41 +00002321 // If our client can't cope with us being out of date, we can't cope with
2322 // our dependency being missing.
2323 unsigned Capabilities = ClientLoadCapabilities;
2324 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2325 Capabilities &= ~ARR_Missing;
2326
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002328 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2329 Loaded, StoredSize, StoredModTime,
2330 StoredSignature, Capabilities);
2331
2332 // If we diagnosed a problem, produce a backtrace.
2333 if (isDiagnosedResult(Result, Capabilities))
2334 Diag(diag::note_module_file_imported_by)
2335 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2336
2337 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 case Failure: return Failure;
2339 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002340 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 case OutOfDate: return OutOfDate;
2342 case VersionMismatch: return VersionMismatch;
2343 case ConfigurationMismatch: return ConfigurationMismatch;
2344 case HadErrors: return HadErrors;
2345 case Success: break;
2346 }
2347 }
2348 break;
2349 }
2350
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 case ORIGINAL_FILE:
2352 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002353 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002355 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 break;
2357
2358 case ORIGINAL_FILE_ID:
2359 F.OriginalSourceFileID = FileID::get(Record[0]);
2360 break;
2361
2362 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002363 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 break;
2365
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002366 case MODULE_NAME:
2367 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002368 if (Listener)
2369 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002370 break;
2371
Richard Smith223d3f22014-12-06 03:21:08 +00002372 case MODULE_DIRECTORY: {
2373 assert(!F.ModuleName.empty() &&
2374 "MODULE_DIRECTORY found before MODULE_NAME");
2375 // If we've already loaded a module map file covering this module, we may
2376 // have a better path for it (relative to the current build).
2377 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2378 if (M && M->Directory) {
2379 // If we're implicitly loading a module, the base directory can't
2380 // change between the build and use.
2381 if (F.Kind != MK_ExplicitModule) {
2382 const DirectoryEntry *BuildDir =
2383 PP.getFileManager().getDirectory(Blob);
2384 if (!BuildDir || BuildDir != M->Directory) {
2385 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2386 Diag(diag::err_imported_module_relocated)
2387 << F.ModuleName << Blob << M->Directory->getName();
2388 return OutOfDate;
2389 }
2390 }
2391 F.BaseDirectory = M->Directory->getName();
2392 } else {
2393 F.BaseDirectory = Blob;
2394 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002395 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002396 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002397
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002398 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002399 if (ASTReadResult Result =
2400 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2401 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002402 break;
2403
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002404 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002405 NumInputs = Record[0];
2406 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002407 F.InputFileOffsets =
2408 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002409 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 break;
2411 }
2412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002413}
2414
Ben Langmuir2c9af442014-04-10 17:57:43 +00002415ASTReader::ASTReadResult
2416ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002417 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418
2419 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2420 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 }
2423
2424 // Read all of the records and blocks for the AST file.
2425 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426 while (1) {
2427 llvm::BitstreamEntry Entry = Stream.advance();
2428
2429 switch (Entry.Kind) {
2430 case llvm::BitstreamEntry::Error:
2431 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002432 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002434 // Outside of C++, we do not store a lookup map for the translation unit.
2435 // Instead, mark it as needing a lookup map to be built if this module
2436 // contains any declarations lexically within it (which it always does!).
2437 // This usually has no cost, since we very rarely need the lookup map for
2438 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002440 if (DC->hasExternalLexicalStorage() &&
2441 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002443
Ben Langmuir2c9af442014-04-10 17:57:43 +00002444 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002446 case llvm::BitstreamEntry::SubBlock:
2447 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 case DECLTYPES_BLOCK_ID:
2449 // We lazily load the decls block, but we want to set up the
2450 // DeclsCursor cursor to point into it. Clone our current bitcode
2451 // cursor to it, enter the block and read the abbrevs in that block.
2452 // With the main cursor, we just skip over it.
2453 F.DeclsCursor = Stream;
2454 if (Stream.SkipBlock() || // Skip with the main cursor.
2455 // Read the abbrevs.
2456 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2457 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002458 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 }
2460 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002461
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 case PREPROCESSOR_BLOCK_ID:
2463 F.MacroCursor = Stream;
2464 if (!PP.getExternalSource())
2465 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002466
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 if (Stream.SkipBlock() ||
2468 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2469 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002470 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 }
2472 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2473 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002474
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 case PREPROCESSOR_DETAIL_BLOCK_ID:
2476 F.PreprocessorDetailCursor = Stream;
2477 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002478 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002480 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002481 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002482 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002484 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2485
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 if (!PP.getPreprocessingRecord())
2487 PP.createPreprocessingRecord();
2488 if (!PP.getPreprocessingRecord()->getExternalSource())
2489 PP.getPreprocessingRecord()->SetExternalSource(*this);
2490 break;
2491
2492 case SOURCE_MANAGER_BLOCK_ID:
2493 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002496
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002498 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2499 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002501
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002503 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 if (Stream.SkipBlock() ||
2505 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2506 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002507 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 }
2509 CommentsCursors.push_back(std::make_pair(C, &F));
2510 break;
2511 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002512
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514 if (Stream.SkipBlock()) {
2515 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002516 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002517 }
2518 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 }
2520 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002521
2522 case llvm::BitstreamEntry::Record:
2523 // The interesting case.
2524 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 }
2526
2527 // Read and process a record.
2528 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002529 StringRef Blob;
2530 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 default: // Default behavior: ignore.
2532 break;
2533
2534 case TYPE_OFFSET: {
2535 if (F.LocalNumTypes != 0) {
2536 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002539 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 F.LocalNumTypes = Record[0];
2541 unsigned LocalBaseTypeIndex = Record[1];
2542 F.BaseTypeIndex = getTotalNumTypes();
2543
2544 if (F.LocalNumTypes > 0) {
2545 // Introduce the global -> local mapping for types within this module.
2546 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2547
2548 // Introduce the local -> global mapping for types within this module.
2549 F.TypeRemap.insertOrReplace(
2550 std::make_pair(LocalBaseTypeIndex,
2551 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002552
2553 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 }
2555 break;
2556 }
2557
2558 case DECL_OFFSET: {
2559 if (F.LocalNumDecls != 0) {
2560 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002561 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002563 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 F.LocalNumDecls = Record[0];
2565 unsigned LocalBaseDeclID = Record[1];
2566 F.BaseDeclID = getTotalNumDecls();
2567
2568 if (F.LocalNumDecls > 0) {
2569 // Introduce the global -> local mapping for declarations within this
2570 // module.
2571 GlobalDeclMap.insert(
2572 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2573
2574 // Introduce the local -> global mapping for declarations within this
2575 // module.
2576 F.DeclRemap.insertOrReplace(
2577 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2578
2579 // Introduce the global -> local mapping for declarations within this
2580 // module.
2581 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002582
Ben Langmuir52ca6782014-10-20 16:27:32 +00002583 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 break;
2586 }
2587
2588 case TU_UPDATE_LEXICAL: {
2589 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002590 LexicalContents Contents(
2591 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2592 Blob.data()),
2593 static_cast<unsigned int>(Blob.size() / 4));
2594 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 TU->setHasExternalLexicalStorage(true);
2596 break;
2597 }
2598
2599 case UPDATE_VISIBLE: {
2600 unsigned Idx = 0;
2601 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002602 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002603 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002604 // If we've already loaded the decl, perform the updates when we finish
2605 // loading this block.
2606 if (Decl *D = GetExistingDecl(ID))
2607 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 break;
2609 }
2610
2611 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002612 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002614 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2615 (const unsigned char *)F.IdentifierTableData + Record[0],
2616 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2617 (const unsigned char *)F.IdentifierTableData,
2618 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002619
2620 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2621 }
2622 break;
2623
2624 case IDENTIFIER_OFFSET: {
2625 if (F.LocalNumIdentifiers != 0) {
2626 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002627 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002629 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 F.LocalNumIdentifiers = Record[0];
2631 unsigned LocalBaseIdentifierID = Record[1];
2632 F.BaseIdentifierID = getTotalNumIdentifiers();
2633
2634 if (F.LocalNumIdentifiers > 0) {
2635 // Introduce the global -> local mapping for identifiers within this
2636 // module.
2637 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2638 &F));
2639
2640 // Introduce the local -> global mapping for identifiers within this
2641 // module.
2642 F.IdentifierRemap.insertOrReplace(
2643 std::make_pair(LocalBaseIdentifierID,
2644 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002645
Ben Langmuir52ca6782014-10-20 16:27:32 +00002646 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2647 + F.LocalNumIdentifiers);
2648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 break;
2650 }
2651
Richard Smith33e0f7e2015-07-22 02:08:40 +00002652 case INTERESTING_IDENTIFIERS:
2653 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2654 break;
2655
Ben Langmuir332aafe2014-01-31 01:06:56 +00002656 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002657 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2658 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002660 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 break;
2662
2663 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002664 if (SpecialTypes.empty()) {
2665 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2666 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2667 break;
2668 }
2669
2670 if (SpecialTypes.size() != Record.size()) {
2671 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002672 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002673 }
2674
2675 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2676 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2677 if (!SpecialTypes[I])
2678 SpecialTypes[I] = ID;
2679 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2680 // merge step?
2681 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 break;
2683
2684 case STATISTICS:
2685 TotalNumStatements += Record[0];
2686 TotalNumMacros += Record[1];
2687 TotalLexicalDeclContexts += Record[2];
2688 TotalVisibleDeclContexts += Record[3];
2689 break;
2690
2691 case UNUSED_FILESCOPED_DECLS:
2692 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2693 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2694 break;
2695
2696 case DELEGATING_CTORS:
2697 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2698 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2699 break;
2700
2701 case WEAK_UNDECLARED_IDENTIFIERS:
2702 if (Record.size() % 4 != 0) {
2703 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002704 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 }
2706
2707 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2708 // files. This isn't the way to do it :)
2709 WeakUndeclaredIdentifiers.clear();
2710
2711 // Translate the weak, undeclared identifiers into global IDs.
2712 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2713 WeakUndeclaredIdentifiers.push_back(
2714 getGlobalIdentifierID(F, Record[I++]));
2715 WeakUndeclaredIdentifiers.push_back(
2716 getGlobalIdentifierID(F, Record[I++]));
2717 WeakUndeclaredIdentifiers.push_back(
2718 ReadSourceLocation(F, Record, I).getRawEncoding());
2719 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2720 }
2721 break;
2722
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 F.LocalNumSelectors = Record[0];
2726 unsigned LocalBaseSelectorID = Record[1];
2727 F.BaseSelectorID = getTotalNumSelectors();
2728
2729 if (F.LocalNumSelectors > 0) {
2730 // Introduce the global -> local mapping for selectors within this
2731 // module.
2732 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2733
2734 // Introduce the local -> global mapping for selectors within this
2735 // module.
2736 F.SelectorRemap.insertOrReplace(
2737 std::make_pair(LocalBaseSelectorID,
2738 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002739
2740 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 }
2742 break;
2743 }
2744
2745 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002746 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 if (Record[0])
2748 F.SelectorLookupTable
2749 = ASTSelectorLookupTable::Create(
2750 F.SelectorLookupTableData + Record[0],
2751 F.SelectorLookupTableData,
2752 ASTSelectorLookupTrait(*this, F));
2753 TotalNumMethodPoolEntries += Record[1];
2754 break;
2755
2756 case REFERENCED_SELECTOR_POOL:
2757 if (!Record.empty()) {
2758 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2759 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2760 Record[Idx++]));
2761 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2762 getRawEncoding());
2763 }
2764 }
2765 break;
2766
2767 case PP_COUNTER_VALUE:
2768 if (!Record.empty() && Listener)
2769 Listener->ReadCounter(F, Record[0]);
2770 break;
2771
2772 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002773 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 F.NumFileSortedDecls = Record[0];
2775 break;
2776
2777 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002778 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 F.LocalNumSLocEntries = Record[0];
2780 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002781 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002782 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002784 if (!F.SLocEntryBaseID) {
2785 Error("ran out of source locations");
2786 break;
2787 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 // Make our entry in the range map. BaseID is negative and growing, so
2789 // we invert it. Because we invert it, though, we need the other end of
2790 // the range.
2791 unsigned RangeStart =
2792 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2793 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2794 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2795
2796 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2797 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2798 GlobalSLocOffsetMap.insert(
2799 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2800 - SLocSpaceSize,&F));
2801
2802 // Initialize the remapping table.
2803 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002804 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002806 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2808
2809 TotalNumSLocEntries += F.LocalNumSLocEntries;
2810 break;
2811 }
2812
2813 case MODULE_OFFSET_MAP: {
2814 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002815 const unsigned char *Data = (const unsigned char*)Blob.data();
2816 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002817
2818 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2819 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2820 F.SLocRemap.insert(std::make_pair(0U, 0));
2821 F.SLocRemap.insert(std::make_pair(2U, 1));
2822 }
2823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002825 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2826 RemapBuilder;
2827 RemapBuilder SLocRemap(F.SLocRemap);
2828 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2829 RemapBuilder MacroRemap(F.MacroRemap);
2830 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2831 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2832 RemapBuilder SelectorRemap(F.SelectorRemap);
2833 RemapBuilder DeclRemap(F.DeclRemap);
2834 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002835
Richard Smithd8879c82015-08-24 21:59:32 +00002836 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002837 using namespace llvm::support;
2838 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 StringRef Name = StringRef((const char*)Data, Len);
2840 Data += Len;
2841 ModuleFile *OM = ModuleMgr.lookup(Name);
2842 if (!OM) {
2843 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002844 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 }
2846
Justin Bogner57ba0b22014-03-28 22:03:24 +00002847 uint32_t SLocOffset =
2848 endian::readNext<uint32_t, little, unaligned>(Data);
2849 uint32_t IdentifierIDOffset =
2850 endian::readNext<uint32_t, little, unaligned>(Data);
2851 uint32_t MacroIDOffset =
2852 endian::readNext<uint32_t, little, unaligned>(Data);
2853 uint32_t PreprocessedEntityIDOffset =
2854 endian::readNext<uint32_t, little, unaligned>(Data);
2855 uint32_t SubmoduleIDOffset =
2856 endian::readNext<uint32_t, little, unaligned>(Data);
2857 uint32_t SelectorIDOffset =
2858 endian::readNext<uint32_t, little, unaligned>(Data);
2859 uint32_t DeclIDOffset =
2860 endian::readNext<uint32_t, little, unaligned>(Data);
2861 uint32_t TypeIndexOffset =
2862 endian::readNext<uint32_t, little, unaligned>(Data);
2863
Ben Langmuir785180e2014-10-20 16:27:30 +00002864 uint32_t None = std::numeric_limits<uint32_t>::max();
2865
2866 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2867 RemapBuilder &Remap) {
2868 if (Offset != None)
2869 Remap.insert(std::make_pair(Offset,
2870 static_cast<int>(BaseOffset - Offset)));
2871 };
2872 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2873 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2874 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2875 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2876 PreprocessedEntityRemap);
2877 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2878 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2879 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2880 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002881
2882 // Global -> local mappings.
2883 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2884 }
2885 break;
2886 }
2887
2888 case SOURCE_MANAGER_LINE_TABLE:
2889 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002890 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 break;
2892
2893 case SOURCE_LOCATION_PRELOADS: {
2894 // Need to transform from the local view (1-based IDs) to the global view,
2895 // which is based off F.SLocEntryBaseID.
2896 if (!F.PreloadSLocEntries.empty()) {
2897 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002898 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 }
2900
2901 F.PreloadSLocEntries.swap(Record);
2902 break;
2903 }
2904
2905 case EXT_VECTOR_DECLS:
2906 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2907 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2908 break;
2909
2910 case VTABLE_USES:
2911 if (Record.size() % 3 != 0) {
2912 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002913 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 }
2915
2916 // Later tables overwrite earlier ones.
2917 // FIXME: Modules will have some trouble with this. This is clearly not
2918 // the right way to do this.
2919 VTableUses.clear();
2920
2921 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2922 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2923 VTableUses.push_back(
2924 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2925 VTableUses.push_back(Record[Idx++]);
2926 }
2927 break;
2928
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 case PENDING_IMPLICIT_INSTANTIATIONS:
2930 if (PendingInstantiations.size() % 2 != 0) {
2931 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002932 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 }
2934
2935 if (Record.size() % 2 != 0) {
2936 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002937 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 }
2939
2940 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2941 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2942 PendingInstantiations.push_back(
2943 ReadSourceLocation(F, Record, I).getRawEncoding());
2944 }
2945 break;
2946
2947 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002948 if (Record.size() != 2) {
2949 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2953 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2954 break;
2955
2956 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002957 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2958 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2959 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002960
2961 unsigned LocalBasePreprocessedEntityID = Record[0];
2962
2963 unsigned StartingID;
2964 if (!PP.getPreprocessingRecord())
2965 PP.createPreprocessingRecord();
2966 if (!PP.getPreprocessingRecord()->getExternalSource())
2967 PP.getPreprocessingRecord()->SetExternalSource(*this);
2968 StartingID
2969 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002970 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 F.BasePreprocessedEntityID = StartingID;
2972
2973 if (F.NumPreprocessedEntities > 0) {
2974 // Introduce the global -> local mapping for preprocessed entities in
2975 // this module.
2976 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2977
2978 // Introduce the local -> global mapping for preprocessed entities in
2979 // this module.
2980 F.PreprocessedEntityRemap.insertOrReplace(
2981 std::make_pair(LocalBasePreprocessedEntityID,
2982 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2983 }
2984
2985 break;
2986 }
2987
2988 case DECL_UPDATE_OFFSETS: {
2989 if (Record.size() % 2 != 0) {
2990 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002991 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002993 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2994 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2995 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2996
2997 // If we've already loaded the decl, perform the updates when we finish
2998 // loading this block.
2999 if (Decl *D = GetExistingDecl(ID))
3000 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 break;
3003 }
3004
3005 case DECL_REPLACEMENTS: {
3006 if (Record.size() % 3 != 0) {
3007 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003008 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 }
3010 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3011 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3012 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3013 break;
3014 }
3015
3016 case OBJC_CATEGORIES_MAP: {
3017 if (F.LocalNumObjCCategoriesInMap != 0) {
3018 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 }
3021
3022 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003023 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 break;
3025 }
3026
3027 case OBJC_CATEGORIES:
3028 F.ObjCCategories.swap(Record);
3029 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003030
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 case CXX_BASE_SPECIFIER_OFFSETS: {
3032 if (F.LocalNumCXXBaseSpecifiers != 0) {
3033 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003034 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003038 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003039 break;
3040 }
3041
3042 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3043 if (F.LocalNumCXXCtorInitializers != 0) {
3044 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3045 return Failure;
3046 }
3047
3048 F.LocalNumCXXCtorInitializers = Record[0];
3049 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 break;
3051 }
3052
3053 case DIAG_PRAGMA_MAPPINGS:
3054 if (F.PragmaDiagMappings.empty())
3055 F.PragmaDiagMappings.swap(Record);
3056 else
3057 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3058 Record.begin(), Record.end());
3059 break;
3060
3061 case CUDA_SPECIAL_DECL_REFS:
3062 // Later tables overwrite earlier ones.
3063 // FIXME: Modules will have trouble with this.
3064 CUDASpecialDeclRefs.clear();
3065 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3066 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3067 break;
3068
3069 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003070 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 if (Record[0]) {
3073 F.HeaderFileInfoTable
3074 = HeaderFileInfoLookupTable::Create(
3075 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3076 (const unsigned char *)F.HeaderFileInfoTableData,
3077 HeaderFileInfoTrait(*this, F,
3078 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003079 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003080
3081 PP.getHeaderSearchInfo().SetExternalSource(this);
3082 if (!PP.getHeaderSearchInfo().getExternalLookup())
3083 PP.getHeaderSearchInfo().SetExternalLookup(this);
3084 }
3085 break;
3086 }
3087
3088 case FP_PRAGMA_OPTIONS:
3089 // Later tables overwrite earlier ones.
3090 FPPragmaOptions.swap(Record);
3091 break;
3092
3093 case OPENCL_EXTENSIONS:
3094 // Later tables overwrite earlier ones.
3095 OpenCLExtensions.swap(Record);
3096 break;
3097
3098 case TENTATIVE_DEFINITIONS:
3099 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3100 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3101 break;
3102
3103 case KNOWN_NAMESPACES:
3104 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3105 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3106 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003107
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003108 case UNDEFINED_BUT_USED:
3109 if (UndefinedButUsed.size() % 2 != 0) {
3110 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003111 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003112 }
3113
3114 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003115 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003116 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003117 }
3118 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003119 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3120 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003121 ReadSourceLocation(F, Record, I).getRawEncoding());
3122 }
3123 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003124 case DELETE_EXPRS_TO_ANALYZE:
3125 for (unsigned I = 0, N = Record.size(); I != N;) {
3126 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3127 const uint64_t Count = Record[I++];
3128 DelayedDeleteExprs.push_back(Count);
3129 for (uint64_t C = 0; C < Count; ++C) {
3130 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3131 bool IsArrayForm = Record[I++] == 1;
3132 DelayedDeleteExprs.push_back(IsArrayForm);
3133 }
3134 }
3135 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003138 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 // If we aren't loading a module (which has its own exports), make
3140 // all of the imported modules visible.
3141 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003142 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3143 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3144 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3145 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003146 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 }
3148 }
3149 break;
3150 }
3151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 case MACRO_OFFSET: {
3153 if (F.LocalNumMacros != 0) {
3154 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003155 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003157 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 F.LocalNumMacros = Record[0];
3159 unsigned LocalBaseMacroID = Record[1];
3160 F.BaseMacroID = getTotalNumMacros();
3161
3162 if (F.LocalNumMacros > 0) {
3163 // Introduce the global -> local mapping for macros within this module.
3164 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3165
3166 // Introduce the local -> global mapping for macros within this module.
3167 F.MacroRemap.insertOrReplace(
3168 std::make_pair(LocalBaseMacroID,
3169 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003170
3171 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 }
3173 break;
3174 }
3175
Richard Smithe40f2ba2013-08-07 21:41:30 +00003176 case LATE_PARSED_TEMPLATE: {
3177 LateParsedTemplates.append(Record.begin(), Record.end());
3178 break;
3179 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003180
3181 case OPTIMIZE_PRAGMA_OPTIONS:
3182 if (Record.size() != 1) {
3183 Error("invalid pragma optimize record");
3184 return Failure;
3185 }
3186 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3187 break;
Nico Weber72889432014-09-06 01:25:55 +00003188
3189 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3190 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3191 UnusedLocalTypedefNameCandidates.push_back(
3192 getGlobalDeclID(F, Record[I]));
3193 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 }
3195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003196}
3197
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003198ASTReader::ASTReadResult
3199ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3200 const ModuleFile *ImportedBy,
3201 unsigned ClientLoadCapabilities) {
3202 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003203 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003204
Richard Smithe842a472014-10-22 02:05:46 +00003205 if (F.Kind == MK_ExplicitModule) {
3206 // For an explicitly-loaded module, we don't care whether the original
3207 // module map file exists or matches.
3208 return Success;
3209 }
3210
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003211 // Try to resolve ModuleName in the current header search context and
3212 // verify that it is found in the same module map file as we saved. If the
3213 // top-level AST file is a main file, skip this check because there is no
3214 // usable header search context.
3215 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003216 "MODULE_NAME should come before MODULE_MAP_FILE");
3217 if (F.Kind == MK_ImplicitModule &&
3218 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3219 // An implicitly-loaded module file should have its module listed in some
3220 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003221 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003222 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3223 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3224 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003225 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003226 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3227 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3228 // This module was defined by an imported (explicit) module.
3229 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3230 << ASTFE->getName();
3231 else
3232 // This module was built with a different module map.
3233 Diag(diag::err_imported_module_not_found)
3234 << F.ModuleName << F.FileName << ImportedBy->FileName
3235 << F.ModuleMapPath;
3236 }
3237 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003238 }
3239
Richard Smithe842a472014-10-22 02:05:46 +00003240 assert(M->Name == F.ModuleName && "found module with different name");
3241
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003242 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003243 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003244 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3245 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003246 assert(ImportedBy && "top-level import should be verified");
3247 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3248 Diag(diag::err_imported_module_modmap_changed)
3249 << F.ModuleName << ImportedBy->FileName
3250 << ModMap->getName() << F.ModuleMapPath;
3251 return OutOfDate;
3252 }
3253
3254 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3255 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3256 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003257 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003258 const FileEntry *F =
3259 FileMgr.getFile(Filename, false, false);
3260 if (F == nullptr) {
3261 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3262 Error("could not find file '" + Filename +"' referenced by AST file");
3263 return OutOfDate;
3264 }
3265 AdditionalStoredMaps.insert(F);
3266 }
3267
3268 // Check any additional module map files (e.g. module.private.modulemap)
3269 // that are not in the pcm.
3270 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3271 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3272 // Remove files that match
3273 // Note: SmallPtrSet::erase is really remove
3274 if (!AdditionalStoredMaps.erase(ModMap)) {
3275 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3276 Diag(diag::err_module_different_modmap)
3277 << F.ModuleName << /*new*/0 << ModMap->getName();
3278 return OutOfDate;
3279 }
3280 }
3281 }
3282
3283 // Check any additional module map files that are in the pcm, but not
3284 // found in header search. Cases that match are already removed.
3285 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3286 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3287 Diag(diag::err_module_different_modmap)
3288 << F.ModuleName << /*not new*/1 << ModMap->getName();
3289 return OutOfDate;
3290 }
3291 }
3292
3293 if (Listener)
3294 Listener->ReadModuleMapFile(F.ModuleMapPath);
3295 return Success;
3296}
3297
3298
Douglas Gregorc1489562013-02-12 23:36:21 +00003299/// \brief Move the given method to the back of the global list of methods.
3300static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3301 // Find the entry for this selector in the method pool.
3302 Sema::GlobalMethodPool::iterator Known
3303 = S.MethodPool.find(Method->getSelector());
3304 if (Known == S.MethodPool.end())
3305 return;
3306
3307 // Retrieve the appropriate method list.
3308 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3309 : Known->second.second;
3310 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003311 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003312 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003313 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003314 Found = true;
3315 } else {
3316 // Keep searching.
3317 continue;
3318 }
3319 }
3320
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003321 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003322 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003323 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003324 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003325 }
3326}
3327
Richard Smithde711422015-04-23 21:20:19 +00003328void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003329 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003330 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003331 bool wasHidden = D->Hidden;
3332 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003333
Richard Smith49f906a2014-03-01 00:08:04 +00003334 if (wasHidden && SemaObj) {
3335 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3336 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 }
3339 }
3340}
3341
Richard Smith49f906a2014-03-01 00:08:04 +00003342void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003343 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003344 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003346 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003347 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003348 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003349 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003350
3351 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003352 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 // there is nothing more to do.
3354 continue;
3355 }
Richard Smith49f906a2014-03-01 00:08:04 +00003356
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 if (!Mod->isAvailable()) {
3358 // Modules that aren't available cannot be made visible.
3359 continue;
3360 }
3361
3362 // Update the module's name visibility.
3363 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 // If we've already deserialized any names from this module,
3366 // mark them as visible.
3367 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3368 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003369 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003370 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003371 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003372 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3373 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003375
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003377 SmallVector<Module *, 16> Exports;
3378 Mod->getExportedModules(Exports);
3379 for (SmallVectorImpl<Module *>::iterator
3380 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3381 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003382 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003383 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 }
3385 }
3386}
3387
Douglas Gregore060e572013-01-25 01:03:03 +00003388bool ASTReader::loadGlobalIndex() {
3389 if (GlobalIndex)
3390 return false;
3391
3392 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3393 !Context.getLangOpts().Modules)
3394 return true;
3395
3396 // Try to load the global index.
3397 TriedLoadingGlobalIndex = true;
3398 StringRef ModuleCachePath
3399 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3400 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003401 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003402 if (!Result.first)
3403 return true;
3404
3405 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003406 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003407 return false;
3408}
3409
3410bool ASTReader::isGlobalIndexUnavailable() const {
3411 return Context.getLangOpts().Modules && UseGlobalIndex &&
3412 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3413}
3414
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003415static void updateModuleTimestamp(ModuleFile &MF) {
3416 // Overwrite the timestamp file contents so that file's mtime changes.
3417 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003418 std::error_code EC;
3419 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3420 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003421 return;
3422 OS << "Timestamp file\n";
3423}
3424
Guy Benyei11169dd2012-12-18 14:30:41 +00003425ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3426 ModuleKind Type,
3427 SourceLocation ImportLoc,
3428 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003429 llvm::SaveAndRestore<SourceLocation>
3430 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3431
Richard Smithd1c46742014-04-30 02:24:17 +00003432 // Defer any pending actions until we get to the end of reading the AST file.
3433 Deserializing AnASTFile(this);
3434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003436 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003437
3438 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003439 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003441 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003442 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 ClientLoadCapabilities)) {
3444 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003445 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 case OutOfDate:
3447 case VersionMismatch:
3448 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003449 case HadErrors: {
3450 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3451 for (const ImportedModule &IM : Loaded)
3452 LoadedSet.insert(IM.Mod);
3453
Douglas Gregor7029ce12013-03-19 00:28:20 +00003454 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003455 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003456 Context.getLangOpts().Modules
3457 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003458 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003459
3460 // If we find that any modules are unusable, the global index is going
3461 // to be out-of-date. Just remove it.
3462 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003463 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003465 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 case Success:
3467 break;
3468 }
3469
3470 // Here comes stuff that we only do once the entire chain is loaded.
3471
3472 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003473 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3474 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 M != MEnd; ++M) {
3476 ModuleFile &F = *M->Mod;
3477
3478 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003479 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3480 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003481
3482 // Once read, set the ModuleFile bit base offset and update the size in
3483 // bits of all files we've seen.
3484 F.GlobalBitOffset = TotalModulesSizeInBits;
3485 TotalModulesSizeInBits += F.SizeInBits;
3486 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3487
3488 // Preload SLocEntries.
3489 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3490 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3491 // Load it through the SourceManager and don't call ReadSLocEntry()
3492 // directly because the entry may have already been loaded in which case
3493 // calling ReadSLocEntry() directly would trigger an assertion in
3494 // SourceManager.
3495 SourceMgr.getLoadedSLocEntryByID(Index);
3496 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003497
3498 // Preload all the pending interesting identifiers by marking them out of
3499 // date.
3500 for (auto Offset : F.PreloadIdentifierOffsets) {
3501 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3502 F.IdentifierTableData + Offset);
3503
3504 ASTIdentifierLookupTrait Trait(*this, F);
3505 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3506 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003507 auto &II = PP.getIdentifierTable().getOwn(Key);
3508 II.setOutOfDate(true);
3509
3510 // Mark this identifier as being from an AST file so that we can track
3511 // whether we need to serialize it.
3512 if (!II.isFromAST()) {
3513 II.setIsFromAST();
3514 if (isInterestingIdentifier(*this, II, F.isModule()))
3515 II.setChangedSinceDeserialization();
3516 }
3517
3518 // Associate the ID with the identifier so that the writer can reuse it.
3519 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3520 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003521 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 }
3523
Douglas Gregor603cd862013-03-22 18:50:14 +00003524 // Setup the import locations and notify the module manager that we've
3525 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003526 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3527 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 M != MEnd; ++M) {
3529 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003530
3531 ModuleMgr.moduleFileAccepted(&F);
3532
3533 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003534 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 if (!M->ImportedBy)
3536 F.ImportLoc = M->ImportLoc;
3537 else
3538 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3539 M->ImportLoc.getRawEncoding());
3540 }
3541
Richard Smith33e0f7e2015-07-22 02:08:40 +00003542 if (!Context.getLangOpts().CPlusPlus ||
3543 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3544 // Mark all of the identifiers in the identifier table as being out of date,
3545 // so that various accessors know to check the loaded modules when the
3546 // identifier is used.
3547 //
3548 // For C++ modules, we don't need information on many identifiers (just
3549 // those that provide macros or are poisoned), so we mark all of
3550 // the interesting ones via PreloadIdentifierOffsets.
3551 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3552 IdEnd = PP.getIdentifierTable().end();
3553 Id != IdEnd; ++Id)
3554 Id->second->setOutOfDate(true);
3555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003556
3557 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003558 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3559 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3561 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003562
3563 switch (Unresolved.Kind) {
3564 case UnresolvedModuleRef::Conflict:
3565 if (ResolvedMod) {
3566 Module::Conflict Conflict;
3567 Conflict.Other = ResolvedMod;
3568 Conflict.Message = Unresolved.String.str();
3569 Unresolved.Mod->Conflicts.push_back(Conflict);
3570 }
3571 continue;
3572
3573 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003575 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003577
Douglas Gregorfb912652013-03-20 21:10:35 +00003578 case UnresolvedModuleRef::Export:
3579 if (ResolvedMod || Unresolved.IsWildcard)
3580 Unresolved.Mod->Exports.push_back(
3581 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3582 continue;
3583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003584 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003585 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003586
3587 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3588 // Might be unnecessary as use declarations are only used to build the
3589 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003590
3591 InitializeContext();
3592
Richard Smith3d8e97e2013-10-18 06:54:39 +00003593 if (SemaObj)
3594 UpdateSema();
3595
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 if (DeserializationListener)
3597 DeserializationListener->ReaderInitialized(this);
3598
3599 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003600 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 PrimaryModule.OriginalSourceFileID
3602 = FileID::get(PrimaryModule.SLocEntryBaseID
3603 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3604
3605 // If this AST file is a precompiled preamble, then set the
3606 // preamble file ID of the source manager to the file source file
3607 // from which the preamble was built.
3608 if (Type == MK_Preamble) {
3609 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3610 } else if (Type == MK_MainFile) {
3611 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3612 }
3613 }
3614
3615 // For any Objective-C class definitions we have already loaded, make sure
3616 // that we load any additional categories.
3617 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3618 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3619 ObjCClassesLoaded[I],
3620 PreviousGeneration);
3621 }
Douglas Gregore060e572013-01-25 01:03:03 +00003622
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003623 if (PP.getHeaderSearchInfo()
3624 .getHeaderSearchOpts()
3625 .ModulesValidateOncePerBuildSession) {
3626 // Now we are certain that the module and all modules it depends on are
3627 // up to date. Create or update timestamp files for modules that are
3628 // located in the module cache (not for PCH files that could be anywhere
3629 // in the filesystem).
3630 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3631 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003632 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003633 updateModuleTimestamp(*M.Mod);
3634 }
3635 }
3636 }
3637
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 return Success;
3639}
3640
Ben Langmuir487ea142014-10-23 18:05:36 +00003641static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3642
Ben Langmuir70a1b812015-03-24 04:43:52 +00003643/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3644static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3645 return Stream.Read(8) == 'C' &&
3646 Stream.Read(8) == 'P' &&
3647 Stream.Read(8) == 'C' &&
3648 Stream.Read(8) == 'H';
3649}
3650
Richard Smith0f99d6a2015-08-09 08:48:41 +00003651static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3652 switch (Kind) {
3653 case MK_PCH:
3654 return 0; // PCH
3655 case MK_ImplicitModule:
3656 case MK_ExplicitModule:
3657 return 1; // module
3658 case MK_MainFile:
3659 case MK_Preamble:
3660 return 2; // main source file
3661 }
3662 llvm_unreachable("unknown module kind");
3663}
3664
Guy Benyei11169dd2012-12-18 14:30:41 +00003665ASTReader::ASTReadResult
3666ASTReader::ReadASTCore(StringRef FileName,
3667 ModuleKind Type,
3668 SourceLocation ImportLoc,
3669 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003670 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003671 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003672 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 unsigned ClientLoadCapabilities) {
3674 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003676 ModuleManager::AddModuleResult AddResult
3677 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003678 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003679 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003680 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003681
Douglas Gregor7029ce12013-03-19 00:28:20 +00003682 switch (AddResult) {
3683 case ModuleManager::AlreadyLoaded:
3684 return Success;
3685
3686 case ModuleManager::NewlyLoaded:
3687 // Load module file below.
3688 break;
3689
3690 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003691 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003692 // it.
3693 if (ClientLoadCapabilities & ARR_Missing)
3694 return Missing;
3695
3696 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003697 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3698 << FileName << ErrorStr.empty()
3699 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003700 return Failure;
3701
3702 case ModuleManager::OutOfDate:
3703 // We couldn't load the module file because it is out-of-date. If the
3704 // client can handle out-of-date, return it.
3705 if (ClientLoadCapabilities & ARR_OutOfDate)
3706 return OutOfDate;
3707
3708 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003709 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3710 << FileName << ErrorStr.empty()
3711 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 return Failure;
3713 }
3714
Douglas Gregor7029ce12013-03-19 00:28:20 +00003715 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003716
3717 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3718 // module?
3719 if (FileName != "-") {
3720 CurrentDir = llvm::sys::path::parent_path(FileName);
3721 if (CurrentDir.empty()) CurrentDir = ".";
3722 }
3723
3724 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003725 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003726 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003727 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003728 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3729
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003731 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003732 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3733 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003734 return Failure;
3735 }
3736
3737 // This is used for compatibility with older PCH formats.
3738 bool HaveReadControlBlock = false;
3739
Chris Lattnerefa77172013-01-20 00:00:22 +00003740 while (1) {
3741 llvm::BitstreamEntry Entry = Stream.advance();
3742
3743 switch (Entry.Kind) {
3744 case llvm::BitstreamEntry::Error:
3745 case llvm::BitstreamEntry::EndBlock:
3746 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 Error("invalid record at top-level of AST file");
3748 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003749
3750 case llvm::BitstreamEntry::SubBlock:
3751 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 }
3753
Chris Lattnerefa77172013-01-20 00:00:22 +00003754 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 case CONTROL_BLOCK_ID:
3756 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003757 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003759 // Check that we didn't try to load a non-module AST file as a module.
3760 //
3761 // FIXME: Should we also perform the converse check? Loading a module as
3762 // a PCH file sort of works, but it's a bit wonky.
3763 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3764 F.ModuleName.empty()) {
3765 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3766 if (Result != OutOfDate ||
3767 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3768 Diag(diag::err_module_file_not_module) << FileName;
3769 return Result;
3770 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 break;
3772
3773 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003774 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 case OutOfDate: return OutOfDate;
3776 case VersionMismatch: return VersionMismatch;
3777 case ConfigurationMismatch: return ConfigurationMismatch;
3778 case HadErrors: return HadErrors;
3779 }
3780 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003781
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 case AST_BLOCK_ID:
3783 if (!HaveReadControlBlock) {
3784 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003785 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 return VersionMismatch;
3787 }
3788
3789 // Record that we've loaded this module.
3790 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3791 return Success;
3792
3793 default:
3794 if (Stream.SkipBlock()) {
3795 Error("malformed block record in AST file");
3796 return Failure;
3797 }
3798 break;
3799 }
3800 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003801}
3802
Richard Smitha7e2cc62015-05-01 01:53:09 +00003803void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 // If there's a listener, notify them that we "read" the translation unit.
3805 if (DeserializationListener)
3806 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3807 Context.getTranslationUnitDecl());
3808
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 // FIXME: Find a better way to deal with collisions between these
3810 // built-in types. Right now, we just ignore the problem.
3811
3812 // Load the special types.
3813 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3814 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3815 if (!Context.CFConstantStringTypeDecl)
3816 Context.setCFConstantStringType(GetType(String));
3817 }
3818
3819 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3820 QualType FileType = GetType(File);
3821 if (FileType.isNull()) {
3822 Error("FILE type is NULL");
3823 return;
3824 }
3825
3826 if (!Context.FILEDecl) {
3827 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3828 Context.setFILEDecl(Typedef->getDecl());
3829 else {
3830 const TagType *Tag = FileType->getAs<TagType>();
3831 if (!Tag) {
3832 Error("Invalid FILE type in AST file");
3833 return;
3834 }
3835 Context.setFILEDecl(Tag->getDecl());
3836 }
3837 }
3838 }
3839
3840 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3841 QualType Jmp_bufType = GetType(Jmp_buf);
3842 if (Jmp_bufType.isNull()) {
3843 Error("jmp_buf type is NULL");
3844 return;
3845 }
3846
3847 if (!Context.jmp_bufDecl) {
3848 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3849 Context.setjmp_bufDecl(Typedef->getDecl());
3850 else {
3851 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3852 if (!Tag) {
3853 Error("Invalid jmp_buf type in AST file");
3854 return;
3855 }
3856 Context.setjmp_bufDecl(Tag->getDecl());
3857 }
3858 }
3859 }
3860
3861 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3862 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3863 if (Sigjmp_bufType.isNull()) {
3864 Error("sigjmp_buf type is NULL");
3865 return;
3866 }
3867
3868 if (!Context.sigjmp_bufDecl) {
3869 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3870 Context.setsigjmp_bufDecl(Typedef->getDecl());
3871 else {
3872 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3873 assert(Tag && "Invalid sigjmp_buf type in AST file");
3874 Context.setsigjmp_bufDecl(Tag->getDecl());
3875 }
3876 }
3877 }
3878
3879 if (unsigned ObjCIdRedef
3880 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3881 if (Context.ObjCIdRedefinitionType.isNull())
3882 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3883 }
3884
3885 if (unsigned ObjCClassRedef
3886 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3887 if (Context.ObjCClassRedefinitionType.isNull())
3888 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3889 }
3890
3891 if (unsigned ObjCSelRedef
3892 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3893 if (Context.ObjCSelRedefinitionType.isNull())
3894 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3895 }
3896
3897 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3898 QualType Ucontext_tType = GetType(Ucontext_t);
3899 if (Ucontext_tType.isNull()) {
3900 Error("ucontext_t type is NULL");
3901 return;
3902 }
3903
3904 if (!Context.ucontext_tDecl) {
3905 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3906 Context.setucontext_tDecl(Typedef->getDecl());
3907 else {
3908 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3909 assert(Tag && "Invalid ucontext_t type in AST file");
3910 Context.setucontext_tDecl(Tag->getDecl());
3911 }
3912 }
3913 }
3914 }
3915
3916 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3917
3918 // If there were any CUDA special declarations, deserialize them.
3919 if (!CUDASpecialDeclRefs.empty()) {
3920 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3921 Context.setcudaConfigureCallDecl(
3922 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3923 }
Richard Smith56be7542014-03-21 00:33:59 +00003924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003926 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003927 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003928 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003929 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003930 /*ImportLoc=*/Import.ImportLoc);
3931 PP.makeModuleVisible(Imported, Import.ImportLoc);
3932 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 }
3934 ImportedModules.clear();
3935}
3936
3937void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003938 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003939}
3940
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003941/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3942/// cursor into the start of the given block ID, returning false on success and
3943/// true on failure.
3944static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003945 while (1) {
3946 llvm::BitstreamEntry Entry = Cursor.advance();
3947 switch (Entry.Kind) {
3948 case llvm::BitstreamEntry::Error:
3949 case llvm::BitstreamEntry::EndBlock:
3950 return true;
3951
3952 case llvm::BitstreamEntry::Record:
3953 // Ignore top-level records.
3954 Cursor.skipRecord(Entry.ID);
3955 break;
3956
3957 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003958 if (Entry.ID == BlockID) {
3959 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003960 return true;
3961 // Found it!
3962 return false;
3963 }
3964
3965 if (Cursor.SkipBlock())
3966 return true;
3967 }
3968 }
3969}
3970
Ben Langmuir70a1b812015-03-24 04:43:52 +00003971/// \brief Reads and return the signature record from \p StreamFile's control
3972/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003973static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3974 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003975 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003976 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003977
3978 // Scan for the CONTROL_BLOCK_ID block.
3979 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3980 return 0;
3981
3982 // Scan for SIGNATURE inside the control block.
3983 ASTReader::RecordData Record;
3984 while (1) {
3985 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3986 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3987 Entry.Kind != llvm::BitstreamEntry::Record)
3988 return 0;
3989
3990 Record.clear();
3991 StringRef Blob;
3992 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3993 return Record[0];
3994 }
3995}
3996
Guy Benyei11169dd2012-12-18 14:30:41 +00003997/// \brief Retrieve the name of the original source file name
3998/// directly from the AST file, without actually loading the AST
3999/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004000std::string ASTReader::getOriginalSourceFile(
4001 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004002 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004004 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004006 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4007 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 return std::string();
4009 }
4010
4011 // Initialize the stream
4012 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004013 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004014 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004015
4016 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004017 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4019 return std::string();
4020 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004021
Chris Lattnere7b154b2013-01-19 21:39:22 +00004022 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004023 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004024 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4025 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004026 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004027
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004028 // Scan for ORIGINAL_FILE inside the control block.
4029 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004030 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004031 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004032 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4033 return std::string();
4034
4035 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4036 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4037 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004039
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004041 StringRef Blob;
4042 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4043 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004045}
4046
4047namespace {
4048 class SimplePCHValidator : public ASTReaderListener {
4049 const LangOptions &ExistingLangOpts;
4050 const TargetOptions &ExistingTargetOpts;
4051 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004052 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004054
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 public:
4056 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4057 const TargetOptions &ExistingTargetOpts,
4058 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004059 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 FileManager &FileMgr)
4061 : ExistingLangOpts(ExistingLangOpts),
4062 ExistingTargetOpts(ExistingTargetOpts),
4063 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004064 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 FileMgr(FileMgr)
4066 {
4067 }
4068
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004069 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4070 bool AllowCompatibleDifferences) override {
4071 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4072 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004073 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004074 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4075 bool AllowCompatibleDifferences) override {
4076 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4077 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004079 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4080 StringRef SpecificModuleCachePath,
4081 bool Complain) override {
4082 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4083 ExistingModuleCachePath,
4084 nullptr, ExistingLangOpts);
4085 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004086 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4087 bool Complain,
4088 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004089 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004090 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004091 }
4092 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004093}
Guy Benyei11169dd2012-12-18 14:30:41 +00004094
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004095bool ASTReader::readASTFileControlBlock(
4096 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004097 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004098 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004100 // FIXME: This allows use of the VFS; we do not allow use of the
4101 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004102 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004103 if (!Buffer) {
4104 return true;
4105 }
4106
4107 // Initialize the stream
4108 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004109 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004110 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004111
4112 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004113 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004116 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004117 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004119
4120 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004121 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004122 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004123 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004126 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004127 while (1) {
Richard Smith0516b182015-09-08 19:40:14 +00004128 llvm::BitstreamEntry Entry = Stream.advance();
4129
4130 switch (Entry.Kind) {
4131 case llvm::BitstreamEntry::SubBlock: {
4132 switch (Entry.ID) {
4133 case OPTIONS_BLOCK_ID: {
4134 std::string IgnoredSuggestedPredefines;
4135 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4136 /*AllowCompatibleConfigurationMismatch*/ false,
4137 Listener, IgnoredSuggestedPredefines) != Success)
4138 return true;
4139 break;
4140 }
4141
4142 case INPUT_FILES_BLOCK_ID:
4143 InputFilesCursor = Stream;
4144 if (Stream.SkipBlock() ||
4145 (NeedsInputFiles &&
4146 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4147 return true;
4148 break;
4149
4150 default:
4151 if (Stream.SkipBlock())
4152 return true;
4153 break;
4154 }
4155
4156 continue;
4157 }
4158
4159 case llvm::BitstreamEntry::EndBlock:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004160 return false;
Richard Smith0516b182015-09-08 19:40:14 +00004161
4162 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004163 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004164
4165 case llvm::BitstreamEntry::Record:
4166 break;
4167 }
4168
Guy Benyei11169dd2012-12-18 14:30:41 +00004169 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004170 StringRef Blob;
4171 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004172 switch ((ControlRecordTypes)RecCode) {
4173 case METADATA: {
4174 if (Record[0] != VERSION_MAJOR)
4175 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004177 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004178 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004180 break;
4181 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004182 case MODULE_NAME:
4183 Listener.ReadModuleName(Blob);
4184 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004185 case MODULE_DIRECTORY:
4186 ModuleDir = Blob;
4187 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004188 case MODULE_MAP_FILE: {
4189 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004190 auto Path = ReadString(Record, Idx);
4191 ResolveImportedPath(Path, ModuleDir);
4192 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004193 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004194 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004195 case INPUT_FILE_OFFSETS: {
4196 if (!NeedsInputFiles)
4197 break;
4198
4199 unsigned NumInputFiles = Record[0];
4200 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004201 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004202 for (unsigned I = 0; I != NumInputFiles; ++I) {
4203 // Go find this input file.
4204 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004205
4206 if (isSystemFile && !NeedsSystemInputFiles)
4207 break; // the rest are system input files
4208
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004209 BitstreamCursor &Cursor = InputFilesCursor;
4210 SavedStreamPosition SavedPosition(Cursor);
4211 Cursor.JumpToBit(InputFileOffs[I]);
4212
4213 unsigned Code = Cursor.ReadCode();
4214 RecordData Record;
4215 StringRef Blob;
4216 bool shouldContinue = false;
4217 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4218 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004219 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004220 std::string Filename = Blob;
4221 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004222 shouldContinue = Listener.visitInputFile(
4223 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004224 break;
4225 }
4226 if (!shouldContinue)
4227 break;
4228 }
4229 break;
4230 }
4231
Richard Smithd4b230b2014-10-27 23:01:16 +00004232 case IMPORTS: {
4233 if (!NeedsImports)
4234 break;
4235
4236 unsigned Idx = 0, N = Record.size();
4237 while (Idx < N) {
4238 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004239 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004240 std::string Filename = ReadString(Record, Idx);
4241 ResolveImportedPath(Filename, ModuleDir);
4242 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004243 }
4244 break;
4245 }
4246
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004247 default:
4248 // No other validation to perform.
4249 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
4251 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004252}
4253
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004254bool ASTReader::isAcceptableASTFile(
4255 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004256 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004257 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4258 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004259 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4260 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004261 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004262 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004263}
4264
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265ASTReader::ASTReadResult
4266ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 // Enter the submodule block.
4268 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4269 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004270 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
4272
4273 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4274 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004275 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 RecordData Record;
4277 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4279
4280 switch (Entry.Kind) {
4281 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4282 case llvm::BitstreamEntry::Error:
4283 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004284 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004285 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004286 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004287 case llvm::BitstreamEntry::Record:
4288 // The interesting case.
4289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004293 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004295 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4296
4297 if ((Kind == SUBMODULE_METADATA) != First) {
4298 Error("submodule metadata record should be at beginning of block");
4299 return Failure;
4300 }
4301 First = false;
4302
4303 // Submodule information is only valid if we have a current module.
4304 // FIXME: Should we error on these cases?
4305 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4306 Kind != SUBMODULE_DEFINITION)
4307 continue;
4308
4309 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 default: // Default behavior: ignore.
4311 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004312
Richard Smith03478d92014-10-23 22:12:14 +00004313 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004314 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004316 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 }
Richard Smith03478d92014-10-23 22:12:14 +00004318
Chris Lattner0e6c9402013-01-20 02:38:54 +00004319 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004320 unsigned Idx = 0;
4321 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4322 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4323 bool IsFramework = Record[Idx++];
4324 bool IsExplicit = Record[Idx++];
4325 bool IsSystem = Record[Idx++];
4326 bool IsExternC = Record[Idx++];
4327 bool InferSubmodules = Record[Idx++];
4328 bool InferExplicitSubmodules = Record[Idx++];
4329 bool InferExportWildcard = Record[Idx++];
4330 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004331
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004332 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004333 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004335
Guy Benyei11169dd2012-12-18 14:30:41 +00004336 // Retrieve this (sub)module from the module map, creating it if
4337 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004338 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004340
4341 // FIXME: set the definition loc for CurrentModule, or call
4342 // ModMap.setInferredModuleAllowedBy()
4343
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4345 if (GlobalIndex >= SubmodulesLoaded.size() ||
4346 SubmodulesLoaded[GlobalIndex]) {
4347 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004348 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004350
Douglas Gregor7029ce12013-03-19 00:28:20 +00004351 if (!ParentModule) {
4352 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4353 if (CurFile != F.File) {
4354 if (!Diags.isDiagnosticInFlight()) {
4355 Diag(diag::err_module_file_conflict)
4356 << CurrentModule->getTopLevelModuleName()
4357 << CurFile->getName()
4358 << F.File->getName();
4359 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004360 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004361 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004362 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004363
4364 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004365 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004366
Adrian Prantl15bcf702015-06-30 17:39:43 +00004367 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 CurrentModule->IsFromModuleFile = true;
4369 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004370 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 CurrentModule->InferSubmodules = InferSubmodules;
4372 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4373 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004374 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 if (DeserializationListener)
4376 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4377
4378 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004379
Douglas Gregorfb912652013-03-20 21:10:35 +00004380 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004381 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004382 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004383 CurrentModule->UnresolvedConflicts.clear();
4384 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 break;
4386 }
4387
4388 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004389 std::string Filename = Blob;
4390 ResolveImportedPath(F, Filename);
4391 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004393 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4394 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004395 // This can be a spurious difference caused by changing the VFS to
4396 // point to a different copy of the file, and it is too late to
4397 // to rebuild safely.
4398 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4399 // after input file validation only real problems would remain and we
4400 // could just error. For now, assume it's okay.
4401 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 }
4403 }
4404 break;
4405 }
4406
Richard Smith202210b2014-10-24 20:23:01 +00004407 case SUBMODULE_HEADER:
4408 case SUBMODULE_EXCLUDED_HEADER:
4409 case SUBMODULE_PRIVATE_HEADER:
4410 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004411 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4412 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004413 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004414
Richard Smith202210b2014-10-24 20:23:01 +00004415 case SUBMODULE_TEXTUAL_HEADER:
4416 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4417 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4418 // them here.
4419 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004420
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004422 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 break;
4424 }
4425
4426 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004427 std::string Dirname = Blob;
4428 ResolveImportedPath(F, Dirname);
4429 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004431 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4432 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004433 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4434 Error("mismatched umbrella directories in submodule");
4435 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 }
4437 }
4438 break;
4439 }
4440
4441 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 F.BaseSubmoduleID = getTotalNumSubmodules();
4443 F.LocalNumSubmodules = Record[0];
4444 unsigned LocalBaseSubmoduleID = Record[1];
4445 if (F.LocalNumSubmodules > 0) {
4446 // Introduce the global -> local mapping for submodules within this
4447 // module.
4448 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4449
4450 // Introduce the local -> global mapping for submodules within this
4451 // module.
4452 F.SubmoduleRemap.insertOrReplace(
4453 std::make_pair(LocalBaseSubmoduleID,
4454 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004455
Ben Langmuir52ca6782014-10-20 16:27:32 +00004456 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4457 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 break;
4459 }
4460
4461 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004463 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 Unresolved.File = &F;
4465 Unresolved.Mod = CurrentModule;
4466 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004467 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004469 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 }
4471 break;
4472 }
4473
4474 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004476 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 Unresolved.File = &F;
4478 Unresolved.Mod = CurrentModule;
4479 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004480 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004482 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 }
4484
4485 // Once we've loaded the set of exports, there's no reason to keep
4486 // the parsed, unresolved exports around.
4487 CurrentModule->UnresolvedExports.clear();
4488 break;
4489 }
4490 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004491 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 Context.getTargetInfo());
4493 break;
4494 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004495
4496 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004497 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004498 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004499 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004500
4501 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004502 CurrentModule->ConfigMacros.push_back(Blob.str());
4503 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004504
4505 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004506 UnresolvedModuleRef Unresolved;
4507 Unresolved.File = &F;
4508 Unresolved.Mod = CurrentModule;
4509 Unresolved.ID = Record[0];
4510 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4511 Unresolved.IsWildcard = false;
4512 Unresolved.String = Blob;
4513 UnresolvedModuleRefs.push_back(Unresolved);
4514 break;
4515 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 }
4517 }
4518}
4519
4520/// \brief Parse the record that corresponds to a LangOptions data
4521/// structure.
4522///
4523/// This routine parses the language options from the AST file and then gives
4524/// them to the AST listener if one is set.
4525///
4526/// \returns true if the listener deems the file unacceptable, false otherwise.
4527bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4528 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004529 ASTReaderListener &Listener,
4530 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 LangOptions LangOpts;
4532 unsigned Idx = 0;
4533#define LANGOPT(Name, Bits, Default, Description) \
4534 LangOpts.Name = Record[Idx++];
4535#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4536 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4537#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004538#define SANITIZER(NAME, ID) \
4539 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004540#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004541
Ben Langmuircd98cb72015-06-23 18:20:18 +00004542 for (unsigned N = Record[Idx++]; N; --N)
4543 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4544
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4546 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4547 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004548
Ben Langmuird4a667a2015-06-23 18:20:23 +00004549 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004550
4551 // Comment options.
4552 for (unsigned N = Record[Idx++]; N; --N) {
4553 LangOpts.CommentOpts.BlockCommandNames.push_back(
4554 ReadString(Record, Idx));
4555 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004556 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004557
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004558 return Listener.ReadLanguageOptions(LangOpts, Complain,
4559 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560}
4561
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004562bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4563 ASTReaderListener &Listener,
4564 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 unsigned Idx = 0;
4566 TargetOptions TargetOpts;
4567 TargetOpts.Triple = ReadString(Record, Idx);
4568 TargetOpts.CPU = ReadString(Record, Idx);
4569 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 for (unsigned N = Record[Idx++]; N; --N) {
4571 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4572 }
4573 for (unsigned N = Record[Idx++]; N; --N) {
4574 TargetOpts.Features.push_back(ReadString(Record, Idx));
4575 }
4576
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004577 return Listener.ReadTargetOptions(TargetOpts, Complain,
4578 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004579}
4580
4581bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4582 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004583 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004585#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004586#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004587 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004588#include "clang/Basic/DiagnosticOptions.def"
4589
Richard Smith3be1cb22014-08-07 00:24:21 +00004590 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004591 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004592 for (unsigned N = Record[Idx++]; N; --N)
4593 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
4595 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4596}
4597
4598bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4599 ASTReaderListener &Listener) {
4600 FileSystemOptions FSOpts;
4601 unsigned Idx = 0;
4602 FSOpts.WorkingDir = ReadString(Record, Idx);
4603 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4604}
4605
4606bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4607 bool Complain,
4608 ASTReaderListener &Listener) {
4609 HeaderSearchOptions HSOpts;
4610 unsigned Idx = 0;
4611 HSOpts.Sysroot = ReadString(Record, Idx);
4612
4613 // Include entries.
4614 for (unsigned N = Record[Idx++]; N; --N) {
4615 std::string Path = ReadString(Record, Idx);
4616 frontend::IncludeDirGroup Group
4617 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 bool IsFramework = Record[Idx++];
4619 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004620 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4621 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 }
4623
4624 // System header prefixes.
4625 for (unsigned N = Record[Idx++]; N; --N) {
4626 std::string Prefix = ReadString(Record, Idx);
4627 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004628 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 }
4630
4631 HSOpts.ResourceDir = ReadString(Record, Idx);
4632 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004633 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 HSOpts.DisableModuleHash = Record[Idx++];
4635 HSOpts.UseBuiltinIncludes = Record[Idx++];
4636 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4637 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4638 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004639 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004640
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004641 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4642 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004643}
4644
4645bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4646 bool Complain,
4647 ASTReaderListener &Listener,
4648 std::string &SuggestedPredefines) {
4649 PreprocessorOptions PPOpts;
4650 unsigned Idx = 0;
4651
4652 // Macro definitions/undefs
4653 for (unsigned N = Record[Idx++]; N; --N) {
4654 std::string Macro = ReadString(Record, Idx);
4655 bool IsUndef = Record[Idx++];
4656 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4657 }
4658
4659 // Includes
4660 for (unsigned N = Record[Idx++]; N; --N) {
4661 PPOpts.Includes.push_back(ReadString(Record, Idx));
4662 }
4663
4664 // Macro Includes
4665 for (unsigned N = Record[Idx++]; N; --N) {
4666 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4667 }
4668
4669 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004670 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4672 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4673 PPOpts.ObjCXXARCStandardLibrary =
4674 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4675 SuggestedPredefines.clear();
4676 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4677 SuggestedPredefines);
4678}
4679
4680std::pair<ModuleFile *, unsigned>
4681ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4682 GlobalPreprocessedEntityMapType::iterator
4683 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4684 assert(I != GlobalPreprocessedEntityMap.end() &&
4685 "Corrupted global preprocessed entity map");
4686 ModuleFile *M = I->second;
4687 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4688 return std::make_pair(M, LocalIndex);
4689}
4690
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004691llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004692ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4693 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4694 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4695 Mod.NumPreprocessedEntities);
4696
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004697 return llvm::make_range(PreprocessingRecord::iterator(),
4698 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004699}
4700
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004701llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004702ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004703 return llvm::make_range(
4704 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4705 ModuleDeclIterator(this, &Mod,
4706 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004707}
4708
4709PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4710 PreprocessedEntityID PPID = Index+1;
4711 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4712 ModuleFile &M = *PPInfo.first;
4713 unsigned LocalIndex = PPInfo.second;
4714 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4715
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 if (!PP.getPreprocessingRecord()) {
4717 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004718 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 }
4720
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004721 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4722 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4723
4724 llvm::BitstreamEntry Entry =
4725 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4726 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004727 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004728
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 // Read the record.
4730 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4731 ReadSourceLocation(M, PPOffs.End));
4732 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004733 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 RecordData Record;
4735 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004736 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4737 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004738 switch (RecType) {
4739 case PPD_MACRO_EXPANSION: {
4740 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004741 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004742 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 if (isBuiltin)
4744 Name = getLocalIdentifier(M, Record[1]);
4745 else {
Richard Smith66a81862015-05-04 02:25:31 +00004746 PreprocessedEntityID GlobalID =
4747 getGlobalPreprocessedEntityID(M, Record[1]);
4748 Def = cast<MacroDefinitionRecord>(
4749 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 }
4751
4752 MacroExpansion *ME;
4753 if (isBuiltin)
4754 ME = new (PPRec) MacroExpansion(Name, Range);
4755 else
4756 ME = new (PPRec) MacroExpansion(Def, Range);
4757
4758 return ME;
4759 }
4760
4761 case PPD_MACRO_DEFINITION: {
4762 // Decode the identifier info and then check again; if the macro is
4763 // still defined and associated with the identifier,
4764 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004765 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004766
4767 if (DeserializationListener)
4768 DeserializationListener->MacroDefinitionRead(PPID, MD);
4769
4770 return MD;
4771 }
4772
4773 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004774 const char *FullFileNameStart = Blob.data() + Record[0];
4775 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004776 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 if (!FullFileName.empty())
4778 File = PP.getFileManager().getFile(FullFileName);
4779
4780 // FIXME: Stable encoding
4781 InclusionDirective::InclusionKind Kind
4782 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4783 InclusionDirective *ID
4784 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004785 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 Record[1], Record[3],
4787 File,
4788 Range);
4789 return ID;
4790 }
4791 }
4792
4793 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4794}
4795
4796/// \brief \arg SLocMapI points at a chunk of a module that contains no
4797/// preprocessed entities or the entities it contains are not the ones we are
4798/// looking for. Find the next module that contains entities and return the ID
4799/// of the first entry.
4800PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4801 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4802 ++SLocMapI;
4803 for (GlobalSLocOffsetMapType::const_iterator
4804 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4805 ModuleFile &M = *SLocMapI->second;
4806 if (M.NumPreprocessedEntities)
4807 return M.BasePreprocessedEntityID;
4808 }
4809
4810 return getTotalNumPreprocessedEntities();
4811}
4812
4813namespace {
4814
4815template <unsigned PPEntityOffset::*PPLoc>
4816struct PPEntityComp {
4817 const ASTReader &Reader;
4818 ModuleFile &M;
4819
4820 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4821
4822 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4823 SourceLocation LHS = getLoc(L);
4824 SourceLocation RHS = getLoc(R);
4825 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4826 }
4827
4828 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4829 SourceLocation LHS = getLoc(L);
4830 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4831 }
4832
4833 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4834 SourceLocation RHS = getLoc(R);
4835 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4836 }
4837
4838 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4839 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4840 }
4841};
4842
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004843}
Guy Benyei11169dd2012-12-18 14:30:41 +00004844
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004845PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4846 bool EndsAfter) const {
4847 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 return getTotalNumPreprocessedEntities();
4849
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004850 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4851 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4853 "Corrupted global sloc offset map");
4854
4855 if (SLocMapI->second->NumPreprocessedEntities == 0)
4856 return findNextPreprocessedEntity(SLocMapI);
4857
4858 ModuleFile &M = *SLocMapI->second;
4859 typedef const PPEntityOffset *pp_iterator;
4860 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4861 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4862
4863 size_t Count = M.NumPreprocessedEntities;
4864 size_t Half;
4865 pp_iterator First = pp_begin;
4866 pp_iterator PPI;
4867
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004868 if (EndsAfter) {
4869 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4870 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4871 } else {
4872 // Do a binary search manually instead of using std::lower_bound because
4873 // The end locations of entities may be unordered (when a macro expansion
4874 // is inside another macro argument), but for this case it is not important
4875 // whether we get the first macro expansion or its containing macro.
4876 while (Count > 0) {
4877 Half = Count / 2;
4878 PPI = First;
4879 std::advance(PPI, Half);
4880 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4881 Loc)) {
4882 First = PPI;
4883 ++First;
4884 Count = Count - Half - 1;
4885 } else
4886 Count = Half;
4887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 }
4889
4890 if (PPI == pp_end)
4891 return findNextPreprocessedEntity(SLocMapI);
4892
4893 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4894}
4895
Guy Benyei11169dd2012-12-18 14:30:41 +00004896/// \brief Returns a pair of [Begin, End) indices of preallocated
4897/// preprocessed entities that \arg Range encompasses.
4898std::pair<unsigned, unsigned>
4899 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4900 if (Range.isInvalid())
4901 return std::make_pair(0,0);
4902 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4903
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004904 PreprocessedEntityID BeginID =
4905 findPreprocessedEntity(Range.getBegin(), false);
4906 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 return std::make_pair(BeginID, EndID);
4908}
4909
4910/// \brief Optionally returns true or false if the preallocated preprocessed
4911/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004912Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 FileID FID) {
4914 if (FID.isInvalid())
4915 return false;
4916
4917 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4918 ModuleFile &M = *PPInfo.first;
4919 unsigned LocalIndex = PPInfo.second;
4920 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4921
4922 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4923 if (Loc.isInvalid())
4924 return false;
4925
4926 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4927 return true;
4928 else
4929 return false;
4930}
4931
4932namespace {
4933 /// \brief Visitor used to search for information about a header file.
4934 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 const FileEntry *FE;
4936
David Blaikie05785d12013-02-20 22:23:23 +00004937 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938
4939 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004940 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4941 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004942
4943 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 HeaderFileInfoLookupTable *Table
4945 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4946 if (!Table)
4947 return false;
4948
4949 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004950 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 if (Pos == Table->end())
4952 return false;
4953
Richard Smithbdf2d932015-07-30 03:37:16 +00004954 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 return true;
4956 }
4957
David Blaikie05785d12013-02-20 22:23:23 +00004958 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004960}
Guy Benyei11169dd2012-12-18 14:30:41 +00004961
4962HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004963 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004964 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004965 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004967
4968 return HeaderFileInfo();
4969}
4970
4971void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4972 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004973 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4975 ModuleFile &F = *(*I);
4976 unsigned Idx = 0;
4977 DiagStates.clear();
4978 assert(!Diag.DiagStates.empty());
4979 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4980 while (Idx < F.PragmaDiagMappings.size()) {
4981 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4982 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4983 if (DiagStateID != 0) {
4984 Diag.DiagStatePoints.push_back(
4985 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4986 FullSourceLoc(Loc, SourceMgr)));
4987 continue;
4988 }
4989
4990 assert(DiagStateID == 0);
4991 // A new DiagState was created here.
4992 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4993 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4994 DiagStates.push_back(NewState);
4995 Diag.DiagStatePoints.push_back(
4996 DiagnosticsEngine::DiagStatePoint(NewState,
4997 FullSourceLoc(Loc, SourceMgr)));
4998 while (1) {
4999 assert(Idx < F.PragmaDiagMappings.size() &&
5000 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5001 if (Idx >= F.PragmaDiagMappings.size()) {
5002 break; // Something is messed up but at least avoid infinite loop in
5003 // release build.
5004 }
5005 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5006 if (DiagID == (unsigned)-1) {
5007 break; // no more diag/map pairs for this location.
5008 }
Alp Tokerc726c362014-06-10 09:31:37 +00005009 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5010 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5011 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 }
5013 }
5014 }
5015}
5016
5017/// \brief Get the correct cursor and offset for loading a type.
5018ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5019 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5020 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5021 ModuleFile *M = I->second;
5022 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5023}
5024
5025/// \brief Read and return the type with the given index..
5026///
5027/// The index is the type ID, shifted and minus the number of predefs. This
5028/// routine actually reads the record corresponding to the type at the given
5029/// location. It is a helper routine for GetType, which deals with reading type
5030/// IDs.
5031QualType ASTReader::readTypeRecord(unsigned Index) {
5032 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005033 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005034
5035 // Keep track of where we are in the stream, then jump back there
5036 // after reading this type.
5037 SavedStreamPosition SavedPosition(DeclsCursor);
5038
5039 ReadingKindTracker ReadingKind(Read_Type, *this);
5040
5041 // Note that we are loading a type record.
5042 Deserializing AType(this);
5043
5044 unsigned Idx = 0;
5045 DeclsCursor.JumpToBit(Loc.Offset);
5046 RecordData Record;
5047 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005048 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case TYPE_EXT_QUAL: {
5050 if (Record.size() != 2) {
5051 Error("Incorrect encoding of extended qualifier type");
5052 return QualType();
5053 }
5054 QualType Base = readType(*Loc.F, Record, Idx);
5055 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5056 return Context.getQualifiedType(Base, Quals);
5057 }
5058
5059 case TYPE_COMPLEX: {
5060 if (Record.size() != 1) {
5061 Error("Incorrect encoding of complex type");
5062 return QualType();
5063 }
5064 QualType ElemType = readType(*Loc.F, Record, Idx);
5065 return Context.getComplexType(ElemType);
5066 }
5067
5068 case TYPE_POINTER: {
5069 if (Record.size() != 1) {
5070 Error("Incorrect encoding of pointer type");
5071 return QualType();
5072 }
5073 QualType PointeeType = readType(*Loc.F, Record, Idx);
5074 return Context.getPointerType(PointeeType);
5075 }
5076
Reid Kleckner8a365022013-06-24 17:51:48 +00005077 case TYPE_DECAYED: {
5078 if (Record.size() != 1) {
5079 Error("Incorrect encoding of decayed type");
5080 return QualType();
5081 }
5082 QualType OriginalType = readType(*Loc.F, Record, Idx);
5083 QualType DT = Context.getAdjustedParameterType(OriginalType);
5084 if (!isa<DecayedType>(DT))
5085 Error("Decayed type does not decay");
5086 return DT;
5087 }
5088
Reid Kleckner0503a872013-12-05 01:23:43 +00005089 case TYPE_ADJUSTED: {
5090 if (Record.size() != 2) {
5091 Error("Incorrect encoding of adjusted type");
5092 return QualType();
5093 }
5094 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5095 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5096 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5097 }
5098
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case TYPE_BLOCK_POINTER: {
5100 if (Record.size() != 1) {
5101 Error("Incorrect encoding of block pointer type");
5102 return QualType();
5103 }
5104 QualType PointeeType = readType(*Loc.F, Record, Idx);
5105 return Context.getBlockPointerType(PointeeType);
5106 }
5107
5108 case TYPE_LVALUE_REFERENCE: {
5109 if (Record.size() != 2) {
5110 Error("Incorrect encoding of lvalue reference type");
5111 return QualType();
5112 }
5113 QualType PointeeType = readType(*Loc.F, Record, Idx);
5114 return Context.getLValueReferenceType(PointeeType, Record[1]);
5115 }
5116
5117 case TYPE_RVALUE_REFERENCE: {
5118 if (Record.size() != 1) {
5119 Error("Incorrect encoding of rvalue reference type");
5120 return QualType();
5121 }
5122 QualType PointeeType = readType(*Loc.F, Record, Idx);
5123 return Context.getRValueReferenceType(PointeeType);
5124 }
5125
5126 case TYPE_MEMBER_POINTER: {
5127 if (Record.size() != 2) {
5128 Error("Incorrect encoding of member pointer type");
5129 return QualType();
5130 }
5131 QualType PointeeType = readType(*Loc.F, Record, Idx);
5132 QualType ClassType = readType(*Loc.F, Record, Idx);
5133 if (PointeeType.isNull() || ClassType.isNull())
5134 return QualType();
5135
5136 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5137 }
5138
5139 case TYPE_CONSTANT_ARRAY: {
5140 QualType ElementType = readType(*Loc.F, Record, Idx);
5141 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5142 unsigned IndexTypeQuals = Record[2];
5143 unsigned Idx = 3;
5144 llvm::APInt Size = ReadAPInt(Record, Idx);
5145 return Context.getConstantArrayType(ElementType, Size,
5146 ASM, IndexTypeQuals);
5147 }
5148
5149 case TYPE_INCOMPLETE_ARRAY: {
5150 QualType ElementType = readType(*Loc.F, Record, Idx);
5151 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5152 unsigned IndexTypeQuals = Record[2];
5153 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5154 }
5155
5156 case TYPE_VARIABLE_ARRAY: {
5157 QualType ElementType = readType(*Loc.F, Record, Idx);
5158 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5159 unsigned IndexTypeQuals = Record[2];
5160 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5161 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5162 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5163 ASM, IndexTypeQuals,
5164 SourceRange(LBLoc, RBLoc));
5165 }
5166
5167 case TYPE_VECTOR: {
5168 if (Record.size() != 3) {
5169 Error("incorrect encoding of vector type in AST file");
5170 return QualType();
5171 }
5172
5173 QualType ElementType = readType(*Loc.F, Record, Idx);
5174 unsigned NumElements = Record[1];
5175 unsigned VecKind = Record[2];
5176 return Context.getVectorType(ElementType, NumElements,
5177 (VectorType::VectorKind)VecKind);
5178 }
5179
5180 case TYPE_EXT_VECTOR: {
5181 if (Record.size() != 3) {
5182 Error("incorrect encoding of extended vector type in AST file");
5183 return QualType();
5184 }
5185
5186 QualType ElementType = readType(*Loc.F, Record, Idx);
5187 unsigned NumElements = Record[1];
5188 return Context.getExtVectorType(ElementType, NumElements);
5189 }
5190
5191 case TYPE_FUNCTION_NO_PROTO: {
5192 if (Record.size() != 6) {
5193 Error("incorrect encoding of no-proto function type");
5194 return QualType();
5195 }
5196 QualType ResultType = readType(*Loc.F, Record, Idx);
5197 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5198 (CallingConv)Record[4], Record[5]);
5199 return Context.getFunctionNoProtoType(ResultType, Info);
5200 }
5201
5202 case TYPE_FUNCTION_PROTO: {
5203 QualType ResultType = readType(*Loc.F, Record, Idx);
5204
5205 FunctionProtoType::ExtProtoInfo EPI;
5206 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5207 /*hasregparm*/ Record[2],
5208 /*regparm*/ Record[3],
5209 static_cast<CallingConv>(Record[4]),
5210 /*produces*/ Record[5]);
5211
5212 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005213
5214 EPI.Variadic = Record[Idx++];
5215 EPI.HasTrailingReturn = Record[Idx++];
5216 EPI.TypeQuals = Record[Idx++];
5217 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005218 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005219 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005220
5221 unsigned NumParams = Record[Idx++];
5222 SmallVector<QualType, 16> ParamTypes;
5223 for (unsigned I = 0; I != NumParams; ++I)
5224 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5225
Jordan Rose5c382722013-03-08 21:51:21 +00005226 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 }
5228
5229 case TYPE_UNRESOLVED_USING: {
5230 unsigned Idx = 0;
5231 return Context.getTypeDeclType(
5232 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5233 }
5234
5235 case TYPE_TYPEDEF: {
5236 if (Record.size() != 2) {
5237 Error("incorrect encoding of typedef type");
5238 return QualType();
5239 }
5240 unsigned Idx = 0;
5241 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5242 QualType Canonical = readType(*Loc.F, Record, Idx);
5243 if (!Canonical.isNull())
5244 Canonical = Context.getCanonicalType(Canonical);
5245 return Context.getTypedefType(Decl, Canonical);
5246 }
5247
5248 case TYPE_TYPEOF_EXPR:
5249 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5250
5251 case TYPE_TYPEOF: {
5252 if (Record.size() != 1) {
5253 Error("incorrect encoding of typeof(type) in AST file");
5254 return QualType();
5255 }
5256 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5257 return Context.getTypeOfType(UnderlyingType);
5258 }
5259
5260 case TYPE_DECLTYPE: {
5261 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5262 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5263 }
5264
5265 case TYPE_UNARY_TRANSFORM: {
5266 QualType BaseType = readType(*Loc.F, Record, Idx);
5267 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5268 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5269 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5270 }
5271
Richard Smith74aeef52013-04-26 16:15:35 +00005272 case TYPE_AUTO: {
5273 QualType Deduced = readType(*Loc.F, Record, Idx);
5274 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005275 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005276 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005277 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005278
5279 case TYPE_RECORD: {
5280 if (Record.size() != 2) {
5281 Error("incorrect encoding of record type");
5282 return QualType();
5283 }
5284 unsigned Idx = 0;
5285 bool IsDependent = Record[Idx++];
5286 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5287 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5288 QualType T = Context.getRecordType(RD);
5289 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5290 return T;
5291 }
5292
5293 case TYPE_ENUM: {
5294 if (Record.size() != 2) {
5295 Error("incorrect encoding of enum type");
5296 return QualType();
5297 }
5298 unsigned Idx = 0;
5299 bool IsDependent = Record[Idx++];
5300 QualType T
5301 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5302 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5303 return T;
5304 }
5305
5306 case TYPE_ATTRIBUTED: {
5307 if (Record.size() != 3) {
5308 Error("incorrect encoding of attributed type");
5309 return QualType();
5310 }
5311 QualType modifiedType = readType(*Loc.F, Record, Idx);
5312 QualType equivalentType = readType(*Loc.F, Record, Idx);
5313 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5314 return Context.getAttributedType(kind, modifiedType, equivalentType);
5315 }
5316
5317 case TYPE_PAREN: {
5318 if (Record.size() != 1) {
5319 Error("incorrect encoding of paren type");
5320 return QualType();
5321 }
5322 QualType InnerType = readType(*Loc.F, Record, Idx);
5323 return Context.getParenType(InnerType);
5324 }
5325
5326 case TYPE_PACK_EXPANSION: {
5327 if (Record.size() != 2) {
5328 Error("incorrect encoding of pack expansion type");
5329 return QualType();
5330 }
5331 QualType Pattern = readType(*Loc.F, Record, Idx);
5332 if (Pattern.isNull())
5333 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005334 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 if (Record[1])
5336 NumExpansions = Record[1] - 1;
5337 return Context.getPackExpansionType(Pattern, NumExpansions);
5338 }
5339
5340 case TYPE_ELABORATED: {
5341 unsigned Idx = 0;
5342 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5343 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5344 QualType NamedType = readType(*Loc.F, Record, Idx);
5345 return Context.getElaboratedType(Keyword, NNS, NamedType);
5346 }
5347
5348 case TYPE_OBJC_INTERFACE: {
5349 unsigned Idx = 0;
5350 ObjCInterfaceDecl *ItfD
5351 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5352 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5353 }
5354
5355 case TYPE_OBJC_OBJECT: {
5356 unsigned Idx = 0;
5357 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005358 unsigned NumTypeArgs = Record[Idx++];
5359 SmallVector<QualType, 4> TypeArgs;
5360 for (unsigned I = 0; I != NumTypeArgs; ++I)
5361 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005362 unsigned NumProtos = Record[Idx++];
5363 SmallVector<ObjCProtocolDecl*, 4> Protos;
5364 for (unsigned I = 0; I != NumProtos; ++I)
5365 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005366 bool IsKindOf = Record[Idx++];
5367 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 }
5369
5370 case TYPE_OBJC_OBJECT_POINTER: {
5371 unsigned Idx = 0;
5372 QualType Pointee = readType(*Loc.F, Record, Idx);
5373 return Context.getObjCObjectPointerType(Pointee);
5374 }
5375
5376 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5377 unsigned Idx = 0;
5378 QualType Parm = readType(*Loc.F, Record, Idx);
5379 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005380 return Context.getSubstTemplateTypeParmType(
5381 cast<TemplateTypeParmType>(Parm),
5382 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 }
5384
5385 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5386 unsigned Idx = 0;
5387 QualType Parm = readType(*Loc.F, Record, Idx);
5388 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5389 return Context.getSubstTemplateTypeParmPackType(
5390 cast<TemplateTypeParmType>(Parm),
5391 ArgPack);
5392 }
5393
5394 case TYPE_INJECTED_CLASS_NAME: {
5395 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5396 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5397 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5398 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005399 const Type *T = nullptr;
5400 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5401 if (const Type *Existing = DI->getTypeForDecl()) {
5402 T = Existing;
5403 break;
5404 }
5405 }
5406 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005407 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005408 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5409 DI->setTypeForDecl(T);
5410 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005411 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 }
5413
5414 case TYPE_TEMPLATE_TYPE_PARM: {
5415 unsigned Idx = 0;
5416 unsigned Depth = Record[Idx++];
5417 unsigned Index = Record[Idx++];
5418 bool Pack = Record[Idx++];
5419 TemplateTypeParmDecl *D
5420 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5421 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5422 }
5423
5424 case TYPE_DEPENDENT_NAME: {
5425 unsigned Idx = 0;
5426 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5427 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005428 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 QualType Canon = readType(*Loc.F, Record, Idx);
5430 if (!Canon.isNull())
5431 Canon = Context.getCanonicalType(Canon);
5432 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5433 }
5434
5435 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5436 unsigned Idx = 0;
5437 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5438 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005439 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 unsigned NumArgs = Record[Idx++];
5441 SmallVector<TemplateArgument, 8> Args;
5442 Args.reserve(NumArgs);
5443 while (NumArgs--)
5444 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5445 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5446 Args.size(), Args.data());
5447 }
5448
5449 case TYPE_DEPENDENT_SIZED_ARRAY: {
5450 unsigned Idx = 0;
5451
5452 // ArrayType
5453 QualType ElementType = readType(*Loc.F, Record, Idx);
5454 ArrayType::ArraySizeModifier ASM
5455 = (ArrayType::ArraySizeModifier)Record[Idx++];
5456 unsigned IndexTypeQuals = Record[Idx++];
5457
5458 // DependentSizedArrayType
5459 Expr *NumElts = ReadExpr(*Loc.F);
5460 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5461
5462 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5463 IndexTypeQuals, Brackets);
5464 }
5465
5466 case TYPE_TEMPLATE_SPECIALIZATION: {
5467 unsigned Idx = 0;
5468 bool IsDependent = Record[Idx++];
5469 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5470 SmallVector<TemplateArgument, 8> Args;
5471 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5472 QualType Underlying = readType(*Loc.F, Record, Idx);
5473 QualType T;
5474 if (Underlying.isNull())
5475 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5476 Args.size());
5477 else
5478 T = Context.getTemplateSpecializationType(Name, Args.data(),
5479 Args.size(), Underlying);
5480 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5481 return T;
5482 }
5483
5484 case TYPE_ATOMIC: {
5485 if (Record.size() != 1) {
5486 Error("Incorrect encoding of atomic type");
5487 return QualType();
5488 }
5489 QualType ValueType = readType(*Loc.F, Record, Idx);
5490 return Context.getAtomicType(ValueType);
5491 }
5492 }
5493 llvm_unreachable("Invalid TypeCode!");
5494}
5495
Richard Smith564417a2014-03-20 21:47:22 +00005496void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5497 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005498 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005499 const RecordData &Record, unsigned &Idx) {
5500 ExceptionSpecificationType EST =
5501 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005502 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005503 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005504 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005505 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005506 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005507 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005508 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005509 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005510 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5511 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005512 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005513 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005514 }
5515}
5516
Guy Benyei11169dd2012-12-18 14:30:41 +00005517class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5518 ASTReader &Reader;
5519 ModuleFile &F;
5520 const ASTReader::RecordData &Record;
5521 unsigned &Idx;
5522
5523 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5524 unsigned &I) {
5525 return Reader.ReadSourceLocation(F, R, I);
5526 }
5527
5528 template<typename T>
5529 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5530 return Reader.ReadDeclAs<T>(F, Record, Idx);
5531 }
5532
5533public:
5534 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5535 const ASTReader::RecordData &Record, unsigned &Idx)
5536 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5537 { }
5538
5539 // We want compile-time assurance that we've enumerated all of
5540 // these, so unfortunately we have to declare them first, then
5541 // define them out-of-line.
5542#define ABSTRACT_TYPELOC(CLASS, PARENT)
5543#define TYPELOC(CLASS, PARENT) \
5544 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5545#include "clang/AST/TypeLocNodes.def"
5546
5547 void VisitFunctionTypeLoc(FunctionTypeLoc);
5548 void VisitArrayTypeLoc(ArrayTypeLoc);
5549};
5550
5551void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5552 // nothing to do
5553}
5554void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5555 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5556 if (TL.needsExtraLocalData()) {
5557 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5558 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5559 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5560 TL.setModeAttr(Record[Idx++]);
5561 }
5562}
5563void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5564 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5565}
5566void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5567 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5568}
Reid Kleckner8a365022013-06-24 17:51:48 +00005569void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5570 // nothing to do
5571}
Reid Kleckner0503a872013-12-05 01:23:43 +00005572void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5573 // nothing to do
5574}
Guy Benyei11169dd2012-12-18 14:30:41 +00005575void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5576 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5577}
5578void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5579 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5580}
5581void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5582 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5583}
5584void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5585 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5586 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5587}
5588void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5589 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5590 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5591 if (Record[Idx++])
5592 TL.setSizeExpr(Reader.ReadExpr(F));
5593 else
Craig Toppera13603a2014-05-22 05:54:18 +00005594 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005595}
5596void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5597 VisitArrayTypeLoc(TL);
5598}
5599void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5600 VisitArrayTypeLoc(TL);
5601}
5602void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5603 VisitArrayTypeLoc(TL);
5604}
5605void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5606 DependentSizedArrayTypeLoc TL) {
5607 VisitArrayTypeLoc(TL);
5608}
5609void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5610 DependentSizedExtVectorTypeLoc TL) {
5611 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5612}
5613void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5614 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5617 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5618}
5619void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5620 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5621 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5622 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5623 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005624 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5625 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 }
5627}
5628void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5629 VisitFunctionTypeLoc(TL);
5630}
5631void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5632 VisitFunctionTypeLoc(TL);
5633}
5634void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5636}
5637void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5638 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5639}
5640void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5641 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5642 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5643 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5644}
5645void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5646 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5647 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5648 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5649 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5650}
5651void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5655 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5656 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5657 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5658 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5659}
5660void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5661 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5662}
5663void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5664 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5665}
5666void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5667 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5668}
5669void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5670 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5671 if (TL.hasAttrOperand()) {
5672 SourceRange range;
5673 range.setBegin(ReadSourceLocation(Record, Idx));
5674 range.setEnd(ReadSourceLocation(Record, Idx));
5675 TL.setAttrOperandParensRange(range);
5676 }
5677 if (TL.hasAttrExprOperand()) {
5678 if (Record[Idx++])
5679 TL.setAttrExprOperand(Reader.ReadExpr(F));
5680 else
Craig Toppera13603a2014-05-22 05:54:18 +00005681 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 } else if (TL.hasAttrEnumOperand())
5683 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5684}
5685void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5686 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5687}
5688void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5689 SubstTemplateTypeParmTypeLoc TL) {
5690 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5691}
5692void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5693 SubstTemplateTypeParmPackTypeLoc TL) {
5694 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5695}
5696void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5697 TemplateSpecializationTypeLoc TL) {
5698 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5699 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5700 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5701 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5702 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5703 TL.setArgLocInfo(i,
5704 Reader.GetTemplateArgumentLocInfo(F,
5705 TL.getTypePtr()->getArg(i).getKind(),
5706 Record, Idx));
5707}
5708void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5709 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5710 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5711}
5712void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5713 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5714 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5715}
5716void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5717 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5718}
5719void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5720 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5721 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5722 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5723}
5724void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5725 DependentTemplateSpecializationTypeLoc TL) {
5726 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5727 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5728 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5729 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5730 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5731 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5732 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5733 TL.setArgLocInfo(I,
5734 Reader.GetTemplateArgumentLocInfo(F,
5735 TL.getTypePtr()->getArg(I).getKind(),
5736 Record, Idx));
5737}
5738void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5739 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5740}
5741void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5742 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5743}
5744void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5745 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005746 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5747 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5748 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5749 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5750 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5751 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005752 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5753 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5756 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5759 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5760 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5761 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5762}
5763
5764TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5765 const RecordData &Record,
5766 unsigned &Idx) {
5767 QualType InfoTy = readType(F, Record, Idx);
5768 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005769 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005770
5771 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5772 TypeLocReader TLR(*this, F, Record, Idx);
5773 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5774 TLR.Visit(TL);
5775 return TInfo;
5776}
5777
5778QualType ASTReader::GetType(TypeID ID) {
5779 unsigned FastQuals = ID & Qualifiers::FastMask;
5780 unsigned Index = ID >> Qualifiers::FastWidth;
5781
5782 if (Index < NUM_PREDEF_TYPE_IDS) {
5783 QualType T;
5784 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005785 case PREDEF_TYPE_NULL_ID:
5786 return QualType();
5787 case PREDEF_TYPE_VOID_ID:
5788 T = Context.VoidTy;
5789 break;
5790 case PREDEF_TYPE_BOOL_ID:
5791 T = Context.BoolTy;
5792 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005793
5794 case PREDEF_TYPE_CHAR_U_ID:
5795 case PREDEF_TYPE_CHAR_S_ID:
5796 // FIXME: Check that the signedness of CharTy is correct!
5797 T = Context.CharTy;
5798 break;
5799
Alexey Baderbdf7c842015-09-15 12:18:29 +00005800 case PREDEF_TYPE_UCHAR_ID:
5801 T = Context.UnsignedCharTy;
5802 break;
5803 case PREDEF_TYPE_USHORT_ID:
5804 T = Context.UnsignedShortTy;
5805 break;
5806 case PREDEF_TYPE_UINT_ID:
5807 T = Context.UnsignedIntTy;
5808 break;
5809 case PREDEF_TYPE_ULONG_ID:
5810 T = Context.UnsignedLongTy;
5811 break;
5812 case PREDEF_TYPE_ULONGLONG_ID:
5813 T = Context.UnsignedLongLongTy;
5814 break;
5815 case PREDEF_TYPE_UINT128_ID:
5816 T = Context.UnsignedInt128Ty;
5817 break;
5818 case PREDEF_TYPE_SCHAR_ID:
5819 T = Context.SignedCharTy;
5820 break;
5821 case PREDEF_TYPE_WCHAR_ID:
5822 T = Context.WCharTy;
5823 break;
5824 case PREDEF_TYPE_SHORT_ID:
5825 T = Context.ShortTy;
5826 break;
5827 case PREDEF_TYPE_INT_ID:
5828 T = Context.IntTy;
5829 break;
5830 case PREDEF_TYPE_LONG_ID:
5831 T = Context.LongTy;
5832 break;
5833 case PREDEF_TYPE_LONGLONG_ID:
5834 T = Context.LongLongTy;
5835 break;
5836 case PREDEF_TYPE_INT128_ID:
5837 T = Context.Int128Ty;
5838 break;
5839 case PREDEF_TYPE_HALF_ID:
5840 T = Context.HalfTy;
5841 break;
5842 case PREDEF_TYPE_FLOAT_ID:
5843 T = Context.FloatTy;
5844 break;
5845 case PREDEF_TYPE_DOUBLE_ID:
5846 T = Context.DoubleTy;
5847 break;
5848 case PREDEF_TYPE_LONGDOUBLE_ID:
5849 T = Context.LongDoubleTy;
5850 break;
5851 case PREDEF_TYPE_OVERLOAD_ID:
5852 T = Context.OverloadTy;
5853 break;
5854 case PREDEF_TYPE_BOUND_MEMBER:
5855 T = Context.BoundMemberTy;
5856 break;
5857 case PREDEF_TYPE_PSEUDO_OBJECT:
5858 T = Context.PseudoObjectTy;
5859 break;
5860 case PREDEF_TYPE_DEPENDENT_ID:
5861 T = Context.DependentTy;
5862 break;
5863 case PREDEF_TYPE_UNKNOWN_ANY:
5864 T = Context.UnknownAnyTy;
5865 break;
5866 case PREDEF_TYPE_NULLPTR_ID:
5867 T = Context.NullPtrTy;
5868 break;
5869 case PREDEF_TYPE_CHAR16_ID:
5870 T = Context.Char16Ty;
5871 break;
5872 case PREDEF_TYPE_CHAR32_ID:
5873 T = Context.Char32Ty;
5874 break;
5875 case PREDEF_TYPE_OBJC_ID:
5876 T = Context.ObjCBuiltinIdTy;
5877 break;
5878 case PREDEF_TYPE_OBJC_CLASS:
5879 T = Context.ObjCBuiltinClassTy;
5880 break;
5881 case PREDEF_TYPE_OBJC_SEL:
5882 T = Context.ObjCBuiltinSelTy;
5883 break;
5884 case PREDEF_TYPE_IMAGE1D_ID:
5885 T = Context.OCLImage1dTy;
5886 break;
5887 case PREDEF_TYPE_IMAGE1D_ARR_ID:
5888 T = Context.OCLImage1dArrayTy;
5889 break;
5890 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
5891 T = Context.OCLImage1dBufferTy;
5892 break;
5893 case PREDEF_TYPE_IMAGE2D_ID:
5894 T = Context.OCLImage2dTy;
5895 break;
5896 case PREDEF_TYPE_IMAGE2D_ARR_ID:
5897 T = Context.OCLImage2dArrayTy;
5898 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005899 case PREDEF_TYPE_IMAGE2D_DEP_ID:
5900 T = Context.OCLImage2dDepthTy;
5901 break;
5902 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
5903 T = Context.OCLImage2dArrayDepthTy;
5904 break;
5905 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
5906 T = Context.OCLImage2dMSAATy;
5907 break;
5908 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
5909 T = Context.OCLImage2dArrayMSAATy;
5910 break;
5911 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
5912 T = Context.OCLImage2dMSAADepthTy;
5913 break;
5914 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
5915 T = Context.OCLImage2dArrayMSAADepthTy;
5916 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00005917 case PREDEF_TYPE_IMAGE3D_ID:
5918 T = Context.OCLImage3dTy;
5919 break;
5920 case PREDEF_TYPE_SAMPLER_ID:
5921 T = Context.OCLSamplerTy;
5922 break;
5923 case PREDEF_TYPE_EVENT_ID:
5924 T = Context.OCLEventTy;
5925 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00005926 case PREDEF_TYPE_CLK_EVENT_ID:
5927 T = Context.OCLClkEventTy;
5928 break;
5929 case PREDEF_TYPE_QUEUE_ID:
5930 T = Context.OCLQueueTy;
5931 break;
5932 case PREDEF_TYPE_NDRANGE_ID:
5933 T = Context.OCLNDRangeTy;
5934 break;
5935 case PREDEF_TYPE_RESERVE_ID_ID:
5936 T = Context.OCLReserveIDTy;
5937 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00005938 case PREDEF_TYPE_AUTO_DEDUCT:
5939 T = Context.getAutoDeductType();
5940 break;
5941
5942 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5943 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005944 break;
5945
5946 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5947 T = Context.ARCUnbridgedCastTy;
5948 break;
5949
Guy Benyei11169dd2012-12-18 14:30:41 +00005950 case PREDEF_TYPE_BUILTIN_FN:
5951 T = Context.BuiltinFnTy;
5952 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005953
5954 case PREDEF_TYPE_OMP_ARRAY_SECTION:
5955 T = Context.OMPArraySectionTy;
5956 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005957 }
5958
5959 assert(!T.isNull() && "Unknown predefined type");
5960 return T.withFastQualifiers(FastQuals);
5961 }
5962
5963 Index -= NUM_PREDEF_TYPE_IDS;
5964 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5965 if (TypesLoaded[Index].isNull()) {
5966 TypesLoaded[Index] = readTypeRecord(Index);
5967 if (TypesLoaded[Index].isNull())
5968 return QualType();
5969
5970 TypesLoaded[Index]->setFromAST();
5971 if (DeserializationListener)
5972 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5973 TypesLoaded[Index]);
5974 }
5975
5976 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5977}
5978
5979QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5980 return GetType(getGlobalTypeID(F, LocalID));
5981}
5982
5983serialization::TypeID
5984ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5985 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5986 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5987
5988 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5989 return LocalID;
5990
5991 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5992 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5993 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5994
5995 unsigned GlobalIndex = LocalIndex + I->second;
5996 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5997}
5998
5999TemplateArgumentLocInfo
6000ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6001 TemplateArgument::ArgKind Kind,
6002 const RecordData &Record,
6003 unsigned &Index) {
6004 switch (Kind) {
6005 case TemplateArgument::Expression:
6006 return ReadExpr(F);
6007 case TemplateArgument::Type:
6008 return GetTypeSourceInfo(F, Record, Index);
6009 case TemplateArgument::Template: {
6010 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6011 Index);
6012 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6013 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6014 SourceLocation());
6015 }
6016 case TemplateArgument::TemplateExpansion: {
6017 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6018 Index);
6019 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6020 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6021 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6022 EllipsisLoc);
6023 }
6024 case TemplateArgument::Null:
6025 case TemplateArgument::Integral:
6026 case TemplateArgument::Declaration:
6027 case TemplateArgument::NullPtr:
6028 case TemplateArgument::Pack:
6029 // FIXME: Is this right?
6030 return TemplateArgumentLocInfo();
6031 }
6032 llvm_unreachable("unexpected template argument loc");
6033}
6034
6035TemplateArgumentLoc
6036ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6037 const RecordData &Record, unsigned &Index) {
6038 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6039
6040 if (Arg.getKind() == TemplateArgument::Expression) {
6041 if (Record[Index++]) // bool InfoHasSameExpr.
6042 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6043 }
6044 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6045 Record, Index));
6046}
6047
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006048const ASTTemplateArgumentListInfo*
6049ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6050 const RecordData &Record,
6051 unsigned &Index) {
6052 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6053 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6054 unsigned NumArgsAsWritten = Record[Index++];
6055 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6056 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6057 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6058 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6059}
6060
Guy Benyei11169dd2012-12-18 14:30:41 +00006061Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6062 return GetDecl(ID);
6063}
6064
Richard Smith50895422015-01-31 03:04:55 +00006065template<typename TemplateSpecializationDecl>
6066static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6067 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6068 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6069}
6070
Richard Smith053f6c62014-05-16 23:01:30 +00006071void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006072 if (NumCurrentElementsDeserializing) {
6073 // We arrange to not care about the complete redeclaration chain while we're
6074 // deserializing. Just remember that the AST has marked this one as complete
6075 // but that it's not actually complete yet, so we know we still need to
6076 // complete it later.
6077 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6078 return;
6079 }
6080
Richard Smith053f6c62014-05-16 23:01:30 +00006081 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6082
Richard Smith053f6c62014-05-16 23:01:30 +00006083 // If this is a named declaration, complete it by looking it up
6084 // within its context.
6085 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006086 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006087 // all mergeable entities within it.
6088 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6089 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6090 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006091 if (!getContext().getLangOpts().CPlusPlus &&
6092 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006093 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006094 // the identifier instead. (For C++ modules, we don't store decls
6095 // in the serialized identifier table, so we do the lookup in the TU.)
6096 auto *II = Name.getAsIdentifierInfo();
6097 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006098 if (II->isOutOfDate())
6099 updateOutOfDateIdentifier(*II);
6100 } else
6101 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006102 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006103 // Find all declarations of this kind from the relevant context.
6104 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6105 auto *DC = cast<DeclContext>(DCDecl);
6106 SmallVector<Decl*, 8> Decls;
6107 FindExternalLexicalDecls(
6108 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6109 }
Richard Smith053f6c62014-05-16 23:01:30 +00006110 }
6111 }
Richard Smith50895422015-01-31 03:04:55 +00006112
6113 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6114 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6115 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6116 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6117 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6118 if (auto *Template = FD->getPrimaryTemplate())
6119 Template->LoadLazySpecializations();
6120 }
Richard Smith053f6c62014-05-16 23:01:30 +00006121}
6122
Richard Smithc2bb8182015-03-24 06:36:48 +00006123uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6124 const RecordData &Record,
6125 unsigned &Idx) {
6126 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6127 Error("malformed AST file: missing C++ ctor initializers");
6128 return 0;
6129 }
6130
6131 unsigned LocalID = Record[Idx++];
6132 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6133}
6134
6135CXXCtorInitializer **
6136ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6137 RecordLocation Loc = getLocalBitOffset(Offset);
6138 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6139 SavedStreamPosition SavedPosition(Cursor);
6140 Cursor.JumpToBit(Loc.Offset);
6141 ReadingKindTracker ReadingKind(Read_Decl, *this);
6142
6143 RecordData Record;
6144 unsigned Code = Cursor.ReadCode();
6145 unsigned RecCode = Cursor.readRecord(Code, Record);
6146 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6147 Error("malformed AST file: missing C++ ctor initializers");
6148 return nullptr;
6149 }
6150
6151 unsigned Idx = 0;
6152 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6153}
6154
Richard Smithcd45dbc2014-04-19 03:48:30 +00006155uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6156 const RecordData &Record,
6157 unsigned &Idx) {
6158 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6159 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006161 }
6162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 unsigned LocalID = Record[Idx++];
6164 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6165}
6166
6167CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6168 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006169 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 SavedStreamPosition SavedPosition(Cursor);
6171 Cursor.JumpToBit(Loc.Offset);
6172 ReadingKindTracker ReadingKind(Read_Decl, *this);
6173 RecordData Record;
6174 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006175 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006177 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006178 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 }
6180
6181 unsigned Idx = 0;
6182 unsigned NumBases = Record[Idx++];
6183 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6184 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6185 for (unsigned I = 0; I != NumBases; ++I)
6186 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6187 return Bases;
6188}
6189
6190serialization::DeclID
6191ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6192 if (LocalID < NUM_PREDEF_DECL_IDS)
6193 return LocalID;
6194
6195 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6196 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6197 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6198
6199 return LocalID + I->second;
6200}
6201
6202bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6203 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006204 // Predefined decls aren't from any module.
6205 if (ID < NUM_PREDEF_DECL_IDS)
6206 return false;
6207
Richard Smithbcda1a92015-07-12 23:51:20 +00006208 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6209 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006210}
6211
Douglas Gregor9f782892013-01-21 15:25:38 +00006212ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006214 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6216 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6217 return I->second;
6218}
6219
6220SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6221 if (ID < NUM_PREDEF_DECL_IDS)
6222 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006223
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6225
6226 if (Index > DeclsLoaded.size()) {
6227 Error("declaration ID out-of-range for AST file");
6228 return SourceLocation();
6229 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006230
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 if (Decl *D = DeclsLoaded[Index])
6232 return D->getLocation();
6233
6234 unsigned RawLocation = 0;
6235 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6236 return ReadSourceLocation(*Rec.F, RawLocation);
6237}
6238
Richard Smithfe620d22015-03-05 23:24:12 +00006239static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6240 switch (ID) {
6241 case PREDEF_DECL_NULL_ID:
6242 return nullptr;
6243
6244 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6245 return Context.getTranslationUnitDecl();
6246
6247 case PREDEF_DECL_OBJC_ID_ID:
6248 return Context.getObjCIdDecl();
6249
6250 case PREDEF_DECL_OBJC_SEL_ID:
6251 return Context.getObjCSelDecl();
6252
6253 case PREDEF_DECL_OBJC_CLASS_ID:
6254 return Context.getObjCClassDecl();
6255
6256 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6257 return Context.getObjCProtocolDecl();
6258
6259 case PREDEF_DECL_INT_128_ID:
6260 return Context.getInt128Decl();
6261
6262 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6263 return Context.getUInt128Decl();
6264
6265 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6266 return Context.getObjCInstanceTypeDecl();
6267
6268 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6269 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006270
Richard Smith9b88a4c2015-07-27 05:40:23 +00006271 case PREDEF_DECL_VA_LIST_TAG:
6272 return Context.getVaListTagDecl();
6273
Charles Davisc7d5c942015-09-17 20:55:33 +00006274 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6275 return Context.getBuiltinMSVaListDecl();
6276
Richard Smithf19e1272015-03-07 00:04:49 +00006277 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6278 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006279 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006280 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006281}
6282
Richard Smithcd45dbc2014-04-19 03:48:30 +00006283Decl *ASTReader::GetExistingDecl(DeclID ID) {
6284 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006285 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6286 if (D) {
6287 // Track that we have merged the declaration with ID \p ID into the
6288 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006289 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006290 if (Merged.empty())
6291 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006292 }
Richard Smithfe620d22015-03-05 23:24:12 +00006293 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006295
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6297
6298 if (Index >= DeclsLoaded.size()) {
6299 assert(0 && "declaration ID out-of-range for AST file");
6300 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006301 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006303
6304 return DeclsLoaded[Index];
6305}
6306
6307Decl *ASTReader::GetDecl(DeclID ID) {
6308 if (ID < NUM_PREDEF_DECL_IDS)
6309 return GetExistingDecl(ID);
6310
6311 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6312
6313 if (Index >= DeclsLoaded.size()) {
6314 assert(0 && "declaration ID out-of-range for AST file");
6315 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006316 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006317 }
6318
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 if (!DeclsLoaded[Index]) {
6320 ReadDeclRecord(ID);
6321 if (DeserializationListener)
6322 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6323 }
6324
6325 return DeclsLoaded[Index];
6326}
6327
6328DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6329 DeclID GlobalID) {
6330 if (GlobalID < NUM_PREDEF_DECL_IDS)
6331 return GlobalID;
6332
6333 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6334 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6335 ModuleFile *Owner = I->second;
6336
6337 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6338 = M.GlobalToLocalDeclIDs.find(Owner);
6339 if (Pos == M.GlobalToLocalDeclIDs.end())
6340 return 0;
6341
6342 return GlobalID - Owner->BaseDeclID + Pos->second;
6343}
6344
6345serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6346 const RecordData &Record,
6347 unsigned &Idx) {
6348 if (Idx >= Record.size()) {
6349 Error("Corrupted AST file");
6350 return 0;
6351 }
6352
6353 return getGlobalDeclID(F, Record[Idx++]);
6354}
6355
6356/// \brief Resolve the offset of a statement into a statement.
6357///
6358/// This operation will read a new statement from the external
6359/// source each time it is called, and is meant to be used via a
6360/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6361Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6362 // Switch case IDs are per Decl.
6363 ClearSwitchCaseIDs();
6364
6365 // Offset here is a global offset across the entire chain.
6366 RecordLocation Loc = getLocalBitOffset(Offset);
6367 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6368 return ReadStmtFromStream(*Loc.F);
6369}
6370
Richard Smith3cb15722015-08-05 22:41:45 +00006371void ASTReader::FindExternalLexicalDecls(
6372 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6373 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006374 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6375
Richard Smith9ccdd932015-08-06 22:14:12 +00006376 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006377 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6378 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6379 auto K = (Decl::Kind)+LexicalDecls[I];
6380 if (!IsKindWeWant(K))
6381 continue;
6382
6383 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6384
6385 // Don't add predefined declarations to the lexical context more
6386 // than once.
6387 if (ID < NUM_PREDEF_DECL_IDS) {
6388 if (PredefsVisited[ID])
6389 continue;
6390
6391 PredefsVisited[ID] = true;
6392 }
6393
6394 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006395 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006396 if (!DC->isDeclInLexicalTraversal(D))
6397 Decls.push_back(D);
6398 }
6399 }
6400 };
6401
6402 if (isa<TranslationUnitDecl>(DC)) {
6403 for (auto Lexical : TULexicalDecls)
6404 Visit(Lexical.first, Lexical.second);
6405 } else {
6406 auto I = LexicalDecls.find(DC);
6407 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006408 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006409 }
6410
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006412}
6413
6414namespace {
6415
6416class DeclIDComp {
6417 ASTReader &Reader;
6418 ModuleFile &Mod;
6419
6420public:
6421 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6422
6423 bool operator()(LocalDeclID L, LocalDeclID R) const {
6424 SourceLocation LHS = getLocation(L);
6425 SourceLocation RHS = getLocation(R);
6426 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6427 }
6428
6429 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6430 SourceLocation RHS = getLocation(R);
6431 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6432 }
6433
6434 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6435 SourceLocation LHS = getLocation(L);
6436 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6437 }
6438
6439 SourceLocation getLocation(LocalDeclID ID) const {
6440 return Reader.getSourceManager().getFileLoc(
6441 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6442 }
6443};
6444
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006445}
Guy Benyei11169dd2012-12-18 14:30:41 +00006446
6447void ASTReader::FindFileRegionDecls(FileID File,
6448 unsigned Offset, unsigned Length,
6449 SmallVectorImpl<Decl *> &Decls) {
6450 SourceManager &SM = getSourceManager();
6451
6452 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6453 if (I == FileDeclIDs.end())
6454 return;
6455
6456 FileDeclsInfo &DInfo = I->second;
6457 if (DInfo.Decls.empty())
6458 return;
6459
6460 SourceLocation
6461 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6462 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6463
6464 DeclIDComp DIDComp(*this, *DInfo.Mod);
6465 ArrayRef<serialization::LocalDeclID>::iterator
6466 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6467 BeginLoc, DIDComp);
6468 if (BeginIt != DInfo.Decls.begin())
6469 --BeginIt;
6470
6471 // If we are pointing at a top-level decl inside an objc container, we need
6472 // to backtrack until we find it otherwise we will fail to report that the
6473 // region overlaps with an objc container.
6474 while (BeginIt != DInfo.Decls.begin() &&
6475 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6476 ->isTopLevelDeclInObjCContainer())
6477 --BeginIt;
6478
6479 ArrayRef<serialization::LocalDeclID>::iterator
6480 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6481 EndLoc, DIDComp);
6482 if (EndIt != DInfo.Decls.end())
6483 ++EndIt;
6484
6485 for (ArrayRef<serialization::LocalDeclID>::iterator
6486 DIt = BeginIt; DIt != EndIt; ++DIt)
6487 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6488}
6489
Richard Smith9ce12e32013-02-07 03:30:24 +00006490bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006491ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6492 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006493 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 "DeclContext has no visible decls in storage");
6495 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006496 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006497
Richard Smithd88a7f12015-09-01 20:35:42 +00006498 auto It = Lookups.find(DC);
6499 if (It == Lookups.end())
6500 return false;
6501
Richard Smith8c913ec2014-08-14 02:21:01 +00006502 Deserializing LookupResults(this);
6503
Richard Smithd88a7f12015-09-01 20:35:42 +00006504 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006506 for (DeclID ID : It->second.Table.find(Name)) {
6507 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6508 if (ND->getDeclName() == Name)
6509 Decls.push_back(ND);
6510 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006511
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 ++NumVisibleDeclContextsRead;
6513 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006514 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006515}
6516
Guy Benyei11169dd2012-12-18 14:30:41 +00006517void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6518 if (!DC->hasExternalVisibleStorage())
6519 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006520
6521 auto It = Lookups.find(DC);
6522 assert(It != Lookups.end() &&
6523 "have external visible storage but no lookup tables");
6524
Craig Topper79be4cd2013-07-05 04:33:53 +00006525 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006526
Richard Smithd88a7f12015-09-01 20:35:42 +00006527 for (DeclID ID : It->second.Table.findAll()) {
6528 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6529 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 }
6531
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 ++NumVisibleDeclContextsRead;
6533
Craig Topper79be4cd2013-07-05 04:33:53 +00006534 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6536 }
6537 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6538}
6539
Richard Smithd88a7f12015-09-01 20:35:42 +00006540const serialization::reader::DeclContextLookupTable *
6541ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6542 auto I = Lookups.find(Primary);
6543 return I == Lookups.end() ? nullptr : &I->second;
6544}
6545
Guy Benyei11169dd2012-12-18 14:30:41 +00006546/// \brief Under non-PCH compilation the consumer receives the objc methods
6547/// before receiving the implementation, and codegen depends on this.
6548/// We simulate this by deserializing and passing to consumer the methods of the
6549/// implementation before passing the deserialized implementation decl.
6550static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6551 ASTConsumer *Consumer) {
6552 assert(ImplD && Consumer);
6553
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006554 for (auto *I : ImplD->methods())
6555 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006556
6557 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6558}
6559
6560void ASTReader::PassInterestingDeclsToConsumer() {
6561 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006562
6563 if (PassingDeclsToConsumer)
6564 return;
6565
6566 // Guard variable to avoid recursively redoing the process of passing
6567 // decls to consumer.
6568 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6569 true);
6570
Richard Smith9e2341d2015-03-23 03:25:59 +00006571 // Ensure that we've loaded all potentially-interesting declarations
6572 // that need to be eagerly loaded.
6573 for (auto ID : EagerlyDeserializedDecls)
6574 GetDecl(ID);
6575 EagerlyDeserializedDecls.clear();
6576
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 while (!InterestingDecls.empty()) {
6578 Decl *D = InterestingDecls.front();
6579 InterestingDecls.pop_front();
6580
6581 PassInterestingDeclToConsumer(D);
6582 }
6583}
6584
6585void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6586 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6587 PassObjCImplDeclToConsumer(ImplD, Consumer);
6588 else
6589 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6590}
6591
6592void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6593 this->Consumer = Consumer;
6594
Richard Smith9e2341d2015-03-23 03:25:59 +00006595 if (Consumer)
6596 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006597
6598 if (DeserializationListener)
6599 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006600}
6601
6602void ASTReader::PrintStats() {
6603 std::fprintf(stderr, "*** AST File Statistics:\n");
6604
6605 unsigned NumTypesLoaded
6606 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6607 QualType());
6608 unsigned NumDeclsLoaded
6609 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006610 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 unsigned NumIdentifiersLoaded
6612 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6613 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006614 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006615 unsigned NumMacrosLoaded
6616 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6617 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006618 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 unsigned NumSelectorsLoaded
6620 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6621 SelectorsLoaded.end(),
6622 Selector());
6623
6624 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6625 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6626 NumSLocEntriesRead, TotalNumSLocEntries,
6627 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6628 if (!TypesLoaded.empty())
6629 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6630 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6631 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6632 if (!DeclsLoaded.empty())
6633 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6634 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6635 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6636 if (!IdentifiersLoaded.empty())
6637 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6638 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6639 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6640 if (!MacrosLoaded.empty())
6641 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6642 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6643 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6644 if (!SelectorsLoaded.empty())
6645 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6646 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6647 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6648 if (TotalNumStatements)
6649 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6650 NumStatementsRead, TotalNumStatements,
6651 ((float)NumStatementsRead/TotalNumStatements * 100));
6652 if (TotalNumMacros)
6653 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6654 NumMacrosRead, TotalNumMacros,
6655 ((float)NumMacrosRead/TotalNumMacros * 100));
6656 if (TotalLexicalDeclContexts)
6657 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6658 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6659 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6660 * 100));
6661 if (TotalVisibleDeclContexts)
6662 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6663 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6664 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6665 * 100));
6666 if (TotalNumMethodPoolEntries) {
6667 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6668 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6669 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6670 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006672 if (NumMethodPoolLookups) {
6673 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6674 NumMethodPoolHits, NumMethodPoolLookups,
6675 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6676 }
6677 if (NumMethodPoolTableLookups) {
6678 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6679 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6680 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6681 * 100.0));
6682 }
6683
Douglas Gregor00a50f72013-01-25 00:38:33 +00006684 if (NumIdentifierLookupHits) {
6685 std::fprintf(stderr,
6686 " %u / %u identifier table lookups succeeded (%f%%)\n",
6687 NumIdentifierLookupHits, NumIdentifierLookups,
6688 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6689 }
6690
Douglas Gregore060e572013-01-25 01:03:03 +00006691 if (GlobalIndex) {
6692 std::fprintf(stderr, "\n");
6693 GlobalIndex->printStats();
6694 }
6695
Guy Benyei11169dd2012-12-18 14:30:41 +00006696 std::fprintf(stderr, "\n");
6697 dump();
6698 std::fprintf(stderr, "\n");
6699}
6700
6701template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6702static void
6703dumpModuleIDMap(StringRef Name,
6704 const ContinuousRangeMap<Key, ModuleFile *,
6705 InitialCapacity> &Map) {
6706 if (Map.begin() == Map.end())
6707 return;
6708
6709 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6710 llvm::errs() << Name << ":\n";
6711 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6712 I != IEnd; ++I) {
6713 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6714 << "\n";
6715 }
6716}
6717
6718void ASTReader::dump() {
6719 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6720 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6721 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6722 dumpModuleIDMap("Global type map", GlobalTypeMap);
6723 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6724 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6725 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6726 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6727 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6728 dumpModuleIDMap("Global preprocessed entity map",
6729 GlobalPreprocessedEntityMap);
6730
6731 llvm::errs() << "\n*** PCH/Modules Loaded:";
6732 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6733 MEnd = ModuleMgr.end();
6734 M != MEnd; ++M)
6735 (*M)->dump();
6736}
6737
6738/// Return the amount of memory used by memory buffers, breaking down
6739/// by heap-backed versus mmap'ed memory.
6740void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6741 for (ModuleConstIterator I = ModuleMgr.begin(),
6742 E = ModuleMgr.end(); I != E; ++I) {
6743 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6744 size_t bytes = buf->getBufferSize();
6745 switch (buf->getBufferKind()) {
6746 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6747 sizes.malloc_bytes += bytes;
6748 break;
6749 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6750 sizes.mmap_bytes += bytes;
6751 break;
6752 }
6753 }
6754 }
6755}
6756
6757void ASTReader::InitializeSema(Sema &S) {
6758 SemaObj = &S;
6759 S.addExternalSource(this);
6760
6761 // Makes sure any declarations that were deserialized "too early"
6762 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006763 for (uint64_t ID : PreloadedDeclIDs) {
6764 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6765 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006767 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006768
Richard Smith3d8e97e2013-10-18 06:54:39 +00006769 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 if (!FPPragmaOptions.empty()) {
6771 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6772 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6773 }
6774
Richard Smith3d8e97e2013-10-18 06:54:39 +00006775 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 if (!OpenCLExtensions.empty()) {
6777 unsigned I = 0;
6778#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6779#include "clang/Basic/OpenCLExtensions.def"
6780
6781 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6782 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006783
6784 UpdateSema();
6785}
6786
6787void ASTReader::UpdateSema() {
6788 assert(SemaObj && "no Sema to update");
6789
6790 // Load the offsets of the declarations that Sema references.
6791 // They will be lazily deserialized when needed.
6792 if (!SemaDeclRefs.empty()) {
6793 assert(SemaDeclRefs.size() % 2 == 0);
6794 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6795 if (!SemaObj->StdNamespace)
6796 SemaObj->StdNamespace = SemaDeclRefs[I];
6797 if (!SemaObj->StdBadAlloc)
6798 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6799 }
6800 SemaDeclRefs.clear();
6801 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006802
6803 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6804 // encountered the pragma in the source.
6805 if(OptimizeOffPragmaLocation.isValid())
6806 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006807}
6808
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006809IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006810 // Note that we are loading an identifier.
6811 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006812
Douglas Gregor7211ac12013-01-25 23:32:03 +00006813 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006814 NumIdentifierLookups,
6815 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006816
6817 // We don't need to do identifier table lookups in C++ modules (we preload
6818 // all interesting declarations, and don't need to use the scope for name
6819 // lookups). Perform the lookup in PCH files, though, since we don't build
6820 // a complete initial identifier table if we're carrying on from a PCH.
6821 if (Context.getLangOpts().CPlusPlus) {
6822 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006823 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006824 break;
6825 } else {
6826 // If there is a global index, look there first to determine which modules
6827 // provably do not have any results for this identifier.
6828 GlobalModuleIndex::HitSet Hits;
6829 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6830 if (!loadGlobalIndex()) {
6831 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6832 HitsPtr = &Hits;
6833 }
6834 }
6835
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006836 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006837 }
6838
Guy Benyei11169dd2012-12-18 14:30:41 +00006839 IdentifierInfo *II = Visitor.getIdentifierInfo();
6840 markIdentifierUpToDate(II);
6841 return II;
6842}
6843
6844namespace clang {
6845 /// \brief An identifier-lookup iterator that enumerates all of the
6846 /// identifiers stored within a set of AST files.
6847 class ASTIdentifierIterator : public IdentifierIterator {
6848 /// \brief The AST reader whose identifiers are being enumerated.
6849 const ASTReader &Reader;
6850
6851 /// \brief The current index into the chain of AST files stored in
6852 /// the AST reader.
6853 unsigned Index;
6854
6855 /// \brief The current position within the identifier lookup table
6856 /// of the current AST file.
6857 ASTIdentifierLookupTable::key_iterator Current;
6858
6859 /// \brief The end position within the identifier lookup table of
6860 /// the current AST file.
6861 ASTIdentifierLookupTable::key_iterator End;
6862
6863 public:
6864 explicit ASTIdentifierIterator(const ASTReader &Reader);
6865
Craig Topper3e89dfe2014-03-13 02:13:41 +00006866 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006868}
Guy Benyei11169dd2012-12-18 14:30:41 +00006869
6870ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6871 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6872 ASTIdentifierLookupTable *IdTable
6873 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6874 Current = IdTable->key_begin();
6875 End = IdTable->key_end();
6876}
6877
6878StringRef ASTIdentifierIterator::Next() {
6879 while (Current == End) {
6880 // If we have exhausted all of our AST files, we're done.
6881 if (Index == 0)
6882 return StringRef();
6883
6884 --Index;
6885 ASTIdentifierLookupTable *IdTable
6886 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6887 IdentifierLookupTable;
6888 Current = IdTable->key_begin();
6889 End = IdTable->key_end();
6890 }
6891
6892 // We have any identifiers remaining in the current AST file; return
6893 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006894 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006896 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006897}
6898
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006899IdentifierIterator *ASTReader::getIdentifiers() {
6900 if (!loadGlobalIndex())
6901 return GlobalIndex->createIdentifierIterator();
6902
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 return new ASTIdentifierIterator(*this);
6904}
6905
6906namespace clang { namespace serialization {
6907 class ReadMethodPoolVisitor {
6908 ASTReader &Reader;
6909 Selector Sel;
6910 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006911 unsigned InstanceBits;
6912 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006913 bool InstanceHasMoreThanOneDecl;
6914 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006915 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6916 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006917
6918 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006919 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006921 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006922 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6923 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006924
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006925 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 if (!M.SelectorLookupTable)
6927 return false;
6928
6929 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006930 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 return true;
6932
Richard Smithbdf2d932015-07-30 03:37:16 +00006933 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 ASTSelectorLookupTable *PoolTable
6935 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006936 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 if (Pos == PoolTable->end())
6938 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006939
Richard Smithbdf2d932015-07-30 03:37:16 +00006940 ++Reader.NumMethodPoolTableHits;
6941 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006942 // FIXME: Not quite happy with the statistics here. We probably should
6943 // disable this tracking when called via LoadSelector.
6944 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006945 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006947 if (Reader.DeserializationListener)
6948 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006949
Richard Smithbdf2d932015-07-30 03:37:16 +00006950 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6951 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6952 InstanceBits = Data.InstanceBits;
6953 FactoryBits = Data.FactoryBits;
6954 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6955 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 return true;
6957 }
6958
6959 /// \brief Retrieve the instance methods found by this visitor.
6960 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6961 return InstanceMethods;
6962 }
6963
6964 /// \brief Retrieve the instance methods found by this visitor.
6965 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6966 return FactoryMethods;
6967 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006968
6969 unsigned getInstanceBits() const { return InstanceBits; }
6970 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006971 bool instanceHasMoreThanOneDecl() const {
6972 return InstanceHasMoreThanOneDecl;
6973 }
6974 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006976} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006977
6978/// \brief Add the given set of methods to the method list.
6979static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6980 ObjCMethodList &List) {
6981 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6982 S.addMethodToGlobalList(&List, Methods[I]);
6983 }
6984}
6985
6986void ASTReader::ReadMethodPool(Selector Sel) {
6987 // Get the selector generation and update it to the current generation.
6988 unsigned &Generation = SelectorGeneration[Sel];
6989 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006990 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006991
6992 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006993 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006994 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006995 ModuleMgr.visit(Visitor);
6996
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006998 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007000
7001 ++NumMethodPoolHits;
7002
Guy Benyei11169dd2012-12-18 14:30:41 +00007003 if (!getSema())
7004 return;
7005
7006 Sema &S = *getSema();
7007 Sema::GlobalMethodPool::iterator Pos
7008 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007009
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007010 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007011 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007012 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007013 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007014
7015 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7016 // when building a module we keep every method individually and may need to
7017 // update hasMoreThanOneDecl as we add the methods.
7018 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7019 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007020}
7021
7022void ASTReader::ReadKnownNamespaces(
7023 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7024 Namespaces.clear();
7025
7026 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7027 if (NamespaceDecl *Namespace
7028 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7029 Namespaces.push_back(Namespace);
7030 }
7031}
7032
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007033void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007034 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007035 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7036 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007037 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007038 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007039 Undefined.insert(std::make_pair(D, Loc));
7040 }
7041}
Nick Lewycky8334af82013-01-26 00:35:08 +00007042
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007043void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7044 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7045 Exprs) {
7046 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7047 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7048 uint64_t Count = DelayedDeleteExprs[Idx++];
7049 for (uint64_t C = 0; C < Count; ++C) {
7050 SourceLocation DeleteLoc =
7051 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7052 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7053 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7054 }
7055 }
7056}
7057
Guy Benyei11169dd2012-12-18 14:30:41 +00007058void ASTReader::ReadTentativeDefinitions(
7059 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7060 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7061 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7062 if (Var)
7063 TentativeDefs.push_back(Var);
7064 }
7065 TentativeDefinitions.clear();
7066}
7067
7068void ASTReader::ReadUnusedFileScopedDecls(
7069 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7070 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7071 DeclaratorDecl *D
7072 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7073 if (D)
7074 Decls.push_back(D);
7075 }
7076 UnusedFileScopedDecls.clear();
7077}
7078
7079void ASTReader::ReadDelegatingConstructors(
7080 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7081 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7082 CXXConstructorDecl *D
7083 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7084 if (D)
7085 Decls.push_back(D);
7086 }
7087 DelegatingCtorDecls.clear();
7088}
7089
7090void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7091 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7092 TypedefNameDecl *D
7093 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7094 if (D)
7095 Decls.push_back(D);
7096 }
7097 ExtVectorDecls.clear();
7098}
7099
Nico Weber72889432014-09-06 01:25:55 +00007100void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7101 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7102 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7103 ++I) {
7104 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7105 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7106 if (D)
7107 Decls.insert(D);
7108 }
7109 UnusedLocalTypedefNameCandidates.clear();
7110}
7111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112void ASTReader::ReadReferencedSelectors(
7113 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7114 if (ReferencedSelectorsData.empty())
7115 return;
7116
7117 // If there are @selector references added them to its pool. This is for
7118 // implementation of -Wselector.
7119 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7120 unsigned I = 0;
7121 while (I < DataSize) {
7122 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7123 SourceLocation SelLoc
7124 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7125 Sels.push_back(std::make_pair(Sel, SelLoc));
7126 }
7127 ReferencedSelectorsData.clear();
7128}
7129
7130void ASTReader::ReadWeakUndeclaredIdentifiers(
7131 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7132 if (WeakUndeclaredIdentifiers.empty())
7133 return;
7134
7135 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7136 IdentifierInfo *WeakId
7137 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7138 IdentifierInfo *AliasId
7139 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7140 SourceLocation Loc
7141 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7142 bool Used = WeakUndeclaredIdentifiers[I++];
7143 WeakInfo WI(AliasId, Loc);
7144 WI.setUsed(Used);
7145 WeakIDs.push_back(std::make_pair(WeakId, WI));
7146 }
7147 WeakUndeclaredIdentifiers.clear();
7148}
7149
7150void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7151 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7152 ExternalVTableUse VT;
7153 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7154 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7155 VT.DefinitionRequired = VTableUses[Idx++];
7156 VTables.push_back(VT);
7157 }
7158
7159 VTableUses.clear();
7160}
7161
7162void ASTReader::ReadPendingInstantiations(
7163 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7164 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7165 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7166 SourceLocation Loc
7167 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7168
7169 Pending.push_back(std::make_pair(D, Loc));
7170 }
7171 PendingInstantiations.clear();
7172}
7173
Richard Smithe40f2ba2013-08-07 21:41:30 +00007174void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007175 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007176 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7177 /* In loop */) {
7178 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7179
7180 LateParsedTemplate *LT = new LateParsedTemplate;
7181 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7182
7183 ModuleFile *F = getOwningModuleFile(LT->D);
7184 assert(F && "No module");
7185
7186 unsigned TokN = LateParsedTemplates[Idx++];
7187 LT->Toks.reserve(TokN);
7188 for (unsigned T = 0; T < TokN; ++T)
7189 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7190
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007191 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007192 }
7193
7194 LateParsedTemplates.clear();
7195}
7196
Guy Benyei11169dd2012-12-18 14:30:41 +00007197void ASTReader::LoadSelector(Selector Sel) {
7198 // It would be complicated to avoid reading the methods anyway. So don't.
7199 ReadMethodPool(Sel);
7200}
7201
7202void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7203 assert(ID && "Non-zero identifier ID required");
7204 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7205 IdentifiersLoaded[ID - 1] = II;
7206 if (DeserializationListener)
7207 DeserializationListener->IdentifierRead(ID, II);
7208}
7209
7210/// \brief Set the globally-visible declarations associated with the given
7211/// identifier.
7212///
7213/// If the AST reader is currently in a state where the given declaration IDs
7214/// cannot safely be resolved, they are queued until it is safe to resolve
7215/// them.
7216///
7217/// \param II an IdentifierInfo that refers to one or more globally-visible
7218/// declarations.
7219///
7220/// \param DeclIDs the set of declaration IDs with the name @p II that are
7221/// visible at global scope.
7222///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007223/// \param Decls if non-null, this vector will be populated with the set of
7224/// deserialized declarations. These declarations will not be pushed into
7225/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007226void
7227ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7228 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007229 SmallVectorImpl<Decl *> *Decls) {
7230 if (NumCurrentElementsDeserializing && !Decls) {
7231 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 return;
7233 }
7234
7235 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007236 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 // Queue this declaration so that it will be added to the
7238 // translation unit scope and identifier's declaration chain
7239 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007240 PreloadedDeclIDs.push_back(DeclIDs[I]);
7241 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007243
7244 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7245
7246 // If we're simply supposed to record the declarations, do so now.
7247 if (Decls) {
7248 Decls->push_back(D);
7249 continue;
7250 }
7251
7252 // Introduce this declaration into the translation-unit scope
7253 // and add it to the declaration chain for this identifier, so
7254 // that (unqualified) name lookup will find it.
7255 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007256 }
7257}
7258
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007259IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007261 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007262
7263 if (IdentifiersLoaded.empty()) {
7264 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007265 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 }
7267
7268 ID -= 1;
7269 if (!IdentifiersLoaded[ID]) {
7270 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7271 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7272 ModuleFile *M = I->second;
7273 unsigned Index = ID - M->BaseIdentifierID;
7274 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7275
7276 // All of the strings in the AST file are preceded by a 16-bit length.
7277 // Extract that 16-bit length to avoid having to execute strlen().
7278 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7279 // unsigned integers. This is important to avoid integer overflow when
7280 // we cast them to 'unsigned'.
7281 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7282 unsigned StrLen = (((unsigned) StrLenPtr[0])
7283 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007284 IdentifiersLoaded[ID]
7285 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007286 if (DeserializationListener)
7287 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7288 }
7289
7290 return IdentifiersLoaded[ID];
7291}
7292
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007293IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7294 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007295}
7296
7297IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7298 if (LocalID < NUM_PREDEF_IDENT_IDS)
7299 return LocalID;
7300
7301 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7302 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7303 assert(I != M.IdentifierRemap.end()
7304 && "Invalid index into identifier index remap");
7305
7306 return LocalID + I->second;
7307}
7308
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007309MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007311 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007312
7313 if (MacrosLoaded.empty()) {
7314 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007315 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007316 }
7317
7318 ID -= NUM_PREDEF_MACRO_IDS;
7319 if (!MacrosLoaded[ID]) {
7320 GlobalMacroMapType::iterator I
7321 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7322 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7323 ModuleFile *M = I->second;
7324 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007325 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7326
7327 if (DeserializationListener)
7328 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7329 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007330 }
7331
7332 return MacrosLoaded[ID];
7333}
7334
7335MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7336 if (LocalID < NUM_PREDEF_MACRO_IDS)
7337 return LocalID;
7338
7339 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7340 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7341 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7342
7343 return LocalID + I->second;
7344}
7345
7346serialization::SubmoduleID
7347ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7348 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7349 return LocalID;
7350
7351 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7352 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7353 assert(I != M.SubmoduleRemap.end()
7354 && "Invalid index into submodule index remap");
7355
7356 return LocalID + I->second;
7357}
7358
7359Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7360 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7361 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007362 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007363 }
7364
7365 if (GlobalID > SubmodulesLoaded.size()) {
7366 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007367 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007368 }
7369
7370 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7371}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007372
7373Module *ASTReader::getModule(unsigned ID) {
7374 return getSubmodule(ID);
7375}
7376
Richard Smithd88a7f12015-09-01 20:35:42 +00007377ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7378 if (ID & 1) {
7379 // It's a module, look it up by submodule ID.
7380 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7381 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7382 } else {
7383 // It's a prefix (preamble, PCH, ...). Look it up by index.
7384 unsigned IndexFromEnd = ID >> 1;
7385 assert(IndexFromEnd && "got reference to unknown module file");
7386 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7387 }
7388}
7389
7390unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7391 if (!F)
7392 return 1;
7393
7394 // For a file representing a module, use the submodule ID of the top-level
7395 // module as the file ID. For any other kind of file, the number of such
7396 // files loaded beforehand will be the same on reload.
7397 // FIXME: Is this true even if we have an explicit module file and a PCH?
7398 if (F->isModule())
7399 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7400
7401 auto PCHModules = getModuleManager().pch_modules();
7402 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7403 assert(I != PCHModules.end() && "emitting reference to unknown file");
7404 return (I - PCHModules.end()) << 1;
7405}
7406
Adrian Prantl15bcf702015-06-30 17:39:43 +00007407llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7408ASTReader::getSourceDescriptor(unsigned ID) {
7409 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007410 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007411
7412 // If there is only a single PCH, return it instead.
7413 // Chained PCH are not suported.
7414 if (ModuleMgr.size() == 1) {
7415 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantlc6458d62015-09-19 00:10:32 +00007416 return ASTReader::ASTSourceDescriptor(
7417 MF.OriginalSourceFileName, MF.OriginalDir, MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007418 }
7419 return None;
7420}
7421
Guy Benyei11169dd2012-12-18 14:30:41 +00007422Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7423 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7424}
7425
7426Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7427 if (ID == 0)
7428 return Selector();
7429
7430 if (ID > SelectorsLoaded.size()) {
7431 Error("selector ID out of range in AST file");
7432 return Selector();
7433 }
7434
Craig Toppera13603a2014-05-22 05:54:18 +00007435 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007436 // Load this selector from the selector table.
7437 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7438 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7439 ModuleFile &M = *I->second;
7440 ASTSelectorLookupTrait Trait(*this, M);
7441 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7442 SelectorsLoaded[ID - 1] =
7443 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7444 if (DeserializationListener)
7445 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7446 }
7447
7448 return SelectorsLoaded[ID - 1];
7449}
7450
7451Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7452 return DecodeSelector(ID);
7453}
7454
7455uint32_t ASTReader::GetNumExternalSelectors() {
7456 // ID 0 (the null selector) is considered an external selector.
7457 return getTotalNumSelectors() + 1;
7458}
7459
7460serialization::SelectorID
7461ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7462 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7463 return LocalID;
7464
7465 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7466 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7467 assert(I != M.SelectorRemap.end()
7468 && "Invalid index into selector index remap");
7469
7470 return LocalID + I->second;
7471}
7472
7473DeclarationName
7474ASTReader::ReadDeclarationName(ModuleFile &F,
7475 const RecordData &Record, unsigned &Idx) {
7476 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7477 switch (Kind) {
7478 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007479 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007480
7481 case DeclarationName::ObjCZeroArgSelector:
7482 case DeclarationName::ObjCOneArgSelector:
7483 case DeclarationName::ObjCMultiArgSelector:
7484 return DeclarationName(ReadSelector(F, Record, Idx));
7485
7486 case DeclarationName::CXXConstructorName:
7487 return Context.DeclarationNames.getCXXConstructorName(
7488 Context.getCanonicalType(readType(F, Record, Idx)));
7489
7490 case DeclarationName::CXXDestructorName:
7491 return Context.DeclarationNames.getCXXDestructorName(
7492 Context.getCanonicalType(readType(F, Record, Idx)));
7493
7494 case DeclarationName::CXXConversionFunctionName:
7495 return Context.DeclarationNames.getCXXConversionFunctionName(
7496 Context.getCanonicalType(readType(F, Record, Idx)));
7497
7498 case DeclarationName::CXXOperatorName:
7499 return Context.DeclarationNames.getCXXOperatorName(
7500 (OverloadedOperatorKind)Record[Idx++]);
7501
7502 case DeclarationName::CXXLiteralOperatorName:
7503 return Context.DeclarationNames.getCXXLiteralOperatorName(
7504 GetIdentifierInfo(F, Record, Idx));
7505
7506 case DeclarationName::CXXUsingDirective:
7507 return DeclarationName::getUsingDirectiveName();
7508 }
7509
7510 llvm_unreachable("Invalid NameKind!");
7511}
7512
7513void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7514 DeclarationNameLoc &DNLoc,
7515 DeclarationName Name,
7516 const RecordData &Record, unsigned &Idx) {
7517 switch (Name.getNameKind()) {
7518 case DeclarationName::CXXConstructorName:
7519 case DeclarationName::CXXDestructorName:
7520 case DeclarationName::CXXConversionFunctionName:
7521 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7522 break;
7523
7524 case DeclarationName::CXXOperatorName:
7525 DNLoc.CXXOperatorName.BeginOpNameLoc
7526 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7527 DNLoc.CXXOperatorName.EndOpNameLoc
7528 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7529 break;
7530
7531 case DeclarationName::CXXLiteralOperatorName:
7532 DNLoc.CXXLiteralOperatorName.OpNameLoc
7533 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7534 break;
7535
7536 case DeclarationName::Identifier:
7537 case DeclarationName::ObjCZeroArgSelector:
7538 case DeclarationName::ObjCOneArgSelector:
7539 case DeclarationName::ObjCMultiArgSelector:
7540 case DeclarationName::CXXUsingDirective:
7541 break;
7542 }
7543}
7544
7545void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7546 DeclarationNameInfo &NameInfo,
7547 const RecordData &Record, unsigned &Idx) {
7548 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7549 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7550 DeclarationNameLoc DNLoc;
7551 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7552 NameInfo.setInfo(DNLoc);
7553}
7554
7555void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7556 const RecordData &Record, unsigned &Idx) {
7557 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7558 unsigned NumTPLists = Record[Idx++];
7559 Info.NumTemplParamLists = NumTPLists;
7560 if (NumTPLists) {
7561 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7562 for (unsigned i=0; i != NumTPLists; ++i)
7563 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7564 }
7565}
7566
7567TemplateName
7568ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7569 unsigned &Idx) {
7570 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7571 switch (Kind) {
7572 case TemplateName::Template:
7573 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7574
7575 case TemplateName::OverloadedTemplate: {
7576 unsigned size = Record[Idx++];
7577 UnresolvedSet<8> Decls;
7578 while (size--)
7579 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7580
7581 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7582 }
7583
7584 case TemplateName::QualifiedTemplate: {
7585 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7586 bool hasTemplKeyword = Record[Idx++];
7587 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7588 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7589 }
7590
7591 case TemplateName::DependentTemplate: {
7592 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7593 if (Record[Idx++]) // isIdentifier
7594 return Context.getDependentTemplateName(NNS,
7595 GetIdentifierInfo(F, Record,
7596 Idx));
7597 return Context.getDependentTemplateName(NNS,
7598 (OverloadedOperatorKind)Record[Idx++]);
7599 }
7600
7601 case TemplateName::SubstTemplateTemplateParm: {
7602 TemplateTemplateParmDecl *param
7603 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7604 if (!param) return TemplateName();
7605 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7606 return Context.getSubstTemplateTemplateParm(param, replacement);
7607 }
7608
7609 case TemplateName::SubstTemplateTemplateParmPack: {
7610 TemplateTemplateParmDecl *Param
7611 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7612 if (!Param)
7613 return TemplateName();
7614
7615 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7616 if (ArgPack.getKind() != TemplateArgument::Pack)
7617 return TemplateName();
7618
7619 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7620 }
7621 }
7622
7623 llvm_unreachable("Unhandled template name kind!");
7624}
7625
Richard Smith2bb3c342015-08-09 01:05:31 +00007626TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7627 const RecordData &Record,
7628 unsigned &Idx,
7629 bool Canonicalize) {
7630 if (Canonicalize) {
7631 // The caller wants a canonical template argument. Sometimes the AST only
7632 // wants template arguments in canonical form (particularly as the template
7633 // argument lists of template specializations) so ensure we preserve that
7634 // canonical form across serialization.
7635 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7636 return Context.getCanonicalTemplateArgument(Arg);
7637 }
7638
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7640 switch (Kind) {
7641 case TemplateArgument::Null:
7642 return TemplateArgument();
7643 case TemplateArgument::Type:
7644 return TemplateArgument(readType(F, Record, Idx));
7645 case TemplateArgument::Declaration: {
7646 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007647 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 }
7649 case TemplateArgument::NullPtr:
7650 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7651 case TemplateArgument::Integral: {
7652 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7653 QualType T = readType(F, Record, Idx);
7654 return TemplateArgument(Context, Value, T);
7655 }
7656 case TemplateArgument::Template:
7657 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7658 case TemplateArgument::TemplateExpansion: {
7659 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007660 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007661 if (unsigned NumExpansions = Record[Idx++])
7662 NumTemplateExpansions = NumExpansions - 1;
7663 return TemplateArgument(Name, NumTemplateExpansions);
7664 }
7665 case TemplateArgument::Expression:
7666 return TemplateArgument(ReadExpr(F));
7667 case TemplateArgument::Pack: {
7668 unsigned NumArgs = Record[Idx++];
7669 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7670 for (unsigned I = 0; I != NumArgs; ++I)
7671 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007672 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 }
7674 }
7675
7676 llvm_unreachable("Unhandled template argument kind!");
7677}
7678
7679TemplateParameterList *
7680ASTReader::ReadTemplateParameterList(ModuleFile &F,
7681 const RecordData &Record, unsigned &Idx) {
7682 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7683 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7684 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7685
7686 unsigned NumParams = Record[Idx++];
7687 SmallVector<NamedDecl *, 16> Params;
7688 Params.reserve(NumParams);
7689 while (NumParams--)
7690 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7691
7692 TemplateParameterList* TemplateParams =
7693 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7694 Params.data(), Params.size(), RAngleLoc);
7695 return TemplateParams;
7696}
7697
7698void
7699ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007700ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007702 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007703 unsigned NumTemplateArgs = Record[Idx++];
7704 TemplArgs.reserve(NumTemplateArgs);
7705 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007706 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007707}
7708
7709/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007710void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 const RecordData &Record, unsigned &Idx) {
7712 unsigned NumDecls = Record[Idx++];
7713 Set.reserve(Context, NumDecls);
7714 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007715 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007717 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 }
7719}
7720
7721CXXBaseSpecifier
7722ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7723 const RecordData &Record, unsigned &Idx) {
7724 bool isVirtual = static_cast<bool>(Record[Idx++]);
7725 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7726 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7727 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7728 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7729 SourceRange Range = ReadSourceRange(F, Record, Idx);
7730 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7731 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7732 EllipsisLoc);
7733 Result.setInheritConstructors(inheritConstructors);
7734 return Result;
7735}
7736
Richard Smithc2bb8182015-03-24 06:36:48 +00007737CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007738ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7739 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007740 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007741 assert(NumInitializers && "wrote ctor initializers but have no inits");
7742 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7743 for (unsigned i = 0; i != NumInitializers; ++i) {
7744 TypeSourceInfo *TInfo = nullptr;
7745 bool IsBaseVirtual = false;
7746 FieldDecl *Member = nullptr;
7747 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
Richard Smithc2bb8182015-03-24 06:36:48 +00007749 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7750 switch (Type) {
7751 case CTOR_INITIALIZER_BASE:
7752 TInfo = GetTypeSourceInfo(F, Record, Idx);
7753 IsBaseVirtual = Record[Idx++];
7754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755
Richard Smithc2bb8182015-03-24 06:36:48 +00007756 case CTOR_INITIALIZER_DELEGATING:
7757 TInfo = GetTypeSourceInfo(F, Record, Idx);
7758 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007759
Richard Smithc2bb8182015-03-24 06:36:48 +00007760 case CTOR_INITIALIZER_MEMBER:
7761 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7762 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007763
Richard Smithc2bb8182015-03-24 06:36:48 +00007764 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7765 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7766 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007768
7769 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7770 Expr *Init = ReadExpr(F);
7771 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7772 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7773 bool IsWritten = Record[Idx++];
7774 unsigned SourceOrderOrNumArrayIndices;
7775 SmallVector<VarDecl *, 8> Indices;
7776 if (IsWritten) {
7777 SourceOrderOrNumArrayIndices = Record[Idx++];
7778 } else {
7779 SourceOrderOrNumArrayIndices = Record[Idx++];
7780 Indices.reserve(SourceOrderOrNumArrayIndices);
7781 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7782 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7783 }
7784
7785 CXXCtorInitializer *BOMInit;
7786 if (Type == CTOR_INITIALIZER_BASE) {
7787 BOMInit = new (Context)
7788 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7789 RParenLoc, MemberOrEllipsisLoc);
7790 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7791 BOMInit = new (Context)
7792 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7793 } else if (IsWritten) {
7794 if (Member)
7795 BOMInit = new (Context) CXXCtorInitializer(
7796 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7797 else
7798 BOMInit = new (Context)
7799 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7800 LParenLoc, Init, RParenLoc);
7801 } else {
7802 if (IndirectMember) {
7803 assert(Indices.empty() && "Indirect field improperly initialized");
7804 BOMInit = new (Context)
7805 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7806 LParenLoc, Init, RParenLoc);
7807 } else {
7808 BOMInit = CXXCtorInitializer::Create(
7809 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7810 Indices.data(), Indices.size());
7811 }
7812 }
7813
7814 if (IsWritten)
7815 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7816 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007817 }
7818
Richard Smithc2bb8182015-03-24 06:36:48 +00007819 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007820}
7821
7822NestedNameSpecifier *
7823ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7824 const RecordData &Record, unsigned &Idx) {
7825 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007826 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 for (unsigned I = 0; I != N; ++I) {
7828 NestedNameSpecifier::SpecifierKind Kind
7829 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7830 switch (Kind) {
7831 case NestedNameSpecifier::Identifier: {
7832 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7833 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7834 break;
7835 }
7836
7837 case NestedNameSpecifier::Namespace: {
7838 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7839 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7840 break;
7841 }
7842
7843 case NestedNameSpecifier::NamespaceAlias: {
7844 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7845 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7846 break;
7847 }
7848
7849 case NestedNameSpecifier::TypeSpec:
7850 case NestedNameSpecifier::TypeSpecWithTemplate: {
7851 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7852 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007853 return nullptr;
7854
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 bool Template = Record[Idx++];
7856 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7857 break;
7858 }
7859
7860 case NestedNameSpecifier::Global: {
7861 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7862 // No associated value, and there can't be a prefix.
7863 break;
7864 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007865
7866 case NestedNameSpecifier::Super: {
7867 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7868 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7869 break;
7870 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 }
7872 Prev = NNS;
7873 }
7874 return NNS;
7875}
7876
7877NestedNameSpecifierLoc
7878ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7879 unsigned &Idx) {
7880 unsigned N = Record[Idx++];
7881 NestedNameSpecifierLocBuilder Builder;
7882 for (unsigned I = 0; I != N; ++I) {
7883 NestedNameSpecifier::SpecifierKind Kind
7884 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7885 switch (Kind) {
7886 case NestedNameSpecifier::Identifier: {
7887 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7888 SourceRange Range = ReadSourceRange(F, Record, Idx);
7889 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7890 break;
7891 }
7892
7893 case NestedNameSpecifier::Namespace: {
7894 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7895 SourceRange Range = ReadSourceRange(F, Record, Idx);
7896 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7897 break;
7898 }
7899
7900 case NestedNameSpecifier::NamespaceAlias: {
7901 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7902 SourceRange Range = ReadSourceRange(F, Record, Idx);
7903 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7904 break;
7905 }
7906
7907 case NestedNameSpecifier::TypeSpec:
7908 case NestedNameSpecifier::TypeSpecWithTemplate: {
7909 bool Template = Record[Idx++];
7910 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7911 if (!T)
7912 return NestedNameSpecifierLoc();
7913 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7914
7915 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7916 Builder.Extend(Context,
7917 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7918 T->getTypeLoc(), ColonColonLoc);
7919 break;
7920 }
7921
7922 case NestedNameSpecifier::Global: {
7923 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7924 Builder.MakeGlobal(Context, ColonColonLoc);
7925 break;
7926 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007927
7928 case NestedNameSpecifier::Super: {
7929 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7930 SourceRange Range = ReadSourceRange(F, Record, Idx);
7931 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7932 break;
7933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 }
7935 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007936
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 return Builder.getWithLocInContext(Context);
7938}
7939
7940SourceRange
7941ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7942 unsigned &Idx) {
7943 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7944 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7945 return SourceRange(beg, end);
7946}
7947
7948/// \brief Read an integral value
7949llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7950 unsigned BitWidth = Record[Idx++];
7951 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7952 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7953 Idx += NumWords;
7954 return Result;
7955}
7956
7957/// \brief Read a signed integral value
7958llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7959 bool isUnsigned = Record[Idx++];
7960 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7961}
7962
7963/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007964llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7965 const llvm::fltSemantics &Sem,
7966 unsigned &Idx) {
7967 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007968}
7969
7970// \brief Read a string
7971std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7972 unsigned Len = Record[Idx++];
7973 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7974 Idx += Len;
7975 return Result;
7976}
7977
Richard Smith7ed1bc92014-12-05 22:42:13 +00007978std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7979 unsigned &Idx) {
7980 std::string Filename = ReadString(Record, Idx);
7981 ResolveImportedPath(F, Filename);
7982 return Filename;
7983}
7984
Guy Benyei11169dd2012-12-18 14:30:41 +00007985VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7986 unsigned &Idx) {
7987 unsigned Major = Record[Idx++];
7988 unsigned Minor = Record[Idx++];
7989 unsigned Subminor = Record[Idx++];
7990 if (Minor == 0)
7991 return VersionTuple(Major);
7992 if (Subminor == 0)
7993 return VersionTuple(Major, Minor - 1);
7994 return VersionTuple(Major, Minor - 1, Subminor - 1);
7995}
7996
7997CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7998 const RecordData &Record,
7999 unsigned &Idx) {
8000 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8001 return CXXTemporary::Create(Context, Decl);
8002}
8003
8004DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008005 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008006}
8007
8008DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8009 return Diags.Report(Loc, DiagID);
8010}
8011
8012/// \brief Retrieve the identifier table associated with the
8013/// preprocessor.
8014IdentifierTable &ASTReader::getIdentifierTable() {
8015 return PP.getIdentifierTable();
8016}
8017
8018/// \brief Record that the given ID maps to the given switch-case
8019/// statement.
8020void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008021 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 "Already have a SwitchCase with this ID");
8023 (*CurrSwitchCaseStmts)[ID] = SC;
8024}
8025
8026/// \brief Retrieve the switch-case statement with the given ID.
8027SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008028 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 return (*CurrSwitchCaseStmts)[ID];
8030}
8031
8032void ASTReader::ClearSwitchCaseIDs() {
8033 CurrSwitchCaseStmts->clear();
8034}
8035
8036void ASTReader::ReadComments() {
8037 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008038 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 serialization::ModuleFile *> >::iterator
8040 I = CommentsCursors.begin(),
8041 E = CommentsCursors.end();
8042 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008043 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008044 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 serialization::ModuleFile &F = *I->second;
8046 SavedStreamPosition SavedPosition(Cursor);
8047
8048 RecordData Record;
8049 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008050 llvm::BitstreamEntry Entry =
8051 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008052
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008053 switch (Entry.Kind) {
8054 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8055 case llvm::BitstreamEntry::Error:
8056 Error("malformed block record in AST file");
8057 return;
8058 case llvm::BitstreamEntry::EndBlock:
8059 goto NextCursor;
8060 case llvm::BitstreamEntry::Record:
8061 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 }
8064
8065 // Read a record.
8066 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008067 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 case COMMENTS_RAW_COMMENT: {
8069 unsigned Idx = 0;
8070 SourceRange SR = ReadSourceRange(F, Record, Idx);
8071 RawComment::CommentKind Kind =
8072 (RawComment::CommentKind) Record[Idx++];
8073 bool IsTrailingComment = Record[Idx++];
8074 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008075 Comments.push_back(new (Context) RawComment(
8076 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8077 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 break;
8079 }
8080 }
8081 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008082 NextCursor:
8083 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008085}
8086
Richard Smithcd45dbc2014-04-19 03:48:30 +00008087std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8088 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008089 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008090 return M->getFullModuleName();
8091
8092 // Otherwise, use the name of the top-level module the decl is within.
8093 if (ModuleFile *M = getOwningModuleFile(D))
8094 return M->ModuleName;
8095
8096 // Not from a module.
8097 return "";
8098}
8099
Guy Benyei11169dd2012-12-18 14:30:41 +00008100void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008101 while (!PendingIdentifierInfos.empty() ||
8102 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008103 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008104 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 // If any identifiers with corresponding top-level declarations have
8106 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008107 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8108 TopLevelDeclsMap;
8109 TopLevelDeclsMap TopLevelDecls;
8110
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008112 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008113 SmallVector<uint32_t, 4> DeclIDs =
8114 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008115 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008116
8117 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008119
Richard Smith851072e2014-05-19 20:59:20 +00008120 // For each decl chain that we wanted to complete while deserializing, mark
8121 // it as "still needs to be completed".
8122 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8123 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8124 }
8125 PendingIncompleteDeclChains.clear();
8126
Guy Benyei11169dd2012-12-18 14:30:41 +00008127 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008128 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008129 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 PendingDeclChains.clear();
8131
Douglas Gregor6168bd22013-02-18 15:53:43 +00008132 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008133 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8134 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008135 IdentifierInfo *II = TLD->first;
8136 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008137 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008138 }
8139 }
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 // Load any pending macro definitions.
8142 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008143 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8144 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8145 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8146 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008147 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008148 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008149 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008150 if (Info.M->Kind != MK_ImplicitModule &&
8151 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008152 resolvePendingMacro(II, Info);
8153 }
8154 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008155 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008156 ++IDIdx) {
8157 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008158 if (Info.M->Kind == MK_ImplicitModule ||
8159 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008160 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 }
8162 }
8163 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008164
8165 // Wire up the DeclContexts for Decls that we delayed setting until
8166 // recursive loading is completed.
8167 while (!PendingDeclContextInfos.empty()) {
8168 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8169 PendingDeclContextInfos.pop_front();
8170 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8171 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8172 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8173 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008174
Richard Smithd1c46742014-04-30 02:24:17 +00008175 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008176 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008177 auto Update = PendingUpdateRecords.pop_back_val();
8178 ReadingKindTracker ReadingKind(Read_Decl, *this);
8179 loadDeclUpdateRecords(Update.first, Update.second);
8180 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 }
Richard Smith8a639892015-01-24 01:07:20 +00008182
8183 // At this point, all update records for loaded decls are in place, so any
8184 // fake class definitions should have become real.
8185 assert(PendingFakeDefinitionData.empty() &&
8186 "faked up a class definition but never saw the real one");
8187
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 // If we deserialized any C++ or Objective-C class definitions, any
8189 // Objective-C protocol definitions, or any redeclarable templates, make sure
8190 // that all redeclarations point to the definitions. Note that this can only
8191 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008192 for (Decl *D : PendingDefinitions) {
8193 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008194 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 // Make sure that the TagType points at the definition.
8196 const_cast<TagType*>(TagT)->decl = TD;
8197 }
Richard Smith8ce51082015-03-11 01:44:51 +00008198
Craig Topperc6914d02014-08-25 04:15:02 +00008199 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008200 for (auto *R = getMostRecentExistingDecl(RD); R;
8201 R = R->getPreviousDecl()) {
8202 assert((R == D) ==
8203 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008204 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008205 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 }
8208
8209 continue;
8210 }
Richard Smith8ce51082015-03-11 01:44:51 +00008211
Craig Topperc6914d02014-08-25 04:15:02 +00008212 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 // Make sure that the ObjCInterfaceType points at the definition.
8214 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8215 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008216
8217 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8218 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8219
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 continue;
8221 }
Richard Smith8ce51082015-03-11 01:44:51 +00008222
Craig Topperc6914d02014-08-25 04:15:02 +00008223 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008224 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8225 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8226
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 continue;
8228 }
Richard Smith8ce51082015-03-11 01:44:51 +00008229
Craig Topperc6914d02014-08-25 04:15:02 +00008230 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008231 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8232 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 }
8234 PendingDefinitions.clear();
8235
8236 // Load the bodies of any functions or methods we've encountered. We do
8237 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008238 // have been fully wired up (hasBody relies on this).
8239 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8241 PBEnd = PendingBodies.end();
8242 PB != PBEnd; ++PB) {
8243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8244 // FIXME: Check for =delete/=default?
8245 // FIXME: Complain about ODR violations here?
8246 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8247 FD->setLazyBody(PB->second);
8248 continue;
8249 }
8250
8251 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8252 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8253 MD->setLazyBody(PB->second);
8254 }
8255 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008256
8257 // Do some cleanup.
8258 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8259 getContext().deduplicateMergedDefinitonsFor(ND);
8260 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008261}
8262
8263void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008264 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8265 return;
8266
Richard Smitha0ce9c42014-07-29 23:23:27 +00008267 // Trigger the import of the full definition of each class that had any
8268 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008269 // These updates may in turn find and diagnose some ODR failures, so take
8270 // ownership of the set first.
8271 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8272 PendingOdrMergeFailures.clear();
8273 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008274 Merge.first->buildLookup();
8275 Merge.first->decls_begin();
8276 Merge.first->bases_begin();
8277 Merge.first->vbases_begin();
8278 for (auto *RD : Merge.second) {
8279 RD->decls_begin();
8280 RD->bases_begin();
8281 RD->vbases_begin();
8282 }
8283 }
8284
8285 // For each declaration from a merged context, check that the canonical
8286 // definition of that context also contains a declaration of the same
8287 // entity.
8288 //
8289 // Caution: this loop does things that might invalidate iterators into
8290 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8291 while (!PendingOdrMergeChecks.empty()) {
8292 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8293
8294 // FIXME: Skip over implicit declarations for now. This matters for things
8295 // like implicitly-declared special member functions. This isn't entirely
8296 // correct; we can end up with multiple unmerged declarations of the same
8297 // implicit entity.
8298 if (D->isImplicit())
8299 continue;
8300
8301 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008302
8303 bool Found = false;
8304 const Decl *DCanon = D->getCanonicalDecl();
8305
Richard Smith01bdb7a2014-08-28 05:44:07 +00008306 for (auto RI : D->redecls()) {
8307 if (RI->getLexicalDeclContext() == CanonDef) {
8308 Found = true;
8309 break;
8310 }
8311 }
8312 if (Found)
8313 continue;
8314
Richard Smith0f4e2c42015-08-06 04:23:48 +00008315 // Quick check failed, time to do the slow thing. Note, we can't just
8316 // look up the name of D in CanonDef here, because the member that is
8317 // in CanonDef might not be found by name lookup (it might have been
8318 // replaced by a more recent declaration in the lookup table), and we
8319 // can't necessarily find it in the redeclaration chain because it might
8320 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008321 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008322 for (auto *CanonMember : CanonDef->decls()) {
8323 if (CanonMember->getCanonicalDecl() == DCanon) {
8324 // This can happen if the declaration is merely mergeable and not
8325 // actually redeclarable (we looked for redeclarations earlier).
8326 //
8327 // FIXME: We should be able to detect this more efficiently, without
8328 // pulling in all of the members of CanonDef.
8329 Found = true;
8330 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008331 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008332 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8333 if (ND->getDeclName() == D->getDeclName())
8334 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008335 }
8336
8337 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008338 // The AST doesn't like TagDecls becoming invalid after they've been
8339 // completed. We only really need to mark FieldDecls as invalid here.
8340 if (!isa<TagDecl>(D))
8341 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008342
8343 // Ensure we don't accidentally recursively enter deserialization while
8344 // we're producing our diagnostic.
8345 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008346
8347 std::string CanonDefModule =
8348 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8349 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8350 << D << getOwningModuleNameForDiagnostic(D)
8351 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8352
8353 if (Candidates.empty())
8354 Diag(cast<Decl>(CanonDef)->getLocation(),
8355 diag::note_module_odr_violation_no_possible_decls) << D;
8356 else {
8357 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8358 Diag(Candidates[I]->getLocation(),
8359 diag::note_module_odr_violation_possible_decl)
8360 << Candidates[I];
8361 }
8362
8363 DiagnosedOdrMergeFailures.insert(CanonDef);
8364 }
8365 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008366
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008367 if (OdrMergeFailures.empty())
8368 return;
8369
8370 // Ensure we don't accidentally recursively enter deserialization while
8371 // we're producing our diagnostics.
8372 Deserializing RecursionGuard(this);
8373
Richard Smithcd45dbc2014-04-19 03:48:30 +00008374 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008375 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008376 // If we've already pointed out a specific problem with this class, don't
8377 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008378 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008379 continue;
8380
8381 bool Diagnosed = false;
8382 for (auto *RD : Merge.second) {
8383 // Multiple different declarations got merged together; tell the user
8384 // where they came from.
8385 if (Merge.first != RD) {
8386 // FIXME: Walk the definition, figure out what's different,
8387 // and diagnose that.
8388 if (!Diagnosed) {
8389 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8390 Diag(Merge.first->getLocation(),
8391 diag::err_module_odr_violation_different_definitions)
8392 << Merge.first << Module.empty() << Module;
8393 Diagnosed = true;
8394 }
8395
8396 Diag(RD->getLocation(),
8397 diag::note_module_odr_violation_different_definitions)
8398 << getOwningModuleNameForDiagnostic(RD);
8399 }
8400 }
8401
8402 if (!Diagnosed) {
8403 // All definitions are updates to the same declaration. This happens if a
8404 // module instantiates the declaration of a class template specialization
8405 // and two or more other modules instantiate its definition.
8406 //
8407 // FIXME: Indicate which modules had instantiations of this definition.
8408 // FIXME: How can this even happen?
8409 Diag(Merge.first->getLocation(),
8410 diag::err_module_odr_violation_different_instantiations)
8411 << Merge.first;
8412 }
8413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008414}
8415
Richard Smithce18a182015-07-14 00:26:00 +00008416void ASTReader::StartedDeserializing() {
8417 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8418 ReadTimer->startTimer();
8419}
8420
Guy Benyei11169dd2012-12-18 14:30:41 +00008421void ASTReader::FinishedDeserializing() {
8422 assert(NumCurrentElementsDeserializing &&
8423 "FinishedDeserializing not paired with StartedDeserializing");
8424 if (NumCurrentElementsDeserializing == 1) {
8425 // We decrease NumCurrentElementsDeserializing only after pending actions
8426 // are finished, to avoid recursively re-calling finishPendingActions().
8427 finishPendingActions();
8428 }
8429 --NumCurrentElementsDeserializing;
8430
Richard Smitha0ce9c42014-07-29 23:23:27 +00008431 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008432 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008433 while (!PendingExceptionSpecUpdates.empty()) {
8434 auto Updates = std::move(PendingExceptionSpecUpdates);
8435 PendingExceptionSpecUpdates.clear();
8436 for (auto Update : Updates) {
8437 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008438 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008439 if (auto *Listener = Context.getASTMutationListener())
8440 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008441 for (auto *Redecl : Update.second->redecls())
8442 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008443 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008444 }
8445
Richard Smithce18a182015-07-14 00:26:00 +00008446 if (ReadTimer)
8447 ReadTimer->stopTimer();
8448
Richard Smith0f4e2c42015-08-06 04:23:48 +00008449 diagnoseOdrViolations();
8450
Richard Smith04d05b52014-03-23 00:27:18 +00008451 // We are not in recursive loading, so it's safe to pass the "interesting"
8452 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008453 if (Consumer)
8454 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008455 }
8456}
8457
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008458void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008459 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8460 // Remove any fake results before adding any real ones.
8461 auto It = PendingFakeLookupResults.find(II);
8462 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008463 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008464 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008465 // FIXME: this works around module+PCH performance issue.
8466 // Rather than erase the result from the map, which is O(n), just clear
8467 // the vector of NamedDecls.
8468 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008469 }
8470 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008471
8472 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8473 SemaObj->TUScope->AddDecl(D);
8474 } else if (SemaObj->TUScope) {
8475 // Adding the decl to IdResolver may have failed because it was already in
8476 // (even though it was not added in scope). If it is already in, make sure
8477 // it gets in the scope as well.
8478 if (std::find(SemaObj->IdResolver.begin(Name),
8479 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8480 SemaObj->TUScope->AddDecl(D);
8481 }
8482}
8483
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008484ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008485 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008486 StringRef isysroot, bool DisableValidation,
8487 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008488 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008489 bool UseGlobalIndex,
8490 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008491 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008492 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008493 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008494 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008495 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008496 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008497 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008498 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8499 AllowConfigurationMismatch(AllowConfigurationMismatch),
8500 ValidateSystemInputs(ValidateSystemInputs),
8501 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008502 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8503 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8504 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8505 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008506 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8507 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8508 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8509 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8510 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8511 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008512 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008513 SourceMgr.setExternalSLocEntrySource(this);
8514}
8515
8516ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008517 if (OwnsDeserializationListener)
8518 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008519}