blob: b2f59d1fa6c91601452387be3571506eddd1af57 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000051#include "llvm/Support/Compression.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000057#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000059#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000061#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000062
63using namespace clang;
64using namespace clang::serialization;
65using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000066using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Ben Langmuircb69b572014-03-07 06:40:32 +000068
69//===----------------------------------------------------------------------===//
70// ChainedASTReaderListener implementation
71//===----------------------------------------------------------------------===//
72
73bool
74ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
75 return First->ReadFullVersionInformation(FullVersion) ||
76 Second->ReadFullVersionInformation(FullVersion);
77}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000078void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
79 First->ReadModuleName(ModuleName);
80 Second->ReadModuleName(ModuleName);
81}
82void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
83 First->ReadModuleMapFile(ModuleMapPath);
84 Second->ReadModuleMapFile(ModuleMapPath);
85}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000086bool
87ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
88 bool Complain,
89 bool AllowCompatibleDifferences) {
90 return First->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences) ||
92 Second->ReadLanguageOptions(LangOpts, Complain,
93 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000094}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000095bool ChainedASTReaderListener::ReadTargetOptions(
96 const TargetOptions &TargetOpts, bool Complain,
97 bool AllowCompatibleDifferences) {
98 return First->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences) ||
100 Second->ReadTargetOptions(TargetOpts, Complain,
101 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000102}
103bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000104 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000105 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
106 Second->ReadDiagnosticOptions(DiagOpts, Complain);
107}
108bool
109ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
110 bool Complain) {
111 return First->ReadFileSystemOptions(FSOpts, Complain) ||
112 Second->ReadFileSystemOptions(FSOpts, Complain);
113}
114
115bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000116 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
117 bool Complain) {
118 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain) ||
120 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
121 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000122}
123bool ChainedASTReaderListener::ReadPreprocessorOptions(
124 const PreprocessorOptions &PPOpts, bool Complain,
125 std::string &SuggestedPredefines) {
126 return First->ReadPreprocessorOptions(PPOpts, Complain,
127 SuggestedPredefines) ||
128 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
129}
130void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
131 unsigned Value) {
132 First->ReadCounter(M, Value);
133 Second->ReadCounter(M, Value);
134}
135bool ChainedASTReaderListener::needsInputFileVisitation() {
136 return First->needsInputFileVisitation() ||
137 Second->needsInputFileVisitation();
138}
139bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
140 return First->needsSystemInputFileVisitation() ||
141 Second->needsSystemInputFileVisitation();
142}
Richard Smith216a3bd2015-08-13 17:57:10 +0000143void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
144 ModuleKind Kind) {
145 First->visitModuleFile(Filename, Kind);
146 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000147}
Ben Langmuircb69b572014-03-07 06:40:32 +0000148bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000149 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000150 bool isOverridden,
151 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000152 bool Continue = false;
153 if (First->needsInputFileVisitation() &&
154 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000155 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
156 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000157 if (Second->needsInputFileVisitation() &&
158 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000159 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
160 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000161 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000162}
163
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000164void ChainedASTReaderListener::readModuleFileExtension(
165 const ModuleFileExtensionMetadata &Metadata) {
166 First->readModuleFileExtension(Metadata);
167 Second->readModuleFileExtension(Metadata);
168}
169
Guy Benyei11169dd2012-12-18 14:30:41 +0000170//===----------------------------------------------------------------------===//
171// PCH validator implementation
172//===----------------------------------------------------------------------===//
173
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000174ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000175
176/// \brief Compare the given set of language options against an existing set of
177/// language options.
178///
179/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000180/// \param AllowCompatibleDifferences If true, differences between compatible
181/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000182///
183/// \returns true if the languagae options mis-match, false otherwise.
184static bool checkLanguageOptions(const LangOptions &LangOpts,
185 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000186 DiagnosticsEngine *Diags,
187 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000188#define LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_mismatch) \
192 << Description << LangOpts.Name << ExistingLangOpts.Name; \
193 return true; \
194 }
195
196#define VALUE_LANGOPT(Name, Bits, Default, Description) \
197 if (ExistingLangOpts.Name != LangOpts.Name) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
204#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
205 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
206 if (Diags) \
207 Diags->Report(diag::err_pch_langopt_value_mismatch) \
208 << Description; \
209 return true; \
210 }
211
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000212#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
213 if (!AllowCompatibleDifferences) \
214 LANGOPT(Name, Bits, Default, Description)
215
216#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
217 if (!AllowCompatibleDifferences) \
218 ENUM_LANGOPT(Name, Bits, Default, Description)
219
Guy Benyei11169dd2012-12-18 14:30:41 +0000220#define BENIGN_LANGOPT(Name, Bits, Default, Description)
221#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
222#include "clang/Basic/LangOptions.def"
223
Ben Langmuircd98cb72015-06-23 18:20:18 +0000224 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
225 if (Diags)
226 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
227 return true;
228 }
229
Guy Benyei11169dd2012-12-18 14:30:41 +0000230 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
231 if (Diags)
232 Diags->Report(diag::err_pch_langopt_value_mismatch)
233 << "target Objective-C runtime";
234 return true;
235 }
236
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000237 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
238 LangOpts.CommentOpts.BlockCommandNames) {
239 if (Diags)
240 Diags->Report(diag::err_pch_langopt_value_mismatch)
241 << "block command names";
242 return true;
243 }
244
Guy Benyei11169dd2012-12-18 14:30:41 +0000245 return false;
246}
247
248/// \brief Compare the given set of target options against an existing set of
249/// target options.
250///
251/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
252///
253/// \returns true if the target options mis-match, false otherwise.
254static bool checkTargetOptions(const TargetOptions &TargetOpts,
255 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000256 DiagnosticsEngine *Diags,
257 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000258#define CHECK_TARGET_OPT(Field, Name) \
259 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
260 if (Diags) \
261 Diags->Report(diag::err_pch_targetopt_mismatch) \
262 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
263 return true; \
264 }
265
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000266 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000267 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000268 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000269
270 // We can tolerate different CPUs in many cases, notably when one CPU
271 // supports a strict superset of another. When allowing compatible
272 // differences skip this check.
273 if (!AllowCompatibleDifferences)
274 CHECK_TARGET_OPT(CPU, "target CPU");
275
Guy Benyei11169dd2012-12-18 14:30:41 +0000276#undef CHECK_TARGET_OPT
277
278 // Compare feature sets.
279 SmallVector<StringRef, 4> ExistingFeatures(
280 ExistingTargetOpts.FeaturesAsWritten.begin(),
281 ExistingTargetOpts.FeaturesAsWritten.end());
282 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
283 TargetOpts.FeaturesAsWritten.end());
284 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
285 std::sort(ReadFeatures.begin(), ReadFeatures.end());
286
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000287 // We compute the set difference in both directions explicitly so that we can
288 // diagnose the differences differently.
289 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
290 std::set_difference(
291 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
292 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
293 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
294 ExistingFeatures.begin(), ExistingFeatures.end(),
295 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000296
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000297 // If we are allowing compatible differences and the read feature set is
298 // a strict subset of the existing feature set, there is nothing to diagnose.
299 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
300 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000301
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000302 if (Diags) {
303 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000305 << /* is-existing-feature */ false << Feature;
306 for (StringRef Feature : UnmatchedExistingFeatures)
307 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
308 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 }
310
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000311 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314bool
315PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000316 bool Complain,
317 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 const LangOptions &ExistingLangOpts = PP.getLangOpts();
319 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000320 Complain ? &Reader.Diags : nullptr,
321 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000322}
323
324bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000325 bool Complain,
326 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000327 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
328 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000329 Complain ? &Reader.Diags : nullptr,
330 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000331}
332
333namespace {
334 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
335 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000336 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
337 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000338}
339
Ben Langmuirb92de022014-04-29 16:25:26 +0000340static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
341 DiagnosticsEngine &Diags,
342 bool Complain) {
343 typedef DiagnosticsEngine::Level Level;
344
345 // Check current mappings for new -Werror mappings, and the stored mappings
346 // for cases that were explicitly mapped to *not* be errors that are now
347 // errors because of options like -Werror.
348 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
349
350 for (DiagnosticsEngine *MappingSource : MappingSources) {
351 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
352 diag::kind DiagID = DiagIDMappingPair.first;
353 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
354 if (CurLevel < DiagnosticsEngine::Error)
355 continue; // not significant
356 Level StoredLevel =
357 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
358 if (StoredLevel < DiagnosticsEngine::Error) {
359 if (Complain)
360 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
361 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
362 return true;
363 }
364 }
365 }
366
367 return false;
368}
369
Alp Tokerac4e8e52014-06-22 21:58:33 +0000370static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
371 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
372 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
373 return true;
374 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000375}
376
377static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
378 DiagnosticsEngine &Diags,
379 bool IsSystem, bool Complain) {
380 // Top-level options
381 if (IsSystem) {
382 if (Diags.getSuppressSystemWarnings())
383 return false;
384 // If -Wsystem-headers was not enabled before, be conservative
385 if (StoredDiags.getSuppressSystemWarnings()) {
386 if (Complain)
387 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
388 return true;
389 }
390 }
391
392 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
393 if (Complain)
394 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
395 return true;
396 }
397
398 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
399 !StoredDiags.getEnableAllWarnings()) {
400 if (Complain)
401 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
402 return true;
403 }
404
405 if (isExtHandlingFromDiagsError(Diags) &&
406 !isExtHandlingFromDiagsError(StoredDiags)) {
407 if (Complain)
408 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
409 return true;
410 }
411
412 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
413}
414
415bool PCHValidator::ReadDiagnosticOptions(
416 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
417 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
418 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
419 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000420 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000421 // This should never fail, because we would have processed these options
422 // before writing them to an ASTFile.
423 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
424
425 ModuleManager &ModuleMgr = Reader.getModuleManager();
426 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
427
428 // If the original import came from a file explicitly generated by the user,
429 // don't check the diagnostic mappings.
430 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000431 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000432 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
433 // the transitive closure of its imports, since unrelated modules cannot be
434 // imported until after this module finishes validation.
435 ModuleFile *TopImport = *ModuleMgr.rbegin();
436 while (!TopImport->ImportedBy.empty())
437 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000438 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000439 return false;
440
441 StringRef ModuleName = TopImport->ModuleName;
442 assert(!ModuleName.empty() && "diagnostic options read before module name");
443
444 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
445 assert(M && "missing module");
446
447 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
448 // contains the union of their flags.
449 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
450}
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452/// \brief Collect the macro definitions provided by the given preprocessor
453/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000454static void
455collectMacroDefinitions(const PreprocessorOptions &PPOpts,
456 MacroDefinitionsMap &Macros,
457 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
459 StringRef Macro = PPOpts.Macros[I].first;
460 bool IsUndef = PPOpts.Macros[I].second;
461
462 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
463 StringRef MacroName = MacroPair.first;
464 StringRef MacroBody = MacroPair.second;
465
466 // For an #undef'd macro, we only care about the name.
467 if (IsUndef) {
468 if (MacroNames && !Macros.count(MacroName))
469 MacroNames->push_back(MacroName);
470
471 Macros[MacroName] = std::make_pair("", true);
472 continue;
473 }
474
475 // For a #define'd macro, figure out the actual definition.
476 if (MacroName.size() == Macro.size())
477 MacroBody = "1";
478 else {
479 // Note: GCC drops anything following an end-of-line character.
480 StringRef::size_type End = MacroBody.find_first_of("\n\r");
481 MacroBody = MacroBody.substr(0, End);
482 }
483
484 if (MacroNames && !Macros.count(MacroName))
485 MacroNames->push_back(MacroName);
486 Macros[MacroName] = std::make_pair(MacroBody, false);
487 }
488}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000489
Guy Benyei11169dd2012-12-18 14:30:41 +0000490/// \brief Check the preprocessor options deserialized from the control block
491/// against the preprocessor options in an existing preprocessor.
492///
493/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
494static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
495 const PreprocessorOptions &ExistingPPOpts,
496 DiagnosticsEngine *Diags,
497 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000498 std::string &SuggestedPredefines,
499 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 // Check macro definitions.
501 MacroDefinitionsMap ASTFileMacros;
502 collectMacroDefinitions(PPOpts, ASTFileMacros);
503 MacroDefinitionsMap ExistingMacros;
504 SmallVector<StringRef, 4> ExistingMacroNames;
505 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
506
507 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
508 // Dig out the macro definition in the existing preprocessor options.
509 StringRef MacroName = ExistingMacroNames[I];
510 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
511
512 // Check whether we know anything about this macro name or not.
513 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
514 = ASTFileMacros.find(MacroName);
515 if (Known == ASTFileMacros.end()) {
516 // FIXME: Check whether this identifier was referenced anywhere in the
517 // AST file. If so, we should reject the AST file. Unfortunately, this
518 // information isn't in the control block. What shall we do about it?
519
520 if (Existing.second) {
521 SuggestedPredefines += "#undef ";
522 SuggestedPredefines += MacroName.str();
523 SuggestedPredefines += '\n';
524 } else {
525 SuggestedPredefines += "#define ";
526 SuggestedPredefines += MacroName.str();
527 SuggestedPredefines += ' ';
528 SuggestedPredefines += Existing.first.str();
529 SuggestedPredefines += '\n';
530 }
531 continue;
532 }
533
534 // If the macro was defined in one but undef'd in the other, we have a
535 // conflict.
536 if (Existing.second != Known->second.second) {
537 if (Diags) {
538 Diags->Report(diag::err_pch_macro_def_undef)
539 << MacroName << Known->second.second;
540 }
541 return true;
542 }
543
544 // If the macro was #undef'd in both, or if the macro bodies are identical,
545 // it's fine.
546 if (Existing.second || Existing.first == Known->second.first)
547 continue;
548
549 // The macro bodies differ; complain.
550 if (Diags) {
551 Diags->Report(diag::err_pch_macro_def_conflict)
552 << MacroName << Known->second.first << Existing.first;
553 }
554 return true;
555 }
556
557 // Check whether we're using predefines.
558 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
559 if (Diags) {
560 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
561 }
562 return true;
563 }
564
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000565 // Detailed record is important since it is used for the module cache hash.
566 if (LangOpts.Modules &&
567 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
568 if (Diags) {
569 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
570 }
571 return true;
572 }
573
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 // Compute the #include and #include_macros lines we need.
575 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
576 StringRef File = ExistingPPOpts.Includes[I];
577 if (File == ExistingPPOpts.ImplicitPCHInclude)
578 continue;
579
580 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
581 != PPOpts.Includes.end())
582 continue;
583
584 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n";
587 }
588
589 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
590 StringRef File = ExistingPPOpts.MacroIncludes[I];
591 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
592 File)
593 != PPOpts.MacroIncludes.end())
594 continue;
595
596 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000597 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 SuggestedPredefines += "\"\n##\n";
599 }
600
601 return false;
602}
603
604bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
605 bool Complain,
606 std::string &SuggestedPredefines) {
607 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
608
609 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000610 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000612 SuggestedPredefines,
613 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000614}
615
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000616/// Check the header search options deserialized from the control block
617/// against the header search options in an existing preprocessor.
618///
619/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
620static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
621 StringRef SpecificModuleCachePath,
622 StringRef ExistingModuleCachePath,
623 DiagnosticsEngine *Diags,
624 const LangOptions &LangOpts) {
625 if (LangOpts.Modules) {
626 if (SpecificModuleCachePath != ExistingModuleCachePath) {
627 if (Diags)
628 Diags->Report(diag::err_pch_modulecache_mismatch)
629 << SpecificModuleCachePath << ExistingModuleCachePath;
630 return true;
631 }
632 }
633
634 return false;
635}
636
637bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
638 StringRef SpecificModuleCachePath,
639 bool Complain) {
640 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
641 PP.getHeaderSearchInfo().getModuleCachePath(),
642 Complain ? &Reader.Diags : nullptr,
643 PP.getLangOpts());
644}
645
Guy Benyei11169dd2012-12-18 14:30:41 +0000646void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
647 PP.setCounterValue(Value);
648}
649
650//===----------------------------------------------------------------------===//
651// AST reader implementation
652//===----------------------------------------------------------------------===//
653
Nico Weber824285e2014-05-08 04:26:47 +0000654void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
655 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000656 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000657 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000658}
659
660
661
662unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
663 return serialization::ComputeHash(Sel);
664}
665
666
667std::pair<unsigned, unsigned>
668ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000669 using namespace llvm::support;
670 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
671 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000672 return std::make_pair(KeyLen, DataLen);
673}
674
675ASTSelectorLookupTrait::internal_key_type
676ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000677 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000679 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
680 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
681 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000682 if (N == 0)
683 return SelTable.getNullarySelector(FirstII);
684 else if (N == 1)
685 return SelTable.getUnarySelector(FirstII);
686
687 SmallVector<IdentifierInfo *, 16> Args;
688 Args.push_back(FirstII);
689 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000690 Args.push_back(Reader.getLocalIdentifier(
691 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 return SelTable.getSelector(N, Args.data());
694}
695
696ASTSelectorLookupTrait::data_type
697ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
698 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000699 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000700
701 data_type Result;
702
Justin Bogner57ba0b22014-03-28 22:03:24 +0000703 Result.ID = Reader.getGlobalSelectorID(
704 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000705 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
706 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
707 Result.InstanceBits = FullInstanceBits & 0x3;
708 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
709 Result.FactoryBits = FullFactoryBits & 0x3;
710 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
711 unsigned NumInstanceMethods = FullInstanceBits >> 3;
712 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000713
714 // Load instance methods
715 for (unsigned I = 0; I != NumInstanceMethods; ++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.Instance.push_back(Method);
719 }
720
721 // Load factory methods
722 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000723 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
724 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000725 Result.Factory.push_back(Method);
726 }
727
728 return Result;
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
732 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000733}
734
735std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000736ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000737 using namespace llvm::support;
738 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
739 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000740 return std::make_pair(KeyLen, DataLen);
741}
742
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000743ASTIdentifierLookupTraitBase::internal_key_type
744ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000746 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000747}
748
Douglas Gregordcf25082013-02-11 18:16:18 +0000749/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000750static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
751 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000752 return II.hadMacroDefinition() ||
753 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000754 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000755 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000756 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
757 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000758}
759
Richard Smith76c2f2c2015-07-17 20:09:43 +0000760static bool readBit(unsigned &Bits) {
761 bool Value = Bits & 0x1;
762 Bits >>= 1;
763 return Value;
764}
765
Richard Smith79bf9202015-08-24 03:33:22 +0000766IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
767 using namespace llvm::support;
768 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
769 return Reader.getGlobalIdentifierID(F, RawID >> 1);
770}
771
Richard Smitheb4b58f62016-02-05 01:40:54 +0000772static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
773 if (!II.isFromAST()) {
774 II.setIsFromAST();
775 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
776 if (isInterestingIdentifier(Reader, II, IsModule))
777 II.setChangedSinceDeserialization();
778 }
779}
780
Guy Benyei11169dd2012-12-18 14:30:41 +0000781IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
782 const unsigned char* d,
783 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000784 using namespace llvm::support;
785 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000786 bool IsInteresting = RawID & 0x01;
787
788 // Wipe out the "is interesting" bit.
789 RawID = RawID >> 1;
790
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 // Build the IdentifierInfo and link the identifier ID with it.
792 IdentifierInfo *II = KnownII;
793 if (!II) {
794 II = &Reader.getIdentifierTable().getOwn(k);
795 KnownII = II;
796 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000797 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000798 Reader.markIdentifierUpToDate(II);
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
801 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000802 // For uninteresting identifiers, there's nothing else to do. Just notify
803 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 return II;
806 }
807
Justin Bogner57ba0b22014-03-28 22:03:24 +0000808 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
809 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000810 bool CPlusPlusOperatorKeyword = readBit(Bits);
811 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000812 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000813 bool Poisoned = readBit(Bits);
814 bool ExtensionToken = readBit(Bits);
815 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000816
817 assert(Bits == 0 && "Extra bits in the identifier?");
818 DataLen -= 8;
819
Guy Benyei11169dd2012-12-18 14:30:41 +0000820 // Set or check the various bits in the IdentifierInfo structure.
821 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000822 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000823 II->revertTokenIDToIdentifier();
824 if (!F.isModule())
825 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
826 else if (HasRevertedBuiltin && II->getBuiltinID()) {
827 II->revertBuiltin();
828 assert((II->hasRevertedBuiltin() ||
829 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
830 "Incorrect ObjC keyword or builtin ID");
831 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 assert(II->isExtensionToken() == ExtensionToken &&
833 "Incorrect extension token flag");
834 (void)ExtensionToken;
835 if (Poisoned)
836 II->setIsPoisoned(true);
837 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
838 "Incorrect C++ operator keyword flag");
839 (void)CPlusPlusOperatorKeyword;
840
841 // If this identifier is a macro, deserialize the macro
842 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000843 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000844 uint32_t MacroDirectivesOffset =
845 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000846 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000847
Richard Smithd7329392015-04-21 21:46:32 +0000848 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 }
850
851 Reader.SetIdentifierInfo(ID, II);
852
853 // Read all of the declarations visible at global scope with this
854 // name.
855 if (DataLen > 0) {
856 SmallVector<uint32_t, 4> DeclIDs;
857 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000858 DeclIDs.push_back(Reader.getGlobalDeclID(
859 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 Reader.SetGloballyVisibleDecls(II, DeclIDs);
861 }
862
863 return II;
864}
865
Richard Smitha06c7e62015-08-26 23:55:49 +0000866DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
867 : Kind(Name.getNameKind()) {
868 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000870 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 break;
872 case DeclarationName::ObjCZeroArgSelector:
873 case DeclarationName::ObjCOneArgSelector:
874 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000875 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 break;
877 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000878 Data = Name.getCXXOverloadedOperator();
879 break;
880 case DeclarationName::CXXLiteralOperatorName:
881 Data = (uint64_t)Name.getCXXLiteralIdentifier();
882 break;
883 case DeclarationName::CXXConstructorName:
884 case DeclarationName::CXXDestructorName:
885 case DeclarationName::CXXConversionFunctionName:
886 case DeclarationName::CXXUsingDirective:
887 Data = 0;
888 break;
889 }
890}
891
892unsigned DeclarationNameKey::getHash() const {
893 llvm::FoldingSetNodeID ID;
894 ID.AddInteger(Kind);
895
896 switch (Kind) {
897 case DeclarationName::Identifier:
898 case DeclarationName::CXXLiteralOperatorName:
899 ID.AddString(((IdentifierInfo*)Data)->getName());
900 break;
901 case DeclarationName::ObjCZeroArgSelector:
902 case DeclarationName::ObjCOneArgSelector:
903 case DeclarationName::ObjCMultiArgSelector:
904 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
905 break;
906 case DeclarationName::CXXOperatorName:
907 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 break;
909 case DeclarationName::CXXConstructorName:
910 case DeclarationName::CXXDestructorName:
911 case DeclarationName::CXXConversionFunctionName:
912 case DeclarationName::CXXUsingDirective:
913 break;
914 }
915
916 return ID.ComputeHash();
917}
918
Richard Smithd88a7f12015-09-01 20:35:42 +0000919ModuleFile *
920ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
921 using namespace llvm::support;
922 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
923 return Reader.getLocalModuleFile(F, ModuleFileID);
924}
925
Guy Benyei11169dd2012-12-18 14:30:41 +0000926std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000927ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000928 using namespace llvm::support;
929 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
930 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000931 return std::make_pair(KeyLen, DataLen);
932}
933
Richard Smitha06c7e62015-08-26 23:55:49 +0000934ASTDeclContextNameLookupTrait::internal_key_type
935ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000936 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000937
Richard Smitha06c7e62015-08-26 23:55:49 +0000938 auto Kind = (DeclarationName::NameKind)*d++;
939 uint64_t Data;
940 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 break;
945 case DeclarationName::ObjCZeroArgSelector:
946 case DeclarationName::ObjCOneArgSelector:
947 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000948 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000949 (uint64_t)Reader.getLocalSelector(
950 F, endian::readNext<uint32_t, little, unaligned>(
951 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 break;
953 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000954 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 break;
956 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000957 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 break;
960 case DeclarationName::CXXConstructorName:
961 case DeclarationName::CXXDestructorName:
962 case DeclarationName::CXXConversionFunctionName:
963 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000964 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 break;
966 }
967
Richard Smitha06c7e62015-08-26 23:55:49 +0000968 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000969}
970
Richard Smithd88a7f12015-09-01 20:35:42 +0000971void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
972 const unsigned char *d,
973 unsigned DataLen,
974 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000975 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000976 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
977 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
978 Val.insert(Reader.getGlobalDeclID(F, LocalID));
979 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000980}
981
Richard Smith0f4e2c42015-08-06 04:23:48 +0000982bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
983 BitstreamCursor &Cursor,
984 uint64_t Offset,
985 DeclContext *DC) {
986 assert(Offset != 0);
987
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000989 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000990
Richard Smith0f4e2c42015-08-06 04:23:48 +0000991 RecordData Record;
992 StringRef Blob;
993 unsigned Code = Cursor.ReadCode();
994 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
995 if (RecCode != DECL_CONTEXT_LEXICAL) {
996 Error("Expected lexical block");
997 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 }
999
Richard Smith82f8fcd2015-08-06 22:07:25 +00001000 assert(!isa<TranslationUnitDecl>(DC) &&
1001 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001002 // If we are handling a C++ class template instantiation, we can see multiple
1003 // lexical updates for the same record. It's important that we select only one
1004 // of them, so that field numbering works properly. Just pick the first one we
1005 // see.
1006 auto &Lex = LexicalDecls[DC];
1007 if (!Lex.first) {
1008 Lex = std::make_pair(
1009 &M, llvm::makeArrayRef(
1010 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1011 Blob.data()),
1012 Blob.size() / 4));
1013 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001014 DC->setHasExternalLexicalStorage(true);
1015 return false;
1016}
Guy Benyei11169dd2012-12-18 14:30:41 +00001017
Richard Smith0f4e2c42015-08-06 04:23:48 +00001018bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1019 BitstreamCursor &Cursor,
1020 uint64_t Offset,
1021 DeclID ID) {
1022 assert(Offset != 0);
1023
1024 SavedStreamPosition SavedPosition(Cursor);
1025 Cursor.JumpToBit(Offset);
1026
1027 RecordData Record;
1028 StringRef Blob;
1029 unsigned Code = Cursor.ReadCode();
1030 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1031 if (RecCode != DECL_CONTEXT_VISIBLE) {
1032 Error("Expected visible lookup table block");
1033 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 }
1035
Richard Smith0f4e2c42015-08-06 04:23:48 +00001036 // We can't safely determine the primary context yet, so delay attaching the
1037 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001038 auto *Data = (const unsigned char*)Blob.data();
1039 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001040 return false;
1041}
1042
1043void ASTReader::Error(StringRef Msg) {
1044 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001045 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1046 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001047 Diag(diag::note_module_cache_path)
1048 << PP.getHeaderSearchInfo().getModuleCachePath();
1049 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001050}
1051
1052void ASTReader::Error(unsigned DiagID,
1053 StringRef Arg1, StringRef Arg2) {
1054 if (Diags.isDiagnosticInFlight())
1055 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1056 else
1057 Diag(DiagID) << Arg1 << Arg2;
1058}
1059
1060//===----------------------------------------------------------------------===//
1061// Source Manager Deserialization
1062//===----------------------------------------------------------------------===//
1063
1064/// \brief Read the line table in the source manager block.
1065/// \returns true if there was an error.
1066bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001067 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001068 unsigned Idx = 0;
1069 LineTableInfo &LineTable = SourceMgr.getLineTable();
1070
1071 // Parse the file names
1072 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001073 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001075 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1077 }
Richard Smith63078492015-09-01 07:41:55 +00001078 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001079
1080 // Parse the line entries
1081 std::vector<LineEntry> Entries;
1082 while (Idx < Record.size()) {
1083 int FID = Record[Idx++];
1084 assert(FID >= 0 && "Serialized line entries for non-local file.");
1085 // Remap FileID from 1-based old view.
1086 FID += F.SLocEntryBaseID - 1;
1087
1088 // Extract the line entries
1089 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001090 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001091 Entries.clear();
1092 Entries.reserve(NumEntries);
1093 for (unsigned I = 0; I != NumEntries; ++I) {
1094 unsigned FileOffset = Record[Idx++];
1095 unsigned LineNo = Record[Idx++];
1096 int FilenameID = FileIDs[Record[Idx++]];
1097 SrcMgr::CharacteristicKind FileKind
1098 = (SrcMgr::CharacteristicKind)Record[Idx++];
1099 unsigned IncludeOffset = Record[Idx++];
1100 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1101 FileKind, IncludeOffset));
1102 }
1103 LineTable.AddEntry(FileID::get(FID), Entries);
1104 }
1105
1106 return false;
1107}
1108
1109/// \brief Read a source manager block
1110bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1111 using namespace SrcMgr;
1112
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001113 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001114
1115 // Set the source-location entry cursor to the current position in
1116 // the stream. This cursor will be used to read the contents of the
1117 // source manager block initially, and then lazily read
1118 // source-location entries as needed.
1119 SLocEntryCursor = F.Stream;
1120
1121 // The stream itself is going to skip over the source manager block.
1122 if (F.Stream.SkipBlock()) {
1123 Error("malformed block record in AST file");
1124 return true;
1125 }
1126
1127 // Enter the source manager block.
1128 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1129 Error("malformed source manager block record in AST file");
1130 return true;
1131 }
1132
1133 RecordData Record;
1134 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001135 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1136
1137 switch (E.Kind) {
1138 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1139 case llvm::BitstreamEntry::Error:
1140 Error("malformed block record in AST file");
1141 return true;
1142 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001144 case llvm::BitstreamEntry::Record:
1145 // The interesting case.
1146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001148
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001151 StringRef Blob;
1152 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 default: // Default behavior: ignore.
1154 break;
1155
1156 case SM_SLOC_FILE_ENTRY:
1157 case SM_SLOC_BUFFER_ENTRY:
1158 case SM_SLOC_EXPANSION_ENTRY:
1159 // Once we hit one of the source location entries, we're done.
1160 return false;
1161 }
1162 }
1163}
1164
1165/// \brief If a header file is not found at the path that we expect it to be
1166/// and the PCH file was moved from its original location, try to resolve the
1167/// file by assuming that header+PCH were moved together and the header is in
1168/// the same place relative to the PCH.
1169static std::string
1170resolveFileRelativeToOriginalDir(const std::string &Filename,
1171 const std::string &OriginalDir,
1172 const std::string &CurrDir) {
1173 assert(OriginalDir != CurrDir &&
1174 "No point trying to resolve the file if the PCH dir didn't change");
1175 using namespace llvm::sys;
1176 SmallString<128> filePath(Filename);
1177 fs::make_absolute(filePath);
1178 assert(path::is_absolute(OriginalDir));
1179 SmallString<128> currPCHPath(CurrDir);
1180
1181 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1182 fileDirE = path::end(path::parent_path(filePath));
1183 path::const_iterator origDirI = path::begin(OriginalDir),
1184 origDirE = path::end(OriginalDir);
1185 // Skip the common path components from filePath and OriginalDir.
1186 while (fileDirI != fileDirE && origDirI != origDirE &&
1187 *fileDirI == *origDirI) {
1188 ++fileDirI;
1189 ++origDirI;
1190 }
1191 for (; origDirI != origDirE; ++origDirI)
1192 path::append(currPCHPath, "..");
1193 path::append(currPCHPath, fileDirI, fileDirE);
1194 path::append(currPCHPath, path::filename(Filename));
1195 return currPCHPath.str();
1196}
1197
1198bool ASTReader::ReadSLocEntry(int ID) {
1199 if (ID == 0)
1200 return false;
1201
1202 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1203 Error("source location entry ID out-of-range for AST file");
1204 return true;
1205 }
1206
Richard Smithaada85c2016-02-06 02:06:43 +00001207 // Local helper to read the (possibly-compressed) buffer data following the
1208 // entry record.
1209 auto ReadBuffer = [this](
1210 BitstreamCursor &SLocEntryCursor,
1211 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1212 RecordData Record;
1213 StringRef Blob;
1214 unsigned Code = SLocEntryCursor.ReadCode();
1215 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1216
1217 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1218 SmallString<0> Uncompressed;
1219 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1220 llvm::zlib::StatusOK) {
1221 Error("could not decompress embedded file contents");
1222 return nullptr;
1223 }
1224 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1225 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1226 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1227 } else {
1228 Error("AST record has invalid code");
1229 return nullptr;
1230 }
1231 };
1232
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1234 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001235 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001236 unsigned BaseOffset = F->SLocEntryBaseOffset;
1237
1238 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001239 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1240 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 Error("incorrectly-formatted source location entry in AST file");
1242 return true;
1243 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001244
Guy Benyei11169dd2012-12-18 14:30:41 +00001245 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001246 StringRef Blob;
1247 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 default:
1249 Error("incorrectly-formatted source location entry in AST file");
1250 return true;
1251
1252 case SM_SLOC_FILE_ENTRY: {
1253 // We will detect whether a file changed and return 'Failure' for it, but
1254 // we will also try to fail gracefully by setting up the SLocEntry.
1255 unsigned InputID = Record[4];
1256 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001257 const FileEntry *File = IF.getFile();
1258 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001259
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001260 // Note that we only check if a File was returned. If it was out-of-date
1261 // we have complained but we will continue creating a FileID to recover
1262 // gracefully.
1263 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001264 return true;
1265
1266 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1267 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1268 // This is the module's main file.
1269 IncludeLoc = getImportLocation(F);
1270 }
1271 SrcMgr::CharacteristicKind
1272 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1273 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1274 ID, BaseOffset + Record[0]);
1275 SrcMgr::FileInfo &FileInfo =
1276 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1277 FileInfo.NumCreatedFIDs = Record[5];
1278 if (Record[3])
1279 FileInfo.setHasLineDirectives();
1280
1281 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1282 unsigned NumFileDecls = Record[7];
1283 if (NumFileDecls) {
1284 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1285 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1286 NumFileDecls));
1287 }
Richard Smithaada85c2016-02-06 02:06:43 +00001288
Guy Benyei11169dd2012-12-18 14:30:41 +00001289 const SrcMgr::ContentCache *ContentCache
1290 = SourceMgr.getOrCreateContentCache(File,
1291 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1292 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001293 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1294 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001295 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1296 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001298 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 }
1300
1301 break;
1302 }
1303
1304 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001305 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 unsigned Offset = Record[0];
1307 SrcMgr::CharacteristicKind
1308 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1309 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001310 if (IncludeLoc.isInvalid() &&
1311 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 IncludeLoc = getImportLocation(F);
1313 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001314
Richard Smithaada85c2016-02-06 02:06:43 +00001315 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1316 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001318 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001319 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 break;
1321 }
1322
1323 case SM_SLOC_EXPANSION_ENTRY: {
1324 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1325 SourceMgr.createExpansionLoc(SpellingLoc,
1326 ReadSourceLocation(*F, Record[2]),
1327 ReadSourceLocation(*F, Record[3]),
1328 Record[4],
1329 ID,
1330 BaseOffset + Record[0]);
1331 break;
1332 }
1333 }
1334
1335 return false;
1336}
1337
1338std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1339 if (ID == 0)
1340 return std::make_pair(SourceLocation(), "");
1341
1342 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1343 Error("source location entry ID out-of-range for AST file");
1344 return std::make_pair(SourceLocation(), "");
1345 }
1346
1347 // Find which module file this entry lands in.
1348 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001349 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001350 return std::make_pair(SourceLocation(), "");
1351
1352 // FIXME: Can we map this down to a particular submodule? That would be
1353 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001354 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001355}
1356
1357/// \brief Find the location where the module F is imported.
1358SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1359 if (F->ImportLoc.isValid())
1360 return F->ImportLoc;
1361
1362 // Otherwise we have a PCH. It's considered to be "imported" at the first
1363 // location of its includer.
1364 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001365 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001366 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001367 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 return F->ImportedBy[0]->FirstLoc;
1370}
1371
1372/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1373/// specified cursor. Read the abbreviations that are at the top of the block
1374/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001375bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001376 if (Cursor.EnterSubBlock(BlockID))
1377 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001378
1379 while (true) {
1380 uint64_t Offset = Cursor.GetCurrentBitNo();
1381 unsigned Code = Cursor.ReadCode();
1382
1383 // We expect all abbrevs to be at the start of the block.
1384 if (Code != llvm::bitc::DEFINE_ABBREV) {
1385 Cursor.JumpToBit(Offset);
1386 return false;
1387 }
1388 Cursor.ReadAbbrevRecord();
1389 }
1390}
1391
Richard Smithe40f2ba2013-08-07 21:41:30 +00001392Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001393 unsigned &Idx) {
1394 Token Tok;
1395 Tok.startToken();
1396 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1397 Tok.setLength(Record[Idx++]);
1398 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1399 Tok.setIdentifierInfo(II);
1400 Tok.setKind((tok::TokenKind)Record[Idx++]);
1401 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1402 return Tok;
1403}
1404
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001406 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001407
1408 // Keep track of where we are in the stream, then jump back there
1409 // after reading this macro.
1410 SavedStreamPosition SavedPosition(Stream);
1411
1412 Stream.JumpToBit(Offset);
1413 RecordData Record;
1414 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001415 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001416
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001418 // Advance to the next record, but if we get to the end of the block, don't
1419 // pop it (removing all the abbreviations from the cursor) since we want to
1420 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001421 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001422 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1423
1424 switch (Entry.Kind) {
1425 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1426 case llvm::BitstreamEntry::Error:
1427 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001428 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001429 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001430 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001431 case llvm::BitstreamEntry::Record:
1432 // The interesting case.
1433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 }
1435
1436 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 Record.clear();
1438 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001439 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001441 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001442 case PP_MACRO_DIRECTIVE_HISTORY:
1443 return Macro;
1444
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 case PP_MACRO_OBJECT_LIKE:
1446 case PP_MACRO_FUNCTION_LIKE: {
1447 // If we already have a macro, that means that we've hit the end
1448 // of the definition of the macro we were looking for. We're
1449 // done.
1450 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001451 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001452
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001453 unsigned NextIndex = 1; // Skip identifier ID.
1454 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001456 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001457 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001459 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001460
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1462 // Decode function-like macro info.
1463 bool isC99VarArgs = Record[NextIndex++];
1464 bool isGNUVarArgs = Record[NextIndex++];
1465 bool hasCommaPasting = Record[NextIndex++];
1466 MacroArgs.clear();
1467 unsigned NumArgs = Record[NextIndex++];
1468 for (unsigned i = 0; i != NumArgs; ++i)
1469 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1470
1471 // Install function-like macro info.
1472 MI->setIsFunctionLike();
1473 if (isC99VarArgs) MI->setIsC99Varargs();
1474 if (isGNUVarArgs) MI->setIsGNUVarargs();
1475 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001476 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 }
1478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 // Remember that we saw this macro last so that we add the tokens that
1480 // form its body to it.
1481 Macro = MI;
1482
1483 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1484 Record[NextIndex]) {
1485 // We have a macro definition. Register the association
1486 PreprocessedEntityID
1487 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1488 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001489 PreprocessingRecord::PPEntityID PPID =
1490 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1491 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1492 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001493 if (PPDef)
1494 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 }
1496
1497 ++NumMacrosRead;
1498 break;
1499 }
1500
1501 case PP_TOKEN: {
1502 // If we see a TOKEN before a PP_MACRO_*, then the file is
1503 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001504 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505
John McCallf413f5e2013-05-03 00:10:13 +00001506 unsigned Idx = 0;
1507 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 Macro->AddTokenToBody(Tok);
1509 break;
1510 }
1511 }
1512 }
1513}
1514
1515PreprocessedEntityID
1516ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1517 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1518 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1519 assert(I != M.PreprocessedEntityRemap.end()
1520 && "Invalid index into preprocessed entity index remap");
1521
1522 return LocalID + I->second;
1523}
1524
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001525unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1526 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001527}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001530HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001531 internal_key_type ikey = {FE->getSize(),
1532 M.HasTimestamps ? FE->getModificationTime() : 0,
1533 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001534 return ikey;
1535}
Guy Benyei11169dd2012-12-18 14:30:41 +00001536
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001537bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001538 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 return false;
1540
Richard Smith7ed1bc92014-12-05 22:42:13 +00001541 if (llvm::sys::path::is_absolute(a.Filename) &&
1542 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001543 return true;
1544
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001546 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001547 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1548 if (!Key.Imported)
1549 return FileMgr.getFile(Key.Filename);
1550
1551 std::string Resolved = Key.Filename;
1552 Reader.ResolveImportedPath(M, Resolved);
1553 return FileMgr.getFile(Resolved);
1554 };
1555
1556 const FileEntry *FEA = GetFile(a);
1557 const FileEntry *FEB = GetFile(b);
1558 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001559}
1560
1561std::pair<unsigned, unsigned>
1562HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001563 using namespace llvm::support;
1564 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001566 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001567}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001568
1569HeaderFileInfoTrait::internal_key_type
1570HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001571 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001572 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001573 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1574 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001575 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001576 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001577 return ikey;
1578}
1579
Guy Benyei11169dd2012-12-18 14:30:41 +00001580HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001581HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 unsigned DataLen) {
1583 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001584 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 HeaderFileInfo HFI;
1586 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001587 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1588 HFI.isImport |= (Flags >> 4) & 0x01;
1589 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1590 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001592 // FIXME: Find a better way to handle this. Maybe just store a
1593 // "has been included" flag?
1594 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1595 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001596 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1597 M, endian::readNext<uint32_t, little, unaligned>(d));
1598 if (unsigned FrameworkOffset =
1599 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 // The framework offset is 1 greater than the actual offset,
1601 // since 0 is used as an indicator for "no framework name".
1602 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1603 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1604 }
Richard Smith386bb072015-08-18 23:42:23 +00001605
1606 assert((End - d) % 4 == 0 &&
1607 "Wrong data length in HeaderFileInfo deserialization");
1608 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001609 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001610 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1611 LocalSMID >>= 2;
1612
1613 // This header is part of a module. Associate it with the module to enable
1614 // implicit module import.
1615 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1616 Module *Mod = Reader.getSubmodule(GlobalSMID);
1617 FileManager &FileMgr = Reader.getFileManager();
1618 ModuleMap &ModMap =
1619 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1620
1621 std::string Filename = key.Filename;
1622 if (key.Imported)
1623 Reader.ResolveImportedPath(M, Filename);
1624 // FIXME: This is not always the right filename-as-written, but we're not
1625 // going to use this information to rebuild the module, so it doesn't make
1626 // a lot of difference.
1627 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001628 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1629 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001630 }
1631
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 // This HeaderFileInfo was externally loaded.
1633 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001634 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 return HFI;
1636}
1637
Richard Smithd7329392015-04-21 21:46:32 +00001638void ASTReader::addPendingMacro(IdentifierInfo *II,
1639 ModuleFile *M,
1640 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001641 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1642 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001643}
1644
1645void ASTReader::ReadDefinedMacros() {
1646 // Note that we are loading defined macros.
1647 Deserializing Macros(this);
1648
Pete Cooper57d3f142015-07-30 17:22:52 +00001649 for (auto &I : llvm::reverse(ModuleMgr)) {
1650 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
1652 // If there was no preprocessor block, skip this file.
1653 if (!MacroCursor.getBitStreamReader())
1654 continue;
1655
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001656 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001657 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001658
1659 RecordData Record;
1660 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001661 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1662
1663 switch (E.Kind) {
1664 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1665 case llvm::BitstreamEntry::Error:
1666 Error("malformed block record in AST file");
1667 return;
1668 case llvm::BitstreamEntry::EndBlock:
1669 goto NextCursor;
1670
1671 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001672 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001673 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001674 default: // Default behavior: ignore.
1675 break;
1676
1677 case PP_MACRO_OBJECT_LIKE:
1678 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001679 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001680 break;
1681
1682 case PP_TOKEN:
1683 // Ignore tokens.
1684 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 break;
1687 }
1688 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001689 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 }
1691}
1692
1693namespace {
1694 /// \brief Visitor class used to look up identifirs in an AST file.
1695 class IdentifierLookupVisitor {
1696 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001697 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001699 unsigned &NumIdentifierLookups;
1700 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001702
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001704 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1705 unsigned &NumIdentifierLookups,
1706 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001707 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1708 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 NumIdentifierLookups(NumIdentifierLookups),
1710 NumIdentifierLookupHits(NumIdentifierLookupHits),
1711 Found()
1712 {
1713 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001714
1715 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001717 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001719
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 ASTIdentifierLookupTable *IdTable
1721 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1722 if (!IdTable)
1723 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001724
1725 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001726 Found);
1727 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001728 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001729 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 if (Pos == IdTable->end())
1731 return false;
1732
1733 // Dereferencing the iterator has the effect of building the
1734 // IdentifierInfo node and populating it with the various
1735 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001736 ++NumIdentifierLookupHits;
1737 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001738 return true;
1739 }
1740
1741 // \brief Retrieve the identifier info found within the module
1742 // files.
1743 IdentifierInfo *getIdentifierInfo() const { return Found; }
1744 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001745}
Guy Benyei11169dd2012-12-18 14:30:41 +00001746
1747void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1748 // Note that we are loading an identifier.
1749 Deserializing AnIdentifier(this);
1750
1751 unsigned PriorGeneration = 0;
1752 if (getContext().getLangOpts().Modules)
1753 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001754
1755 // If there is a global index, look there first to determine which modules
1756 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001757 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001758 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001759 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001760 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1761 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001762 }
1763 }
1764
Douglas Gregor7211ac12013-01-25 23:32:03 +00001765 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001766 NumIdentifierLookups,
1767 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001768 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 markIdentifierUpToDate(&II);
1770}
1771
1772void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1773 if (!II)
1774 return;
1775
1776 II->setOutOfDate(false);
1777
1778 // Update the generation for this identifier.
1779 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001780 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001781}
1782
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001783void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1784 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001785 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786
1787 BitstreamCursor &Cursor = M.MacroCursor;
1788 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001789 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001790
Richard Smith713369b2015-04-23 20:40:50 +00001791 struct ModuleMacroRecord {
1792 SubmoduleID SubModID;
1793 MacroInfo *MI;
1794 SmallVector<SubmoduleID, 8> Overrides;
1795 };
1796 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797
Richard Smithd7329392015-04-21 21:46:32 +00001798 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1799 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1800 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001801 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001802 while (true) {
1803 llvm::BitstreamEntry Entry =
1804 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1805 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1806 Error("malformed block record in AST file");
1807 return;
1808 }
1809
1810 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001811 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001812 case PP_MACRO_DIRECTIVE_HISTORY:
1813 break;
1814
1815 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001816 ModuleMacros.push_back(ModuleMacroRecord());
1817 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001818 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1819 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001820 for (int I = 2, N = Record.size(); I != N; ++I)
1821 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001822 continue;
1823 }
1824
1825 default:
1826 Error("malformed block record in AST file");
1827 return;
1828 }
1829
1830 // We found the macro directive history; that's the last record
1831 // for this macro.
1832 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001833 }
1834
Richard Smithd7329392015-04-21 21:46:32 +00001835 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001836 {
1837 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001838 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001839 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001840 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001841 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001842 Module *Mod = getSubmodule(ModID);
1843 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001844 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001845 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001846 }
1847
1848 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001849 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001850 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001851 }
1852 }
1853
1854 // Don't read the directive history for a module; we don't have anywhere
1855 // to put it.
1856 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1857 return;
1858
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001859 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001860 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861 unsigned Idx = 0, N = Record.size();
1862 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001863 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001865 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1866 switch (K) {
1867 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001868 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001869 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001870 break;
1871 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001872 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001873 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001874 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001875 }
1876 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001877 bool isPublic = Record[Idx++];
1878 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1879 break;
1880 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001881
1882 if (!Latest)
1883 Latest = MD;
1884 if (Earliest)
1885 Earliest->setPrevious(MD);
1886 Earliest = MD;
1887 }
1888
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001889 if (Latest)
1890 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001891}
1892
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001893ASTReader::InputFileInfo
1894ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001895 // Go find this input file.
1896 BitstreamCursor &Cursor = F.InputFilesCursor;
1897 SavedStreamPosition SavedPosition(Cursor);
1898 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1899
1900 unsigned Code = Cursor.ReadCode();
1901 RecordData Record;
1902 StringRef Blob;
1903
1904 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1905 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1906 "invalid record type for input file");
1907 (void)Result;
1908
1909 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001910 InputFileInfo R;
1911 R.StoredSize = static_cast<off_t>(Record[1]);
1912 R.StoredTime = static_cast<time_t>(Record[2]);
1913 R.Overridden = static_cast<bool>(Record[3]);
1914 R.Transient = static_cast<bool>(Record[4]);
1915 R.Filename = Blob;
1916 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001917 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001918}
1919
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001920InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 // If this ID is bogus, just return an empty input file.
1922 if (ID == 0 || ID > F.InputFilesLoaded.size())
1923 return InputFile();
1924
1925 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001926 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 return F.InputFilesLoaded[ID-1];
1928
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001929 if (F.InputFilesLoaded[ID-1].isNotFound())
1930 return InputFile();
1931
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001933 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 SavedStreamPosition SavedPosition(Cursor);
1935 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1936
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001937 InputFileInfo FI = readInputFileInfo(F, ID);
1938 off_t StoredSize = FI.StoredSize;
1939 time_t StoredTime = FI.StoredTime;
1940 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001941 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001942 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001943
Richard Smitha8cfffa2015-11-26 02:04:16 +00001944 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00001945
1946 // If we didn't find the file, resolve it relative to the
1947 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001948 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001949 F.OriginalDir != CurrentDir) {
1950 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1951 F.OriginalDir,
1952 CurrentDir);
1953 if (!Resolved.empty())
1954 File = FileMgr.getFile(Resolved);
1955 }
1956
1957 // For an overridden file, create a virtual file with the stored
1958 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001959 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00001961
Craig Toppera13603a2014-05-22 05:54:18 +00001962 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001963 if (Complain) {
1964 std::string ErrorStr = "could not find file '";
1965 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001966 ErrorStr += "' referenced by AST file '";
1967 ErrorStr += F.FileName;
1968 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001969 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001970 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001971 // Record that we didn't find the file.
1972 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1973 return InputFile();
1974 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001975
Ben Langmuir198c1682014-03-07 07:27:49 +00001976 // Check if there was a request to override the contents of the file
1977 // that was part of the precompiled header. Overridding such a file
1978 // can lead to problems when lexing using the source locations from the
1979 // PCH.
1980 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00001981 // FIXME: Reject if the overrides are different.
1982 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 if (Complain)
1984 Error(diag::err_fe_pch_file_overridden, Filename);
1985 // After emitting the diagnostic, recover by disabling the override so
1986 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001987 //
1988 // FIXME: This recovery is just as broken as the original state; there may
1989 // be another precompiled module that's using the overridden contents, or
1990 // we might be half way through parsing it. Instead, we should treat the
1991 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00001992 SM.disableFileContentsOverride(File);
1993 // The FileEntry is a virtual file entry with the size of the contents
1994 // that would override the original contents. Set it to the original's
1995 // size/time.
1996 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1997 StoredSize, StoredTime);
1998 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 bool IsOutOfDate = false;
2001
2002 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002003 if (!Overridden && //
2004 (StoredSize != File->getSize() ||
2005#if defined(LLVM_ON_WIN32)
2006 false
2007#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 // In our regression testing, the Windows file system seems to
2009 // have inconsistent modification times that sometimes
2010 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002011 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00002012 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
2013 (StoredTime && StoredTime != File->getModificationTime() &&
2014 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00002015#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002016 )) {
2017 if (Complain) {
2018 // Build a list of the PCH imports that got us here (in reverse).
2019 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2020 while (ImportStack.back()->ImportedBy.size() > 0)
2021 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002022
Ben Langmuir198c1682014-03-07 07:27:49 +00002023 // The top-level PCH is stale.
2024 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2025 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002026
Ben Langmuir198c1682014-03-07 07:27:49 +00002027 // Print the import stack.
2028 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2029 Diag(diag::note_pch_required_by)
2030 << Filename << ImportStack[0]->FileName;
2031 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002032 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002033 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002034 }
2035
Ben Langmuir198c1682014-03-07 07:27:49 +00002036 if (!Diags.isDiagnosticInFlight())
2037 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 }
2039
Ben Langmuir198c1682014-03-07 07:27:49 +00002040 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002041 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002042 // FIXME: If the file is overridden and we've already opened it,
2043 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002044
Richard Smitha8cfffa2015-11-26 02:04:16 +00002045 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002046
2047 // Note that we've loaded this input file.
2048 F.InputFilesLoaded[ID-1] = IF;
2049 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002050}
2051
Richard Smith7ed1bc92014-12-05 22:42:13 +00002052/// \brief If we are loading a relocatable PCH or module file, and the filename
2053/// is not an absolute path, add the system or module root to the beginning of
2054/// the file name.
2055void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2056 // Resolve relative to the base directory, if we have one.
2057 if (!M.BaseDirectory.empty())
2058 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002059}
2060
Richard Smith7ed1bc92014-12-05 22:42:13 +00002061void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2063 return;
2064
Richard Smith7ed1bc92014-12-05 22:42:13 +00002065 SmallString<128> Buffer;
2066 llvm::sys::path::append(Buffer, Prefix, Filename);
2067 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002068}
2069
Richard Smith0f99d6a2015-08-09 08:48:41 +00002070static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2071 switch (ARR) {
2072 case ASTReader::Failure: return true;
2073 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2074 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2075 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2076 case ASTReader::ConfigurationMismatch:
2077 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2078 case ASTReader::HadErrors: return true;
2079 case ASTReader::Success: return false;
2080 }
2081
2082 llvm_unreachable("unknown ASTReadResult");
2083}
2084
Richard Smith0516b182015-09-08 19:40:14 +00002085ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2086 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2087 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2088 std::string &SuggestedPredefines) {
2089 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2090 return Failure;
2091
2092 // Read all of the records in the options block.
2093 RecordData Record;
2094 ASTReadResult Result = Success;
2095 while (1) {
2096 llvm::BitstreamEntry Entry = Stream.advance();
2097
2098 switch (Entry.Kind) {
2099 case llvm::BitstreamEntry::Error:
2100 case llvm::BitstreamEntry::SubBlock:
2101 return Failure;
2102
2103 case llvm::BitstreamEntry::EndBlock:
2104 return Result;
2105
2106 case llvm::BitstreamEntry::Record:
2107 // The interesting case.
2108 break;
2109 }
2110
2111 // Read and process a record.
2112 Record.clear();
2113 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2114 case LANGUAGE_OPTIONS: {
2115 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2116 if (ParseLanguageOptions(Record, Complain, Listener,
2117 AllowCompatibleConfigurationMismatch))
2118 Result = ConfigurationMismatch;
2119 break;
2120 }
2121
2122 case TARGET_OPTIONS: {
2123 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2124 if (ParseTargetOptions(Record, Complain, Listener,
2125 AllowCompatibleConfigurationMismatch))
2126 Result = ConfigurationMismatch;
2127 break;
2128 }
2129
2130 case DIAGNOSTIC_OPTIONS: {
2131 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2132 if (!AllowCompatibleConfigurationMismatch &&
2133 ParseDiagnosticOptions(Record, Complain, Listener))
2134 return OutOfDate;
2135 break;
2136 }
2137
2138 case FILE_SYSTEM_OPTIONS: {
2139 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2140 if (!AllowCompatibleConfigurationMismatch &&
2141 ParseFileSystemOptions(Record, Complain, Listener))
2142 Result = ConfigurationMismatch;
2143 break;
2144 }
2145
2146 case HEADER_SEARCH_OPTIONS: {
2147 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2148 if (!AllowCompatibleConfigurationMismatch &&
2149 ParseHeaderSearchOptions(Record, Complain, Listener))
2150 Result = ConfigurationMismatch;
2151 break;
2152 }
2153
2154 case PREPROCESSOR_OPTIONS:
2155 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2156 if (!AllowCompatibleConfigurationMismatch &&
2157 ParsePreprocessorOptions(Record, Complain, Listener,
2158 SuggestedPredefines))
2159 Result = ConfigurationMismatch;
2160 break;
2161 }
2162 }
2163}
2164
Guy Benyei11169dd2012-12-18 14:30:41 +00002165ASTReader::ASTReadResult
2166ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002167 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002168 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002169 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002170 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002171 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002172
2173 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2174 Error("malformed block record in AST file");
2175 return Failure;
2176 }
2177
2178 // Read all of the records and blocks in the control block.
2179 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002180 unsigned NumInputs = 0;
2181 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002182 while (1) {
2183 llvm::BitstreamEntry Entry = Stream.advance();
2184
2185 switch (Entry.Kind) {
2186 case llvm::BitstreamEntry::Error:
2187 Error("malformed block record in AST file");
2188 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002189 case llvm::BitstreamEntry::EndBlock: {
2190 // Validate input files.
2191 const HeaderSearchOptions &HSOpts =
2192 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002193
Richard Smitha1825302014-10-23 22:18:29 +00002194 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002195 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2196 // loaded module files, ignore missing inputs.
2197 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002199
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002200 // If we are reading a module, we will create a verification timestamp,
2201 // so we verify all input files. Otherwise, verify only user input
2202 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002203
2204 unsigned N = NumUserInputs;
2205 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002206 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002207 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002208 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002209 N = NumInputs;
2210
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002211 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002212 InputFile IF = getInputFile(F, I+1, Complain);
2213 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002216 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002217
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002218 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002219 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002220
Ben Langmuircb69b572014-03-07 06:40:32 +00002221 if (Listener && Listener->needsInputFileVisitation()) {
2222 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2223 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002224 for (unsigned I = 0; I < N; ++I) {
2225 bool IsSystem = I >= NumUserInputs;
2226 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002227 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2228 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002229 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002230 }
2231
Richard Smith8a308ec2015-11-05 00:54:55 +00002232 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002233 }
2234
Chris Lattnere7b154b2013-01-19 21:39:22 +00002235 case llvm::BitstreamEntry::SubBlock:
2236 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 case INPUT_FILES_BLOCK_ID:
2238 F.InputFilesCursor = Stream;
2239 if (Stream.SkipBlock() || // Skip with the main cursor
2240 // Read the abbreviations
2241 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2242 Error("malformed block record in AST file");
2243 return Failure;
2244 }
2245 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002246
2247 case OPTIONS_BLOCK_ID:
2248 // If we're reading the first module for this group, check its options
2249 // are compatible with ours. For modules it imports, no further checking
2250 // is required, because we checked them when we built it.
2251 if (Listener && !ImportedBy) {
2252 // Should we allow the configuration of the module file to differ from
2253 // the configuration of the current translation unit in a compatible
2254 // way?
2255 //
2256 // FIXME: Allow this for files explicitly specified with -include-pch.
2257 bool AllowCompatibleConfigurationMismatch =
2258 F.Kind == MK_ExplicitModule;
2259
Richard Smith8a308ec2015-11-05 00:54:55 +00002260 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2261 AllowCompatibleConfigurationMismatch,
2262 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002263 if (Result == Failure) {
2264 Error("malformed block record in AST file");
2265 return Result;
2266 }
2267
Richard Smith8a308ec2015-11-05 00:54:55 +00002268 if (DisableValidation ||
2269 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2270 Result = Success;
2271
2272 // If we've diagnosed a problem, we're done.
2273 if (Result != Success &&
2274 isDiagnosedResult(Result, ClientLoadCapabilities))
Richard Smith0516b182015-09-08 19:40:14 +00002275 return Result;
2276 } else if (Stream.SkipBlock()) {
2277 Error("malformed block record in AST file");
2278 return Failure;
2279 }
2280 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002281
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002283 if (Stream.SkipBlock()) {
2284 Error("malformed block record in AST file");
2285 return Failure;
2286 }
2287 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002289
2290 case llvm::BitstreamEntry::Record:
2291 // The interesting case.
2292 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 }
2294
2295 // Read and process a record.
2296 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002297 StringRef Blob;
2298 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 case METADATA: {
2300 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2301 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002302 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2303 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 return VersionMismatch;
2305 }
2306
Richard Smithe75ee0f2015-08-17 07:13:32 +00002307 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2309 Diag(diag::err_pch_with_compiler_errors);
2310 return HadErrors;
2311 }
2312
2313 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002314 // Relative paths in a relocatable PCH are relative to our sysroot.
2315 if (F.RelocatablePCH)
2316 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002317
Richard Smithe75ee0f2015-08-17 07:13:32 +00002318 F.HasTimestamps = Record[5];
2319
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002321 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2323 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002324 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 return VersionMismatch;
2326 }
2327 break;
2328 }
2329
Ben Langmuir487ea142014-10-23 18:05:36 +00002330 case SIGNATURE:
2331 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2332 F.Signature = Record[0];
2333 break;
2334
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case IMPORTS: {
2336 // Load each of the imported PCH files.
2337 unsigned Idx = 0, N = Record.size();
2338 while (Idx < N) {
2339 // Read information about the AST file.
2340 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2341 // The import location will be the local one for now; we will adjust
2342 // all import locations of module imports after the global source
2343 // location info are setup.
2344 SourceLocation ImportLoc =
2345 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002346 off_t StoredSize = (off_t)Record[Idx++];
2347 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002348 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002349 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002350
Richard Smith0f99d6a2015-08-09 08:48:41 +00002351 // If our client can't cope with us being out of date, we can't cope with
2352 // our dependency being missing.
2353 unsigned Capabilities = ClientLoadCapabilities;
2354 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2355 Capabilities &= ~ARR_Missing;
2356
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002358 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2359 Loaded, StoredSize, StoredModTime,
2360 StoredSignature, Capabilities);
2361
2362 // If we diagnosed a problem, produce a backtrace.
2363 if (isDiagnosedResult(Result, Capabilities))
2364 Diag(diag::note_module_file_imported_by)
2365 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2366
2367 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 case Failure: return Failure;
2369 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002370 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case OutOfDate: return OutOfDate;
2372 case VersionMismatch: return VersionMismatch;
2373 case ConfigurationMismatch: return ConfigurationMismatch;
2374 case HadErrors: return HadErrors;
2375 case Success: break;
2376 }
2377 }
2378 break;
2379 }
2380
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 case ORIGINAL_FILE:
2382 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002383 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002385 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 break;
2387
2388 case ORIGINAL_FILE_ID:
2389 F.OriginalSourceFileID = FileID::get(Record[0]);
2390 break;
2391
2392 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002393 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 break;
2395
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002396 case MODULE_NAME:
2397 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002398 if (Listener)
2399 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002400 break;
2401
Richard Smith223d3f22014-12-06 03:21:08 +00002402 case MODULE_DIRECTORY: {
2403 assert(!F.ModuleName.empty() &&
2404 "MODULE_DIRECTORY found before MODULE_NAME");
2405 // If we've already loaded a module map file covering this module, we may
2406 // have a better path for it (relative to the current build).
2407 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2408 if (M && M->Directory) {
2409 // If we're implicitly loading a module, the base directory can't
2410 // change between the build and use.
2411 if (F.Kind != MK_ExplicitModule) {
2412 const DirectoryEntry *BuildDir =
2413 PP.getFileManager().getDirectory(Blob);
2414 if (!BuildDir || BuildDir != M->Directory) {
2415 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2416 Diag(diag::err_imported_module_relocated)
2417 << F.ModuleName << Blob << M->Directory->getName();
2418 return OutOfDate;
2419 }
2420 }
2421 F.BaseDirectory = M->Directory->getName();
2422 } else {
2423 F.BaseDirectory = Blob;
2424 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002425 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002426 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002427
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002428 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002429 if (ASTReadResult Result =
2430 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2431 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002432 break;
2433
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002434 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002435 NumInputs = Record[0];
2436 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002437 F.InputFileOffsets =
2438 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002439 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 break;
2441 }
2442 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002443}
2444
Ben Langmuir2c9af442014-04-10 17:57:43 +00002445ASTReader::ASTReadResult
2446ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002447 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448
2449 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2450 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 }
2453
2454 // Read all of the records and blocks for the AST file.
2455 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002456 while (1) {
2457 llvm::BitstreamEntry Entry = Stream.advance();
2458
2459 switch (Entry.Kind) {
2460 case llvm::BitstreamEntry::Error:
2461 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002462 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002463 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002464 // Outside of C++, we do not store a lookup map for the translation unit.
2465 // Instead, mark it as needing a lookup map to be built if this module
2466 // contains any declarations lexically within it (which it always does!).
2467 // This usually has no cost, since we very rarely need the lookup map for
2468 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002470 if (DC->hasExternalLexicalStorage() &&
2471 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002473
Ben Langmuir2c9af442014-04-10 17:57:43 +00002474 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002476 case llvm::BitstreamEntry::SubBlock:
2477 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 case DECLTYPES_BLOCK_ID:
2479 // We lazily load the decls block, but we want to set up the
2480 // DeclsCursor cursor to point into it. Clone our current bitcode
2481 // cursor to it, enter the block and read the abbrevs in that block.
2482 // With the main cursor, we just skip over it.
2483 F.DeclsCursor = Stream;
2484 if (Stream.SkipBlock() || // Skip with the main cursor.
2485 // Read the abbrevs.
2486 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2487 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002488 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 }
2490 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002491
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 case PREPROCESSOR_BLOCK_ID:
2493 F.MacroCursor = Stream;
2494 if (!PP.getExternalSource())
2495 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002496
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 if (Stream.SkipBlock() ||
2498 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2499 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002500 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 }
2502 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2503 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002504
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 case PREPROCESSOR_DETAIL_BLOCK_ID:
2506 F.PreprocessorDetailCursor = Stream;
2507 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002508 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002510 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002511 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2515
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 if (!PP.getPreprocessingRecord())
2517 PP.createPreprocessingRecord();
2518 if (!PP.getPreprocessingRecord()->getExternalSource())
2519 PP.getPreprocessingRecord()->SetExternalSource(*this);
2520 break;
2521
2522 case SOURCE_MANAGER_BLOCK_ID:
2523 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002524 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002526
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002528 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2529 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002531
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002533 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 if (Stream.SkipBlock() ||
2535 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2536 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539 CommentsCursors.push_back(std::make_pair(C, &F));
2540 break;
2541 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002542
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002544 if (Stream.SkipBlock()) {
2545 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002546 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547 }
2548 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 }
2550 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002551
2552 case llvm::BitstreamEntry::Record:
2553 // The interesting case.
2554 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 }
2556
2557 // Read and process a record.
2558 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002559 StringRef Blob;
2560 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 default: // Default behavior: ignore.
2562 break;
2563
2564 case TYPE_OFFSET: {
2565 if (F.LocalNumTypes != 0) {
2566 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002567 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002569 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 F.LocalNumTypes = Record[0];
2571 unsigned LocalBaseTypeIndex = Record[1];
2572 F.BaseTypeIndex = getTotalNumTypes();
2573
2574 if (F.LocalNumTypes > 0) {
2575 // Introduce the global -> local mapping for types within this module.
2576 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2577
2578 // Introduce the local -> global mapping for types within this module.
2579 F.TypeRemap.insertOrReplace(
2580 std::make_pair(LocalBaseTypeIndex,
2581 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002582
2583 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 }
2585 break;
2586 }
2587
2588 case DECL_OFFSET: {
2589 if (F.LocalNumDecls != 0) {
2590 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002593 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 F.LocalNumDecls = Record[0];
2595 unsigned LocalBaseDeclID = Record[1];
2596 F.BaseDeclID = getTotalNumDecls();
2597
2598 if (F.LocalNumDecls > 0) {
2599 // Introduce the global -> local mapping for declarations within this
2600 // module.
2601 GlobalDeclMap.insert(
2602 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2603
2604 // Introduce the local -> global mapping for declarations within this
2605 // module.
2606 F.DeclRemap.insertOrReplace(
2607 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2608
2609 // Introduce the global -> local mapping for declarations within this
2610 // module.
2611 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002612
Ben Langmuir52ca6782014-10-20 16:27:32 +00002613 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2614 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 break;
2616 }
2617
2618 case TU_UPDATE_LEXICAL: {
2619 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002620 LexicalContents Contents(
2621 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2622 Blob.data()),
2623 static_cast<unsigned int>(Blob.size() / 4));
2624 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 TU->setHasExternalLexicalStorage(true);
2626 break;
2627 }
2628
2629 case UPDATE_VISIBLE: {
2630 unsigned Idx = 0;
2631 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002632 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002633 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002634 // If we've already loaded the decl, perform the updates when we finish
2635 // loading this block.
2636 if (Decl *D = GetExistingDecl(ID))
2637 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 break;
2639 }
2640
2641 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002642 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002644 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2645 (const unsigned char *)F.IdentifierTableData + Record[0],
2646 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2647 (const unsigned char *)F.IdentifierTableData,
2648 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002649
2650 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2651 }
2652 break;
2653
2654 case IDENTIFIER_OFFSET: {
2655 if (F.LocalNumIdentifiers != 0) {
2656 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002657 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002659 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 F.LocalNumIdentifiers = Record[0];
2661 unsigned LocalBaseIdentifierID = Record[1];
2662 F.BaseIdentifierID = getTotalNumIdentifiers();
2663
2664 if (F.LocalNumIdentifiers > 0) {
2665 // Introduce the global -> local mapping for identifiers within this
2666 // module.
2667 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2668 &F));
2669
2670 // Introduce the local -> global mapping for identifiers within this
2671 // module.
2672 F.IdentifierRemap.insertOrReplace(
2673 std::make_pair(LocalBaseIdentifierID,
2674 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002675
Ben Langmuir52ca6782014-10-20 16:27:32 +00002676 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2677 + F.LocalNumIdentifiers);
2678 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 break;
2680 }
2681
Richard Smith33e0f7e2015-07-22 02:08:40 +00002682 case INTERESTING_IDENTIFIERS:
2683 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2684 break;
2685
Ben Langmuir332aafe2014-01-31 01:06:56 +00002686 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002687 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2688 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002690 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 break;
2692
2693 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002694 if (SpecialTypes.empty()) {
2695 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2696 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2697 break;
2698 }
2699
2700 if (SpecialTypes.size() != Record.size()) {
2701 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002702 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002703 }
2704
2705 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2706 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2707 if (!SpecialTypes[I])
2708 SpecialTypes[I] = ID;
2709 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2710 // merge step?
2711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 break;
2713
2714 case STATISTICS:
2715 TotalNumStatements += Record[0];
2716 TotalNumMacros += Record[1];
2717 TotalLexicalDeclContexts += Record[2];
2718 TotalVisibleDeclContexts += Record[3];
2719 break;
2720
2721 case UNUSED_FILESCOPED_DECLS:
2722 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2723 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2724 break;
2725
2726 case DELEGATING_CTORS:
2727 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2728 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2729 break;
2730
2731 case WEAK_UNDECLARED_IDENTIFIERS:
2732 if (Record.size() % 4 != 0) {
2733 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002734 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 }
2736
2737 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2738 // files. This isn't the way to do it :)
2739 WeakUndeclaredIdentifiers.clear();
2740
2741 // Translate the weak, undeclared identifiers into global IDs.
2742 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2743 WeakUndeclaredIdentifiers.push_back(
2744 getGlobalIdentifierID(F, Record[I++]));
2745 WeakUndeclaredIdentifiers.push_back(
2746 getGlobalIdentifierID(F, Record[I++]));
2747 WeakUndeclaredIdentifiers.push_back(
2748 ReadSourceLocation(F, Record, I).getRawEncoding());
2749 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2750 }
2751 break;
2752
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002754 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 F.LocalNumSelectors = Record[0];
2756 unsigned LocalBaseSelectorID = Record[1];
2757 F.BaseSelectorID = getTotalNumSelectors();
2758
2759 if (F.LocalNumSelectors > 0) {
2760 // Introduce the global -> local mapping for selectors within this
2761 // module.
2762 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2763
2764 // Introduce the local -> global mapping for selectors within this
2765 // module.
2766 F.SelectorRemap.insertOrReplace(
2767 std::make_pair(LocalBaseSelectorID,
2768 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002769
2770 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 }
2772 break;
2773 }
2774
2775 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002776 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 if (Record[0])
2778 F.SelectorLookupTable
2779 = ASTSelectorLookupTable::Create(
2780 F.SelectorLookupTableData + Record[0],
2781 F.SelectorLookupTableData,
2782 ASTSelectorLookupTrait(*this, F));
2783 TotalNumMethodPoolEntries += Record[1];
2784 break;
2785
2786 case REFERENCED_SELECTOR_POOL:
2787 if (!Record.empty()) {
2788 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2789 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2790 Record[Idx++]));
2791 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2792 getRawEncoding());
2793 }
2794 }
2795 break;
2796
2797 case PP_COUNTER_VALUE:
2798 if (!Record.empty() && Listener)
2799 Listener->ReadCounter(F, Record[0]);
2800 break;
2801
2802 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002803 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 F.NumFileSortedDecls = Record[0];
2805 break;
2806
2807 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002808 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 F.LocalNumSLocEntries = Record[0];
2810 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002811 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002812 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002814 if (!F.SLocEntryBaseID) {
2815 Error("ran out of source locations");
2816 break;
2817 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 // Make our entry in the range map. BaseID is negative and growing, so
2819 // we invert it. Because we invert it, though, we need the other end of
2820 // the range.
2821 unsigned RangeStart =
2822 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2823 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2824 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2825
2826 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2827 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2828 GlobalSLocOffsetMap.insert(
2829 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2830 - SLocSpaceSize,&F));
2831
2832 // Initialize the remapping table.
2833 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002834 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002836 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2838
2839 TotalNumSLocEntries += F.LocalNumSLocEntries;
2840 break;
2841 }
2842
2843 case MODULE_OFFSET_MAP: {
2844 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002845 const unsigned char *Data = (const unsigned char*)Blob.data();
2846 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002847
2848 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2849 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2850 F.SLocRemap.insert(std::make_pair(0U, 0));
2851 F.SLocRemap.insert(std::make_pair(2U, 1));
2852 }
2853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002855 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2856 RemapBuilder;
2857 RemapBuilder SLocRemap(F.SLocRemap);
2858 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2859 RemapBuilder MacroRemap(F.MacroRemap);
2860 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2861 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2862 RemapBuilder SelectorRemap(F.SelectorRemap);
2863 RemapBuilder DeclRemap(F.DeclRemap);
2864 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002865
Richard Smithd8879c82015-08-24 21:59:32 +00002866 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002867 using namespace llvm::support;
2868 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 StringRef Name = StringRef((const char*)Data, Len);
2870 Data += Len;
2871 ModuleFile *OM = ModuleMgr.lookup(Name);
2872 if (!OM) {
2873 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002874 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 }
2876
Justin Bogner57ba0b22014-03-28 22:03:24 +00002877 uint32_t SLocOffset =
2878 endian::readNext<uint32_t, little, unaligned>(Data);
2879 uint32_t IdentifierIDOffset =
2880 endian::readNext<uint32_t, little, unaligned>(Data);
2881 uint32_t MacroIDOffset =
2882 endian::readNext<uint32_t, little, unaligned>(Data);
2883 uint32_t PreprocessedEntityIDOffset =
2884 endian::readNext<uint32_t, little, unaligned>(Data);
2885 uint32_t SubmoduleIDOffset =
2886 endian::readNext<uint32_t, little, unaligned>(Data);
2887 uint32_t SelectorIDOffset =
2888 endian::readNext<uint32_t, little, unaligned>(Data);
2889 uint32_t DeclIDOffset =
2890 endian::readNext<uint32_t, little, unaligned>(Data);
2891 uint32_t TypeIndexOffset =
2892 endian::readNext<uint32_t, little, unaligned>(Data);
2893
Ben Langmuir785180e2014-10-20 16:27:30 +00002894 uint32_t None = std::numeric_limits<uint32_t>::max();
2895
2896 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2897 RemapBuilder &Remap) {
2898 if (Offset != None)
2899 Remap.insert(std::make_pair(Offset,
2900 static_cast<int>(BaseOffset - Offset)));
2901 };
2902 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2903 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2904 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2905 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2906 PreprocessedEntityRemap);
2907 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2908 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2909 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2910 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002911
2912 // Global -> local mappings.
2913 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2914 }
2915 break;
2916 }
2917
2918 case SOURCE_MANAGER_LINE_TABLE:
2919 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002920 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 break;
2922
2923 case SOURCE_LOCATION_PRELOADS: {
2924 // Need to transform from the local view (1-based IDs) to the global view,
2925 // which is based off F.SLocEntryBaseID.
2926 if (!F.PreloadSLocEntries.empty()) {
2927 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 F.PreloadSLocEntries.swap(Record);
2932 break;
2933 }
2934
2935 case EXT_VECTOR_DECLS:
2936 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2937 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2938 break;
2939
2940 case VTABLE_USES:
2941 if (Record.size() % 3 != 0) {
2942 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
2945
2946 // Later tables overwrite earlier ones.
2947 // FIXME: Modules will have some trouble with this. This is clearly not
2948 // the right way to do this.
2949 VTableUses.clear();
2950
2951 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2952 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2953 VTableUses.push_back(
2954 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2955 VTableUses.push_back(Record[Idx++]);
2956 }
2957 break;
2958
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 case PENDING_IMPLICIT_INSTANTIATIONS:
2960 if (PendingInstantiations.size() % 2 != 0) {
2961 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002962 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 }
2964
2965 if (Record.size() % 2 != 0) {
2966 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002967 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 }
2969
2970 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2971 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2972 PendingInstantiations.push_back(
2973 ReadSourceLocation(F, Record, I).getRawEncoding());
2974 }
2975 break;
2976
2977 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002978 if (Record.size() != 2) {
2979 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2983 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2984 break;
2985
2986 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002987 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2988 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2989 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002990
2991 unsigned LocalBasePreprocessedEntityID = Record[0];
2992
2993 unsigned StartingID;
2994 if (!PP.getPreprocessingRecord())
2995 PP.createPreprocessingRecord();
2996 if (!PP.getPreprocessingRecord()->getExternalSource())
2997 PP.getPreprocessingRecord()->SetExternalSource(*this);
2998 StartingID
2999 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003000 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 F.BasePreprocessedEntityID = StartingID;
3002
3003 if (F.NumPreprocessedEntities > 0) {
3004 // Introduce the global -> local mapping for preprocessed entities in
3005 // this module.
3006 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3007
3008 // Introduce the local -> global mapping for preprocessed entities in
3009 // this module.
3010 F.PreprocessedEntityRemap.insertOrReplace(
3011 std::make_pair(LocalBasePreprocessedEntityID,
3012 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3013 }
3014
3015 break;
3016 }
3017
3018 case DECL_UPDATE_OFFSETS: {
3019 if (Record.size() % 2 != 0) {
3020 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003023 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3024 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3025 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3026
3027 // If we've already loaded the decl, perform the updates when we finish
3028 // loading this block.
3029 if (Decl *D = GetExistingDecl(ID))
3030 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3031 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 break;
3033 }
3034
3035 case DECL_REPLACEMENTS: {
3036 if (Record.size() % 3 != 0) {
3037 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
3040 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3041 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3042 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3043 break;
3044 }
3045
3046 case OBJC_CATEGORIES_MAP: {
3047 if (F.LocalNumObjCCategoriesInMap != 0) {
3048 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
3051
3052 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003053 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 break;
3055 }
3056
3057 case OBJC_CATEGORIES:
3058 F.ObjCCategories.swap(Record);
3059 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003060
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 case CXX_BASE_SPECIFIER_OFFSETS: {
3062 if (F.LocalNumCXXBaseSpecifiers != 0) {
3063 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003064 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003066
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003068 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003069 break;
3070 }
3071
3072 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3073 if (F.LocalNumCXXCtorInitializers != 0) {
3074 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3075 return Failure;
3076 }
3077
3078 F.LocalNumCXXCtorInitializers = Record[0];
3079 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 break;
3081 }
3082
3083 case DIAG_PRAGMA_MAPPINGS:
3084 if (F.PragmaDiagMappings.empty())
3085 F.PragmaDiagMappings.swap(Record);
3086 else
3087 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3088 Record.begin(), Record.end());
3089 break;
3090
3091 case CUDA_SPECIAL_DECL_REFS:
3092 // Later tables overwrite earlier ones.
3093 // FIXME: Modules will have trouble with this.
3094 CUDASpecialDeclRefs.clear();
3095 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3096 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3097 break;
3098
3099 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003100 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 if (Record[0]) {
3103 F.HeaderFileInfoTable
3104 = HeaderFileInfoLookupTable::Create(
3105 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3106 (const unsigned char *)F.HeaderFileInfoTableData,
3107 HeaderFileInfoTrait(*this, F,
3108 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003109 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003110
3111 PP.getHeaderSearchInfo().SetExternalSource(this);
3112 if (!PP.getHeaderSearchInfo().getExternalLookup())
3113 PP.getHeaderSearchInfo().SetExternalLookup(this);
3114 }
3115 break;
3116 }
3117
3118 case FP_PRAGMA_OPTIONS:
3119 // Later tables overwrite earlier ones.
3120 FPPragmaOptions.swap(Record);
3121 break;
3122
3123 case OPENCL_EXTENSIONS:
3124 // Later tables overwrite earlier ones.
3125 OpenCLExtensions.swap(Record);
3126 break;
3127
3128 case TENTATIVE_DEFINITIONS:
3129 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3130 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3131 break;
3132
3133 case KNOWN_NAMESPACES:
3134 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3135 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3136 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003137
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003138 case UNDEFINED_BUT_USED:
3139 if (UndefinedButUsed.size() % 2 != 0) {
3140 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003141 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003142 }
3143
3144 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003145 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003146 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003147 }
3148 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003149 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3150 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003151 ReadSourceLocation(F, Record, I).getRawEncoding());
3152 }
3153 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003154 case DELETE_EXPRS_TO_ANALYZE:
3155 for (unsigned I = 0, N = Record.size(); I != N;) {
3156 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3157 const uint64_t Count = Record[I++];
3158 DelayedDeleteExprs.push_back(Count);
3159 for (uint64_t C = 0; C < Count; ++C) {
3160 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3161 bool IsArrayForm = Record[I++] == 1;
3162 DelayedDeleteExprs.push_back(IsArrayForm);
3163 }
3164 }
3165 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003166
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003168 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 // If we aren't loading a module (which has its own exports), make
3170 // all of the imported modules visible.
3171 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003172 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3173 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3174 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3175 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003176 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 }
3178 }
3179 break;
3180 }
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 case MACRO_OFFSET: {
3183 if (F.LocalNumMacros != 0) {
3184 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003185 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003187 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003188 F.LocalNumMacros = Record[0];
3189 unsigned LocalBaseMacroID = Record[1];
3190 F.BaseMacroID = getTotalNumMacros();
3191
3192 if (F.LocalNumMacros > 0) {
3193 // Introduce the global -> local mapping for macros within this module.
3194 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3195
3196 // Introduce the local -> global mapping for macros within this module.
3197 F.MacroRemap.insertOrReplace(
3198 std::make_pair(LocalBaseMacroID,
3199 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003200
3201 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 }
3203 break;
3204 }
3205
Richard Smithe40f2ba2013-08-07 21:41:30 +00003206 case LATE_PARSED_TEMPLATE: {
3207 LateParsedTemplates.append(Record.begin(), Record.end());
3208 break;
3209 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003210
3211 case OPTIMIZE_PRAGMA_OPTIONS:
3212 if (Record.size() != 1) {
3213 Error("invalid pragma optimize record");
3214 return Failure;
3215 }
3216 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3217 break;
Nico Weber72889432014-09-06 01:25:55 +00003218
3219 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3220 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3221 UnusedLocalTypedefNameCandidates.push_back(
3222 getGlobalDeclID(F, Record[I]));
3223 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 }
3225 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003226}
3227
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003228ASTReader::ASTReadResult
3229ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3230 const ModuleFile *ImportedBy,
3231 unsigned ClientLoadCapabilities) {
3232 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003233 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003234
Richard Smithe842a472014-10-22 02:05:46 +00003235 if (F.Kind == MK_ExplicitModule) {
3236 // For an explicitly-loaded module, we don't care whether the original
3237 // module map file exists or matches.
3238 return Success;
3239 }
3240
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003241 // Try to resolve ModuleName in the current header search context and
3242 // verify that it is found in the same module map file as we saved. If the
3243 // top-level AST file is a main file, skip this check because there is no
3244 // usable header search context.
3245 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003246 "MODULE_NAME should come before MODULE_MAP_FILE");
3247 if (F.Kind == MK_ImplicitModule &&
3248 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3249 // An implicitly-loaded module file should have its module listed in some
3250 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003251 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003252 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3253 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3254 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003255 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003256 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3257 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3258 // This module was defined by an imported (explicit) module.
3259 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3260 << ASTFE->getName();
3261 else
3262 // This module was built with a different module map.
3263 Diag(diag::err_imported_module_not_found)
3264 << F.ModuleName << F.FileName << ImportedBy->FileName
3265 << F.ModuleMapPath;
3266 }
3267 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003268 }
3269
Richard Smithe842a472014-10-22 02:05:46 +00003270 assert(M->Name == F.ModuleName && "found module with different name");
3271
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003272 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003273 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003274 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3275 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003276 assert(ImportedBy && "top-level import should be verified");
3277 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3278 Diag(diag::err_imported_module_modmap_changed)
3279 << F.ModuleName << ImportedBy->FileName
3280 << ModMap->getName() << F.ModuleMapPath;
3281 return OutOfDate;
3282 }
3283
3284 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3285 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3286 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003287 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003288 const FileEntry *F =
3289 FileMgr.getFile(Filename, false, false);
3290 if (F == nullptr) {
3291 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3292 Error("could not find file '" + Filename +"' referenced by AST file");
3293 return OutOfDate;
3294 }
3295 AdditionalStoredMaps.insert(F);
3296 }
3297
3298 // Check any additional module map files (e.g. module.private.modulemap)
3299 // that are not in the pcm.
3300 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3301 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3302 // Remove files that match
3303 // Note: SmallPtrSet::erase is really remove
3304 if (!AdditionalStoredMaps.erase(ModMap)) {
3305 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3306 Diag(diag::err_module_different_modmap)
3307 << F.ModuleName << /*new*/0 << ModMap->getName();
3308 return OutOfDate;
3309 }
3310 }
3311 }
3312
3313 // Check any additional module map files that are in the pcm, but not
3314 // found in header search. Cases that match are already removed.
3315 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3316 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3317 Diag(diag::err_module_different_modmap)
3318 << F.ModuleName << /*not new*/1 << ModMap->getName();
3319 return OutOfDate;
3320 }
3321 }
3322
3323 if (Listener)
3324 Listener->ReadModuleMapFile(F.ModuleMapPath);
3325 return Success;
3326}
3327
3328
Douglas Gregorc1489562013-02-12 23:36:21 +00003329/// \brief Move the given method to the back of the global list of methods.
3330static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3331 // Find the entry for this selector in the method pool.
3332 Sema::GlobalMethodPool::iterator Known
3333 = S.MethodPool.find(Method->getSelector());
3334 if (Known == S.MethodPool.end())
3335 return;
3336
3337 // Retrieve the appropriate method list.
3338 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3339 : Known->second.second;
3340 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003341 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003342 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003343 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003344 Found = true;
3345 } else {
3346 // Keep searching.
3347 continue;
3348 }
3349 }
3350
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003351 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003352 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003353 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003354 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003355 }
3356}
3357
Richard Smithde711422015-04-23 21:20:19 +00003358void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003359 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003360 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003361 bool wasHidden = D->Hidden;
3362 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003363
Richard Smith49f906a2014-03-01 00:08:04 +00003364 if (wasHidden && SemaObj) {
3365 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3366 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003367 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 }
3369 }
3370}
3371
Richard Smith49f906a2014-03-01 00:08:04 +00003372void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003373 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003374 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003376 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003377 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003379 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003380
3381 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003382 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 // there is nothing more to do.
3384 continue;
3385 }
Richard Smith49f906a2014-03-01 00:08:04 +00003386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 if (!Mod->isAvailable()) {
3388 // Modules that aren't available cannot be made visible.
3389 continue;
3390 }
3391
3392 // Update the module's name visibility.
3393 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 // If we've already deserialized any names from this module,
3396 // mark them as visible.
3397 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3398 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003399 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003401 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003402 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3403 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003405
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003407 SmallVector<Module *, 16> Exports;
3408 Mod->getExportedModules(Exports);
3409 for (SmallVectorImpl<Module *>::iterator
3410 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3411 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003412 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003413 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 }
3415 }
3416}
3417
Douglas Gregore060e572013-01-25 01:03:03 +00003418bool ASTReader::loadGlobalIndex() {
3419 if (GlobalIndex)
3420 return false;
3421
3422 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3423 !Context.getLangOpts().Modules)
3424 return true;
3425
3426 // Try to load the global index.
3427 TriedLoadingGlobalIndex = true;
3428 StringRef ModuleCachePath
3429 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3430 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003431 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003432 if (!Result.first)
3433 return true;
3434
3435 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003436 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003437 return false;
3438}
3439
3440bool ASTReader::isGlobalIndexUnavailable() const {
3441 return Context.getLangOpts().Modules && UseGlobalIndex &&
3442 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3443}
3444
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003445static void updateModuleTimestamp(ModuleFile &MF) {
3446 // Overwrite the timestamp file contents so that file's mtime changes.
3447 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003448 std::error_code EC;
3449 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3450 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003451 return;
3452 OS << "Timestamp file\n";
3453}
3454
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003455/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3456/// cursor into the start of the given block ID, returning false on success and
3457/// true on failure.
3458static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3459 while (1) {
3460 llvm::BitstreamEntry Entry = Cursor.advance();
3461 switch (Entry.Kind) {
3462 case llvm::BitstreamEntry::Error:
3463 case llvm::BitstreamEntry::EndBlock:
3464 return true;
3465
3466 case llvm::BitstreamEntry::Record:
3467 // Ignore top-level records.
3468 Cursor.skipRecord(Entry.ID);
3469 break;
3470
3471 case llvm::BitstreamEntry::SubBlock:
3472 if (Entry.ID == BlockID) {
3473 if (Cursor.EnterSubBlock(BlockID))
3474 return true;
3475 // Found it!
3476 return false;
3477 }
3478
3479 if (Cursor.SkipBlock())
3480 return true;
3481 }
3482 }
3483}
3484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3486 ModuleKind Type,
3487 SourceLocation ImportLoc,
3488 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003489 llvm::SaveAndRestore<SourceLocation>
3490 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3491
Richard Smithd1c46742014-04-30 02:24:17 +00003492 // Defer any pending actions until we get to the end of reading the AST file.
3493 Deserializing AnASTFile(this);
3494
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003496 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
3498 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003499 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003501 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003502 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 ClientLoadCapabilities)) {
3504 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003505 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003506 case OutOfDate:
3507 case VersionMismatch:
3508 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003509 case HadErrors: {
3510 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3511 for (const ImportedModule &IM : Loaded)
3512 LoadedSet.insert(IM.Mod);
3513
Douglas Gregor7029ce12013-03-19 00:28:20 +00003514 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003515 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003516 Context.getLangOpts().Modules
3517 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003518 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003519
3520 // If we find that any modules are unusable, the global index is going
3521 // to be out-of-date. Just remove it.
3522 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003523 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 case Success:
3527 break;
3528 }
3529
3530 // Here comes stuff that we only do once the entire chain is loaded.
3531
3532 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003533 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3534 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 M != MEnd; ++M) {
3536 ModuleFile &F = *M->Mod;
3537
3538 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003539 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3540 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003541
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003542 // Read the extension blocks.
3543 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3544 if (ASTReadResult Result = ReadExtensionBlock(F))
3545 return Result;
3546 }
3547
Guy Benyei11169dd2012-12-18 14:30:41 +00003548 // Once read, set the ModuleFile bit base offset and update the size in
3549 // bits of all files we've seen.
3550 F.GlobalBitOffset = TotalModulesSizeInBits;
3551 TotalModulesSizeInBits += F.SizeInBits;
3552 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3553
3554 // Preload SLocEntries.
3555 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3556 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3557 // Load it through the SourceManager and don't call ReadSLocEntry()
3558 // directly because the entry may have already been loaded in which case
3559 // calling ReadSLocEntry() directly would trigger an assertion in
3560 // SourceManager.
3561 SourceMgr.getLoadedSLocEntryByID(Index);
3562 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003563
3564 // Preload all the pending interesting identifiers by marking them out of
3565 // date.
3566 for (auto Offset : F.PreloadIdentifierOffsets) {
3567 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3568 F.IdentifierTableData + Offset);
3569
3570 ASTIdentifierLookupTrait Trait(*this, F);
3571 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3572 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003573 auto &II = PP.getIdentifierTable().getOwn(Key);
3574 II.setOutOfDate(true);
3575
3576 // Mark this identifier as being from an AST file so that we can track
3577 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003578 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003579
3580 // Associate the ID with the identifier so that the writer can reuse it.
3581 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3582 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003583 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003584 }
3585
Douglas Gregor603cd862013-03-22 18:50:14 +00003586 // Setup the import locations and notify the module manager that we've
3587 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003588 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3589 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 M != MEnd; ++M) {
3591 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003592
3593 ModuleMgr.moduleFileAccepted(&F);
3594
3595 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003596 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003597 if (!M->ImportedBy)
3598 F.ImportLoc = M->ImportLoc;
3599 else
3600 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3601 M->ImportLoc.getRawEncoding());
3602 }
3603
Richard Smith33e0f7e2015-07-22 02:08:40 +00003604 if (!Context.getLangOpts().CPlusPlus ||
3605 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3606 // Mark all of the identifiers in the identifier table as being out of date,
3607 // so that various accessors know to check the loaded modules when the
3608 // identifier is used.
3609 //
3610 // For C++ modules, we don't need information on many identifiers (just
3611 // those that provide macros or are poisoned), so we mark all of
3612 // the interesting ones via PreloadIdentifierOffsets.
3613 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3614 IdEnd = PP.getIdentifierTable().end();
3615 Id != IdEnd; ++Id)
3616 Id->second->setOutOfDate(true);
3617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003618
3619 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003620 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3621 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3623 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003624
3625 switch (Unresolved.Kind) {
3626 case UnresolvedModuleRef::Conflict:
3627 if (ResolvedMod) {
3628 Module::Conflict Conflict;
3629 Conflict.Other = ResolvedMod;
3630 Conflict.Message = Unresolved.String.str();
3631 Unresolved.Mod->Conflicts.push_back(Conflict);
3632 }
3633 continue;
3634
3635 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003637 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003639
Douglas Gregorfb912652013-03-20 21:10:35 +00003640 case UnresolvedModuleRef::Export:
3641 if (ResolvedMod || Unresolved.IsWildcard)
3642 Unresolved.Mod->Exports.push_back(
3643 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3644 continue;
3645 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003646 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003647 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003648
3649 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3650 // Might be unnecessary as use declarations are only used to build the
3651 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003652
3653 InitializeContext();
3654
Richard Smith3d8e97e2013-10-18 06:54:39 +00003655 if (SemaObj)
3656 UpdateSema();
3657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 if (DeserializationListener)
3659 DeserializationListener->ReaderInitialized(this);
3660
3661 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003662 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 PrimaryModule.OriginalSourceFileID
3664 = FileID::get(PrimaryModule.SLocEntryBaseID
3665 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3666
3667 // If this AST file is a precompiled preamble, then set the
3668 // preamble file ID of the source manager to the file source file
3669 // from which the preamble was built.
3670 if (Type == MK_Preamble) {
3671 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3672 } else if (Type == MK_MainFile) {
3673 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3674 }
3675 }
3676
3677 // For any Objective-C class definitions we have already loaded, make sure
3678 // that we load any additional categories.
3679 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3680 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3681 ObjCClassesLoaded[I],
3682 PreviousGeneration);
3683 }
Douglas Gregore060e572013-01-25 01:03:03 +00003684
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003685 if (PP.getHeaderSearchInfo()
3686 .getHeaderSearchOpts()
3687 .ModulesValidateOncePerBuildSession) {
3688 // Now we are certain that the module and all modules it depends on are
3689 // up to date. Create or update timestamp files for modules that are
3690 // located in the module cache (not for PCH files that could be anywhere
3691 // in the filesystem).
3692 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3693 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003694 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003695 updateModuleTimestamp(*M.Mod);
3696 }
3697 }
3698 }
3699
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 return Success;
3701}
3702
Ben Langmuir487ea142014-10-23 18:05:36 +00003703static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3704
Ben Langmuir70a1b812015-03-24 04:43:52 +00003705/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3706static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3707 return Stream.Read(8) == 'C' &&
3708 Stream.Read(8) == 'P' &&
3709 Stream.Read(8) == 'C' &&
3710 Stream.Read(8) == 'H';
3711}
3712
Richard Smith0f99d6a2015-08-09 08:48:41 +00003713static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3714 switch (Kind) {
3715 case MK_PCH:
3716 return 0; // PCH
3717 case MK_ImplicitModule:
3718 case MK_ExplicitModule:
3719 return 1; // module
3720 case MK_MainFile:
3721 case MK_Preamble:
3722 return 2; // main source file
3723 }
3724 llvm_unreachable("unknown module kind");
3725}
3726
Guy Benyei11169dd2012-12-18 14:30:41 +00003727ASTReader::ASTReadResult
3728ASTReader::ReadASTCore(StringRef FileName,
3729 ModuleKind Type,
3730 SourceLocation ImportLoc,
3731 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003732 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003733 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003734 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 unsigned ClientLoadCapabilities) {
3736 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003738 ModuleManager::AddModuleResult AddResult
3739 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003740 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003741 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003742 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003743
Douglas Gregor7029ce12013-03-19 00:28:20 +00003744 switch (AddResult) {
3745 case ModuleManager::AlreadyLoaded:
3746 return Success;
3747
3748 case ModuleManager::NewlyLoaded:
3749 // Load module file below.
3750 break;
3751
3752 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003753 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003754 // it.
3755 if (ClientLoadCapabilities & ARR_Missing)
3756 return Missing;
3757
3758 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003759 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3760 << FileName << ErrorStr.empty()
3761 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003762 return Failure;
3763
3764 case ModuleManager::OutOfDate:
3765 // We couldn't load the module file because it is out-of-date. If the
3766 // client can handle out-of-date, return it.
3767 if (ClientLoadCapabilities & ARR_OutOfDate)
3768 return OutOfDate;
3769
3770 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003771 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3772 << FileName << ErrorStr.empty()
3773 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 return Failure;
3775 }
3776
Douglas Gregor7029ce12013-03-19 00:28:20 +00003777 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
3779 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3780 // module?
3781 if (FileName != "-") {
3782 CurrentDir = llvm::sys::path::parent_path(FileName);
3783 if (CurrentDir.empty()) CurrentDir = ".";
3784 }
3785
3786 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003787 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003788 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003789 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003790 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3791
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003793 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003794 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3795 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003796 return Failure;
3797 }
3798
3799 // This is used for compatibility with older PCH formats.
3800 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003801 while (1) {
3802 llvm::BitstreamEntry Entry = Stream.advance();
3803
3804 switch (Entry.Kind) {
3805 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003806 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003807 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 Error("invalid record at top-level of AST file");
3809 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003810
3811 case llvm::BitstreamEntry::SubBlock:
3812 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003813 }
3814
Chris Lattnerefa77172013-01-20 00:00:22 +00003815 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 case CONTROL_BLOCK_ID:
3817 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003818 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003820 // Check that we didn't try to load a non-module AST file as a module.
3821 //
3822 // FIXME: Should we also perform the converse check? Loading a module as
3823 // a PCH file sort of works, but it's a bit wonky.
3824 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3825 F.ModuleName.empty()) {
3826 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3827 if (Result != OutOfDate ||
3828 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3829 Diag(diag::err_module_file_not_module) << FileName;
3830 return Result;
3831 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 break;
3833
3834 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003835 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 case OutOfDate: return OutOfDate;
3837 case VersionMismatch: return VersionMismatch;
3838 case ConfigurationMismatch: return ConfigurationMismatch;
3839 case HadErrors: return HadErrors;
3840 }
3841 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003842
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 case AST_BLOCK_ID:
3844 if (!HaveReadControlBlock) {
3845 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003846 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003847 return VersionMismatch;
3848 }
3849
3850 // Record that we've loaded this module.
3851 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3852 return Success;
3853
3854 default:
3855 if (Stream.SkipBlock()) {
3856 Error("malformed block record in AST file");
3857 return Failure;
3858 }
3859 break;
3860 }
3861 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003862
3863 return Success;
3864}
3865
3866/// Parse a record and blob containing module file extension metadata.
3867static bool parseModuleFileExtensionMetadata(
3868 const SmallVectorImpl<uint64_t> &Record,
3869 StringRef Blob,
3870 ModuleFileExtensionMetadata &Metadata) {
3871 if (Record.size() < 4) return true;
3872
3873 Metadata.MajorVersion = Record[0];
3874 Metadata.MinorVersion = Record[1];
3875
3876 unsigned BlockNameLen = Record[2];
3877 unsigned UserInfoLen = Record[3];
3878
3879 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3880
3881 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3882 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3883 Blob.data() + BlockNameLen + UserInfoLen);
3884 return false;
3885}
3886
3887ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3888 BitstreamCursor &Stream = F.Stream;
3889
3890 RecordData Record;
3891 while (true) {
3892 llvm::BitstreamEntry Entry = Stream.advance();
3893 switch (Entry.Kind) {
3894 case llvm::BitstreamEntry::SubBlock:
3895 if (Stream.SkipBlock())
3896 return Failure;
3897
3898 continue;
3899
3900 case llvm::BitstreamEntry::EndBlock:
3901 return Success;
3902
3903 case llvm::BitstreamEntry::Error:
3904 return HadErrors;
3905
3906 case llvm::BitstreamEntry::Record:
3907 break;
3908 }
3909
3910 Record.clear();
3911 StringRef Blob;
3912 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3913 switch (RecCode) {
3914 case EXTENSION_METADATA: {
3915 ModuleFileExtensionMetadata Metadata;
3916 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3917 return Failure;
3918
3919 // Find a module file extension with this block name.
3920 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3921 if (Known == ModuleFileExtensions.end()) break;
3922
3923 // Form a reader.
3924 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3925 F, Stream)) {
3926 F.ExtensionReaders.push_back(std::move(Reader));
3927 }
3928
3929 break;
3930 }
3931 }
3932 }
3933
3934 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003935}
3936
Richard Smitha7e2cc62015-05-01 01:53:09 +00003937void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 // If there's a listener, notify them that we "read" the translation unit.
3939 if (DeserializationListener)
3940 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3941 Context.getTranslationUnitDecl());
3942
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 // FIXME: Find a better way to deal with collisions between these
3944 // built-in types. Right now, we just ignore the problem.
3945
3946 // Load the special types.
3947 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3948 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3949 if (!Context.CFConstantStringTypeDecl)
3950 Context.setCFConstantStringType(GetType(String));
3951 }
3952
3953 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3954 QualType FileType = GetType(File);
3955 if (FileType.isNull()) {
3956 Error("FILE type is NULL");
3957 return;
3958 }
3959
3960 if (!Context.FILEDecl) {
3961 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3962 Context.setFILEDecl(Typedef->getDecl());
3963 else {
3964 const TagType *Tag = FileType->getAs<TagType>();
3965 if (!Tag) {
3966 Error("Invalid FILE type in AST file");
3967 return;
3968 }
3969 Context.setFILEDecl(Tag->getDecl());
3970 }
3971 }
3972 }
3973
3974 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3975 QualType Jmp_bufType = GetType(Jmp_buf);
3976 if (Jmp_bufType.isNull()) {
3977 Error("jmp_buf type is NULL");
3978 return;
3979 }
3980
3981 if (!Context.jmp_bufDecl) {
3982 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3983 Context.setjmp_bufDecl(Typedef->getDecl());
3984 else {
3985 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3986 if (!Tag) {
3987 Error("Invalid jmp_buf type in AST file");
3988 return;
3989 }
3990 Context.setjmp_bufDecl(Tag->getDecl());
3991 }
3992 }
3993 }
3994
3995 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3996 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3997 if (Sigjmp_bufType.isNull()) {
3998 Error("sigjmp_buf type is NULL");
3999 return;
4000 }
4001
4002 if (!Context.sigjmp_bufDecl) {
4003 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4004 Context.setsigjmp_bufDecl(Typedef->getDecl());
4005 else {
4006 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4007 assert(Tag && "Invalid sigjmp_buf type in AST file");
4008 Context.setsigjmp_bufDecl(Tag->getDecl());
4009 }
4010 }
4011 }
4012
4013 if (unsigned ObjCIdRedef
4014 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4015 if (Context.ObjCIdRedefinitionType.isNull())
4016 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4017 }
4018
4019 if (unsigned ObjCClassRedef
4020 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4021 if (Context.ObjCClassRedefinitionType.isNull())
4022 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4023 }
4024
4025 if (unsigned ObjCSelRedef
4026 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4027 if (Context.ObjCSelRedefinitionType.isNull())
4028 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4029 }
4030
4031 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4032 QualType Ucontext_tType = GetType(Ucontext_t);
4033 if (Ucontext_tType.isNull()) {
4034 Error("ucontext_t type is NULL");
4035 return;
4036 }
4037
4038 if (!Context.ucontext_tDecl) {
4039 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4040 Context.setucontext_tDecl(Typedef->getDecl());
4041 else {
4042 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4043 assert(Tag && "Invalid ucontext_t type in AST file");
4044 Context.setucontext_tDecl(Tag->getDecl());
4045 }
4046 }
4047 }
4048 }
4049
4050 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4051
4052 // If there were any CUDA special declarations, deserialize them.
4053 if (!CUDASpecialDeclRefs.empty()) {
4054 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4055 Context.setcudaConfigureCallDecl(
4056 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4057 }
Richard Smith56be7542014-03-21 00:33:59 +00004058
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004060 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004061 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004062 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004063 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004064 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004065 if (Import.ImportLoc.isValid())
4066 PP.makeModuleVisible(Imported, Import.ImportLoc);
4067 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004068 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 }
4070 ImportedModules.clear();
4071}
4072
4073void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004074 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004075}
4076
Ben Langmuir70a1b812015-03-24 04:43:52 +00004077/// \brief Reads and return the signature record from \p StreamFile's control
4078/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004079static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4080 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004081 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004082 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004083
4084 // Scan for the CONTROL_BLOCK_ID block.
4085 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4086 return 0;
4087
4088 // Scan for SIGNATURE inside the control block.
4089 ASTReader::RecordData Record;
4090 while (1) {
4091 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4092 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4093 Entry.Kind != llvm::BitstreamEntry::Record)
4094 return 0;
4095
4096 Record.clear();
4097 StringRef Blob;
4098 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4099 return Record[0];
4100 }
4101}
4102
Guy Benyei11169dd2012-12-18 14:30:41 +00004103/// \brief Retrieve the name of the original source file name
4104/// directly from the AST file, without actually loading the AST
4105/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004106std::string ASTReader::getOriginalSourceFile(
4107 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004108 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004110 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004112 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4113 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 return std::string();
4115 }
4116
4117 // Initialize the stream
4118 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004119 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004120 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004121
4122 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004123 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4125 return std::string();
4126 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004127
Chris Lattnere7b154b2013-01-19 21:39:22 +00004128 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004129 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004130 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4131 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004132 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004133
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134 // Scan for ORIGINAL_FILE inside the control block.
4135 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004136 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004137 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004138 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4139 return std::string();
4140
4141 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4142 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4143 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004145
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004147 StringRef Blob;
4148 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4149 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004151}
4152
4153namespace {
4154 class SimplePCHValidator : public ASTReaderListener {
4155 const LangOptions &ExistingLangOpts;
4156 const TargetOptions &ExistingTargetOpts;
4157 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004158 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004160
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 public:
4162 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4163 const TargetOptions &ExistingTargetOpts,
4164 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004165 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 FileManager &FileMgr)
4167 : ExistingLangOpts(ExistingLangOpts),
4168 ExistingTargetOpts(ExistingTargetOpts),
4169 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004170 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 FileMgr(FileMgr)
4172 {
4173 }
4174
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004175 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4176 bool AllowCompatibleDifferences) override {
4177 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4178 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004180 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4181 bool AllowCompatibleDifferences) override {
4182 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4183 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004185 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4186 StringRef SpecificModuleCachePath,
4187 bool Complain) override {
4188 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4189 ExistingModuleCachePath,
4190 nullptr, ExistingLangOpts);
4191 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004192 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4193 bool Complain,
4194 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004195 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004196 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
4198 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004199}
Guy Benyei11169dd2012-12-18 14:30:41 +00004200
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004201bool ASTReader::readASTFileControlBlock(
4202 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004203 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004204 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004205 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004207 // FIXME: This allows use of the VFS; we do not allow use of the
4208 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004209 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 if (!Buffer) {
4211 return true;
4212 }
4213
4214 // Initialize the stream
4215 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004216 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004217 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
4219 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004220 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004222
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004223 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004224 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004225 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004226
4227 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004228 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004229 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004230 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004231
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004233 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004234 bool DoneWithControlBlock = false;
4235 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004236 llvm::BitstreamEntry Entry = Stream.advance();
4237
4238 switch (Entry.Kind) {
4239 case llvm::BitstreamEntry::SubBlock: {
4240 switch (Entry.ID) {
4241 case OPTIONS_BLOCK_ID: {
4242 std::string IgnoredSuggestedPredefines;
4243 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4244 /*AllowCompatibleConfigurationMismatch*/ false,
4245 Listener, IgnoredSuggestedPredefines) != Success)
4246 return true;
4247 break;
4248 }
4249
4250 case INPUT_FILES_BLOCK_ID:
4251 InputFilesCursor = Stream;
4252 if (Stream.SkipBlock() ||
4253 (NeedsInputFiles &&
4254 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4255 return true;
4256 break;
4257
4258 default:
4259 if (Stream.SkipBlock())
4260 return true;
4261 break;
4262 }
4263
4264 continue;
4265 }
4266
4267 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004268 DoneWithControlBlock = true;
4269 break;
Richard Smith0516b182015-09-08 19:40:14 +00004270
4271 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004272 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004273
4274 case llvm::BitstreamEntry::Record:
4275 break;
4276 }
4277
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004278 if (DoneWithControlBlock) break;
4279
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004281 StringRef Blob;
4282 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004283 switch ((ControlRecordTypes)RecCode) {
4284 case METADATA: {
4285 if (Record[0] != VERSION_MAJOR)
4286 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004288 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004289 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004290
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291 break;
4292 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004293 case MODULE_NAME:
4294 Listener.ReadModuleName(Blob);
4295 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004296 case MODULE_DIRECTORY:
4297 ModuleDir = Blob;
4298 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004299 case MODULE_MAP_FILE: {
4300 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004301 auto Path = ReadString(Record, Idx);
4302 ResolveImportedPath(Path, ModuleDir);
4303 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004304 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004305 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004306 case INPUT_FILE_OFFSETS: {
4307 if (!NeedsInputFiles)
4308 break;
4309
4310 unsigned NumInputFiles = Record[0];
4311 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004312 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004313 for (unsigned I = 0; I != NumInputFiles; ++I) {
4314 // Go find this input file.
4315 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004316
4317 if (isSystemFile && !NeedsSystemInputFiles)
4318 break; // the rest are system input files
4319
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004320 BitstreamCursor &Cursor = InputFilesCursor;
4321 SavedStreamPosition SavedPosition(Cursor);
4322 Cursor.JumpToBit(InputFileOffs[I]);
4323
4324 unsigned Code = Cursor.ReadCode();
4325 RecordData Record;
4326 StringRef Blob;
4327 bool shouldContinue = false;
4328 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4329 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004330 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004331 std::string Filename = Blob;
4332 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004333 shouldContinue = Listener.visitInputFile(
4334 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004335 break;
4336 }
4337 if (!shouldContinue)
4338 break;
4339 }
4340 break;
4341 }
4342
Richard Smithd4b230b2014-10-27 23:01:16 +00004343 case IMPORTS: {
4344 if (!NeedsImports)
4345 break;
4346
4347 unsigned Idx = 0, N = Record.size();
4348 while (Idx < N) {
4349 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004350 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004351 std::string Filename = ReadString(Record, Idx);
4352 ResolveImportedPath(Filename, ModuleDir);
4353 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004354 }
4355 break;
4356 }
4357
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004358 default:
4359 // No other validation to perform.
4360 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 }
4362 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004363
4364 // Look for module file extension blocks, if requested.
4365 if (FindModuleFileExtensions) {
4366 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4367 bool DoneWithExtensionBlock = false;
4368 while (!DoneWithExtensionBlock) {
4369 llvm::BitstreamEntry Entry = Stream.advance();
4370
4371 switch (Entry.Kind) {
4372 case llvm::BitstreamEntry::SubBlock:
4373 if (Stream.SkipBlock())
4374 return true;
4375
4376 continue;
4377
4378 case llvm::BitstreamEntry::EndBlock:
4379 DoneWithExtensionBlock = true;
4380 continue;
4381
4382 case llvm::BitstreamEntry::Error:
4383 return true;
4384
4385 case llvm::BitstreamEntry::Record:
4386 break;
4387 }
4388
4389 Record.clear();
4390 StringRef Blob;
4391 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4392 switch (RecCode) {
4393 case EXTENSION_METADATA: {
4394 ModuleFileExtensionMetadata Metadata;
4395 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4396 return true;
4397
4398 Listener.readModuleFileExtension(Metadata);
4399 break;
4400 }
4401 }
4402 }
4403 }
4404 }
4405
4406 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004407}
4408
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004409bool ASTReader::isAcceptableASTFile(
4410 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004411 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004412 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4413 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004414 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4415 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004416 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004417 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004418 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004419}
4420
Ben Langmuir2c9af442014-04-10 17:57:43 +00004421ASTReader::ASTReadResult
4422ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 // Enter the submodule block.
4424 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4425 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004426 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 }
4428
4429 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4430 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004431 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 RecordData Record;
4433 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004434 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4435
4436 switch (Entry.Kind) {
4437 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4438 case llvm::BitstreamEntry::Error:
4439 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004440 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004441 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004442 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004443 case llvm::BitstreamEntry::Record:
4444 // The interesting case.
4445 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004447
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004449 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004451 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4452
4453 if ((Kind == SUBMODULE_METADATA) != First) {
4454 Error("submodule metadata record should be at beginning of block");
4455 return Failure;
4456 }
4457 First = false;
4458
4459 // Submodule information is only valid if we have a current module.
4460 // FIXME: Should we error on these cases?
4461 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4462 Kind != SUBMODULE_DEFINITION)
4463 continue;
4464
4465 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 default: // Default behavior: ignore.
4467 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004468
Richard Smith03478d92014-10-23 22:12:14 +00004469 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004470 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004472 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
Richard Smith03478d92014-10-23 22:12:14 +00004474
Chris Lattner0e6c9402013-01-20 02:38:54 +00004475 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004476 unsigned Idx = 0;
4477 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4478 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4479 bool IsFramework = Record[Idx++];
4480 bool IsExplicit = Record[Idx++];
4481 bool IsSystem = Record[Idx++];
4482 bool IsExternC = Record[Idx++];
4483 bool InferSubmodules = Record[Idx++];
4484 bool InferExplicitSubmodules = Record[Idx++];
4485 bool InferExportWildcard = Record[Idx++];
4486 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004487
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004488 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004489 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004491
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 // Retrieve this (sub)module from the module map, creating it if
4493 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004494 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004496
4497 // FIXME: set the definition loc for CurrentModule, or call
4498 // ModMap.setInferredModuleAllowedBy()
4499
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4501 if (GlobalIndex >= SubmodulesLoaded.size() ||
4502 SubmodulesLoaded[GlobalIndex]) {
4503 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004504 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004506
Douglas Gregor7029ce12013-03-19 00:28:20 +00004507 if (!ParentModule) {
4508 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4509 if (CurFile != F.File) {
4510 if (!Diags.isDiagnosticInFlight()) {
4511 Diag(diag::err_module_file_conflict)
4512 << CurrentModule->getTopLevelModuleName()
4513 << CurFile->getName()
4514 << F.File->getName();
4515 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004516 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004517 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004518 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004519
4520 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004521 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004522
Adrian Prantl15bcf702015-06-30 17:39:43 +00004523 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 CurrentModule->IsFromModuleFile = true;
4525 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004526 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 CurrentModule->InferSubmodules = InferSubmodules;
4528 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4529 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004530 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 if (DeserializationListener)
4532 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4533
4534 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004535
Douglas Gregorfb912652013-03-20 21:10:35 +00004536 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004537 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004538 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004539 CurrentModule->UnresolvedConflicts.clear();
4540 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 break;
4542 }
4543
4544 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004545 std::string Filename = Blob;
4546 ResolveImportedPath(F, Filename);
4547 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004549 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4550 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004551 // This can be a spurious difference caused by changing the VFS to
4552 // point to a different copy of the file, and it is too late to
4553 // to rebuild safely.
4554 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4555 // after input file validation only real problems would remain and we
4556 // could just error. For now, assume it's okay.
4557 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 }
4559 }
4560 break;
4561 }
4562
Richard Smith202210b2014-10-24 20:23:01 +00004563 case SUBMODULE_HEADER:
4564 case SUBMODULE_EXCLUDED_HEADER:
4565 case SUBMODULE_PRIVATE_HEADER:
4566 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004567 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4568 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004569 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004570
Richard Smith202210b2014-10-24 20:23:01 +00004571 case SUBMODULE_TEXTUAL_HEADER:
4572 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4573 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4574 // them here.
4575 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004576
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004578 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 break;
4580 }
4581
4582 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004583 std::string Dirname = Blob;
4584 ResolveImportedPath(F, Dirname);
4585 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004587 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4588 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004589 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4590 Error("mismatched umbrella directories in submodule");
4591 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 }
4593 }
4594 break;
4595 }
4596
4597 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 F.BaseSubmoduleID = getTotalNumSubmodules();
4599 F.LocalNumSubmodules = Record[0];
4600 unsigned LocalBaseSubmoduleID = Record[1];
4601 if (F.LocalNumSubmodules > 0) {
4602 // Introduce the global -> local mapping for submodules within this
4603 // module.
4604 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4605
4606 // Introduce the local -> global mapping for submodules within this
4607 // module.
4608 F.SubmoduleRemap.insertOrReplace(
4609 std::make_pair(LocalBaseSubmoduleID,
4610 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004611
Ben Langmuir52ca6782014-10-20 16:27:32 +00004612 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4613 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 break;
4615 }
4616
4617 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004619 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 Unresolved.File = &F;
4621 Unresolved.Mod = CurrentModule;
4622 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004623 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004625 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627 break;
4628 }
4629
4630 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004632 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 Unresolved.File = &F;
4634 Unresolved.Mod = CurrentModule;
4635 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004636 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004638 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 }
4640
4641 // Once we've loaded the set of exports, there's no reason to keep
4642 // the parsed, unresolved exports around.
4643 CurrentModule->UnresolvedExports.clear();
4644 break;
4645 }
4646 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004647 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 Context.getTargetInfo());
4649 break;
4650 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004651
4652 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004653 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004654 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004655 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004656
4657 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004658 CurrentModule->ConfigMacros.push_back(Blob.str());
4659 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004660
4661 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004662 UnresolvedModuleRef Unresolved;
4663 Unresolved.File = &F;
4664 Unresolved.Mod = CurrentModule;
4665 Unresolved.ID = Record[0];
4666 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4667 Unresolved.IsWildcard = false;
4668 Unresolved.String = Blob;
4669 UnresolvedModuleRefs.push_back(Unresolved);
4670 break;
4671 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 }
4673 }
4674}
4675
4676/// \brief Parse the record that corresponds to a LangOptions data
4677/// structure.
4678///
4679/// This routine parses the language options from the AST file and then gives
4680/// them to the AST listener if one is set.
4681///
4682/// \returns true if the listener deems the file unacceptable, false otherwise.
4683bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4684 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004685 ASTReaderListener &Listener,
4686 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 LangOptions LangOpts;
4688 unsigned Idx = 0;
4689#define LANGOPT(Name, Bits, Default, Description) \
4690 LangOpts.Name = Record[Idx++];
4691#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4692 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4693#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004694#define SANITIZER(NAME, ID) \
4695 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004696#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004697
Ben Langmuircd98cb72015-06-23 18:20:18 +00004698 for (unsigned N = Record[Idx++]; N; --N)
4699 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4700
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4702 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4703 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004704
Ben Langmuird4a667a2015-06-23 18:20:23 +00004705 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004706
4707 // Comment options.
4708 for (unsigned N = Record[Idx++]; N; --N) {
4709 LangOpts.CommentOpts.BlockCommandNames.push_back(
4710 ReadString(Record, Idx));
4711 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004712 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004713
Samuel Antaoee8fb302016-01-06 13:42:12 +00004714 // OpenMP offloading options.
4715 for (unsigned N = Record[Idx++]; N; --N) {
4716 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4717 }
4718
4719 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4720
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004721 return Listener.ReadLanguageOptions(LangOpts, Complain,
4722 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004723}
4724
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004725bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4726 ASTReaderListener &Listener,
4727 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 unsigned Idx = 0;
4729 TargetOptions TargetOpts;
4730 TargetOpts.Triple = ReadString(Record, Idx);
4731 TargetOpts.CPU = ReadString(Record, Idx);
4732 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 for (unsigned N = Record[Idx++]; N; --N) {
4734 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4735 }
4736 for (unsigned N = Record[Idx++]; N; --N) {
4737 TargetOpts.Features.push_back(ReadString(Record, Idx));
4738 }
4739
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004740 return Listener.ReadTargetOptions(TargetOpts, Complain,
4741 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004742}
4743
4744bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4745 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004746 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004748#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004749#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004750 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004751#include "clang/Basic/DiagnosticOptions.def"
4752
Richard Smith3be1cb22014-08-07 00:24:21 +00004753 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004754 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004755 for (unsigned N = Record[Idx++]; N; --N)
4756 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004757
4758 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4759}
4760
4761bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4762 ASTReaderListener &Listener) {
4763 FileSystemOptions FSOpts;
4764 unsigned Idx = 0;
4765 FSOpts.WorkingDir = ReadString(Record, Idx);
4766 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4767}
4768
4769bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4770 bool Complain,
4771 ASTReaderListener &Listener) {
4772 HeaderSearchOptions HSOpts;
4773 unsigned Idx = 0;
4774 HSOpts.Sysroot = ReadString(Record, Idx);
4775
4776 // Include entries.
4777 for (unsigned N = Record[Idx++]; N; --N) {
4778 std::string Path = ReadString(Record, Idx);
4779 frontend::IncludeDirGroup Group
4780 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 bool IsFramework = Record[Idx++];
4782 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004783 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4784 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 }
4786
4787 // System header prefixes.
4788 for (unsigned N = Record[Idx++]; N; --N) {
4789 std::string Prefix = ReadString(Record, Idx);
4790 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004791 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 }
4793
4794 HSOpts.ResourceDir = ReadString(Record, Idx);
4795 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004796 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 HSOpts.DisableModuleHash = Record[Idx++];
4798 HSOpts.UseBuiltinIncludes = Record[Idx++];
4799 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4800 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4801 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004802 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004803
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004804 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4805 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004806}
4807
4808bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4809 bool Complain,
4810 ASTReaderListener &Listener,
4811 std::string &SuggestedPredefines) {
4812 PreprocessorOptions PPOpts;
4813 unsigned Idx = 0;
4814
4815 // Macro definitions/undefs
4816 for (unsigned N = Record[Idx++]; N; --N) {
4817 std::string Macro = ReadString(Record, Idx);
4818 bool IsUndef = Record[Idx++];
4819 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4820 }
4821
4822 // Includes
4823 for (unsigned N = Record[Idx++]; N; --N) {
4824 PPOpts.Includes.push_back(ReadString(Record, Idx));
4825 }
4826
4827 // Macro Includes
4828 for (unsigned N = Record[Idx++]; N; --N) {
4829 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4830 }
4831
4832 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004833 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4835 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4836 PPOpts.ObjCXXARCStandardLibrary =
4837 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4838 SuggestedPredefines.clear();
4839 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4840 SuggestedPredefines);
4841}
4842
4843std::pair<ModuleFile *, unsigned>
4844ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4845 GlobalPreprocessedEntityMapType::iterator
4846 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4847 assert(I != GlobalPreprocessedEntityMap.end() &&
4848 "Corrupted global preprocessed entity map");
4849 ModuleFile *M = I->second;
4850 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4851 return std::make_pair(M, LocalIndex);
4852}
4853
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004854llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004855ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4856 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4857 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4858 Mod.NumPreprocessedEntities);
4859
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004860 return llvm::make_range(PreprocessingRecord::iterator(),
4861 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004862}
4863
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004864llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004865ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004866 return llvm::make_range(
4867 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4868 ModuleDeclIterator(this, &Mod,
4869 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004870}
4871
4872PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4873 PreprocessedEntityID PPID = Index+1;
4874 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4875 ModuleFile &M = *PPInfo.first;
4876 unsigned LocalIndex = PPInfo.second;
4877 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4878
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 if (!PP.getPreprocessingRecord()) {
4880 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004881 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 }
4883
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004884 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4885 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4886
4887 llvm::BitstreamEntry Entry =
4888 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4889 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004890 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004891
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 // Read the record.
4893 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4894 ReadSourceLocation(M, PPOffs.End));
4895 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004896 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 RecordData Record;
4898 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004899 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4900 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 switch (RecType) {
4902 case PPD_MACRO_EXPANSION: {
4903 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004904 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004905 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 if (isBuiltin)
4907 Name = getLocalIdentifier(M, Record[1]);
4908 else {
Richard Smith66a81862015-05-04 02:25:31 +00004909 PreprocessedEntityID GlobalID =
4910 getGlobalPreprocessedEntityID(M, Record[1]);
4911 Def = cast<MacroDefinitionRecord>(
4912 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 }
4914
4915 MacroExpansion *ME;
4916 if (isBuiltin)
4917 ME = new (PPRec) MacroExpansion(Name, Range);
4918 else
4919 ME = new (PPRec) MacroExpansion(Def, Range);
4920
4921 return ME;
4922 }
4923
4924 case PPD_MACRO_DEFINITION: {
4925 // Decode the identifier info and then check again; if the macro is
4926 // still defined and associated with the identifier,
4927 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004928 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004929
4930 if (DeserializationListener)
4931 DeserializationListener->MacroDefinitionRead(PPID, MD);
4932
4933 return MD;
4934 }
4935
4936 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004937 const char *FullFileNameStart = Blob.data() + Record[0];
4938 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004939 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 if (!FullFileName.empty())
4941 File = PP.getFileManager().getFile(FullFileName);
4942
4943 // FIXME: Stable encoding
4944 InclusionDirective::InclusionKind Kind
4945 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4946 InclusionDirective *ID
4947 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004948 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 Record[1], Record[3],
4950 File,
4951 Range);
4952 return ID;
4953 }
4954 }
4955
4956 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4957}
4958
4959/// \brief \arg SLocMapI points at a chunk of a module that contains no
4960/// preprocessed entities or the entities it contains are not the ones we are
4961/// looking for. Find the next module that contains entities and return the ID
4962/// of the first entry.
4963PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4964 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4965 ++SLocMapI;
4966 for (GlobalSLocOffsetMapType::const_iterator
4967 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4968 ModuleFile &M = *SLocMapI->second;
4969 if (M.NumPreprocessedEntities)
4970 return M.BasePreprocessedEntityID;
4971 }
4972
4973 return getTotalNumPreprocessedEntities();
4974}
4975
4976namespace {
4977
4978template <unsigned PPEntityOffset::*PPLoc>
4979struct PPEntityComp {
4980 const ASTReader &Reader;
4981 ModuleFile &M;
4982
4983 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4984
4985 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4986 SourceLocation LHS = getLoc(L);
4987 SourceLocation RHS = getLoc(R);
4988 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4989 }
4990
4991 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4992 SourceLocation LHS = getLoc(L);
4993 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4994 }
4995
4996 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4997 SourceLocation RHS = getLoc(R);
4998 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4999 }
5000
5001 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5002 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5003 }
5004};
5005
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005006}
Guy Benyei11169dd2012-12-18 14:30:41 +00005007
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005008PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5009 bool EndsAfter) const {
5010 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 return getTotalNumPreprocessedEntities();
5012
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005013 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5014 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5016 "Corrupted global sloc offset map");
5017
5018 if (SLocMapI->second->NumPreprocessedEntities == 0)
5019 return findNextPreprocessedEntity(SLocMapI);
5020
5021 ModuleFile &M = *SLocMapI->second;
5022 typedef const PPEntityOffset *pp_iterator;
5023 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5024 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5025
5026 size_t Count = M.NumPreprocessedEntities;
5027 size_t Half;
5028 pp_iterator First = pp_begin;
5029 pp_iterator PPI;
5030
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005031 if (EndsAfter) {
5032 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5033 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5034 } else {
5035 // Do a binary search manually instead of using std::lower_bound because
5036 // The end locations of entities may be unordered (when a macro expansion
5037 // is inside another macro argument), but for this case it is not important
5038 // whether we get the first macro expansion or its containing macro.
5039 while (Count > 0) {
5040 Half = Count / 2;
5041 PPI = First;
5042 std::advance(PPI, Half);
5043 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5044 Loc)) {
5045 First = PPI;
5046 ++First;
5047 Count = Count - Half - 1;
5048 } else
5049 Count = Half;
5050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 }
5052
5053 if (PPI == pp_end)
5054 return findNextPreprocessedEntity(SLocMapI);
5055
5056 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5057}
5058
Guy Benyei11169dd2012-12-18 14:30:41 +00005059/// \brief Returns a pair of [Begin, End) indices of preallocated
5060/// preprocessed entities that \arg Range encompasses.
5061std::pair<unsigned, unsigned>
5062 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5063 if (Range.isInvalid())
5064 return std::make_pair(0,0);
5065 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5066
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005067 PreprocessedEntityID BeginID =
5068 findPreprocessedEntity(Range.getBegin(), false);
5069 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 return std::make_pair(BeginID, EndID);
5071}
5072
5073/// \brief Optionally returns true or false if the preallocated preprocessed
5074/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005075Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 FileID FID) {
5077 if (FID.isInvalid())
5078 return false;
5079
5080 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5081 ModuleFile &M = *PPInfo.first;
5082 unsigned LocalIndex = PPInfo.second;
5083 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5084
5085 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5086 if (Loc.isInvalid())
5087 return false;
5088
5089 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5090 return true;
5091 else
5092 return false;
5093}
5094
5095namespace {
5096 /// \brief Visitor used to search for information about a header file.
5097 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 const FileEntry *FE;
5099
David Blaikie05785d12013-02-20 22:23:23 +00005100 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005101
5102 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005103 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5104 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005105
5106 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 HeaderFileInfoLookupTable *Table
5108 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5109 if (!Table)
5110 return false;
5111
5112 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005113 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 if (Pos == Table->end())
5115 return false;
5116
Richard Smithbdf2d932015-07-30 03:37:16 +00005117 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 return true;
5119 }
5120
David Blaikie05785d12013-02-20 22:23:23 +00005121 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005123}
Guy Benyei11169dd2012-12-18 14:30:41 +00005124
5125HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005126 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005127 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005128 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005130
5131 return HeaderFileInfo();
5132}
5133
5134void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5135 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005136 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5138 ModuleFile &F = *(*I);
5139 unsigned Idx = 0;
5140 DiagStates.clear();
5141 assert(!Diag.DiagStates.empty());
5142 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5143 while (Idx < F.PragmaDiagMappings.size()) {
5144 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5145 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5146 if (DiagStateID != 0) {
5147 Diag.DiagStatePoints.push_back(
5148 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5149 FullSourceLoc(Loc, SourceMgr)));
5150 continue;
5151 }
5152
5153 assert(DiagStateID == 0);
5154 // A new DiagState was created here.
5155 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5156 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5157 DiagStates.push_back(NewState);
5158 Diag.DiagStatePoints.push_back(
5159 DiagnosticsEngine::DiagStatePoint(NewState,
5160 FullSourceLoc(Loc, SourceMgr)));
5161 while (1) {
5162 assert(Idx < F.PragmaDiagMappings.size() &&
5163 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5164 if (Idx >= F.PragmaDiagMappings.size()) {
5165 break; // Something is messed up but at least avoid infinite loop in
5166 // release build.
5167 }
5168 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5169 if (DiagID == (unsigned)-1) {
5170 break; // no more diag/map pairs for this location.
5171 }
Alp Tokerc726c362014-06-10 09:31:37 +00005172 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5173 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5174 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 }
5176 }
5177 }
5178}
5179
5180/// \brief Get the correct cursor and offset for loading a type.
5181ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5182 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5183 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5184 ModuleFile *M = I->second;
5185 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5186}
5187
5188/// \brief Read and return the type with the given index..
5189///
5190/// The index is the type ID, shifted and minus the number of predefs. This
5191/// routine actually reads the record corresponding to the type at the given
5192/// location. It is a helper routine for GetType, which deals with reading type
5193/// IDs.
5194QualType ASTReader::readTypeRecord(unsigned Index) {
5195 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005196 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005197
5198 // Keep track of where we are in the stream, then jump back there
5199 // after reading this type.
5200 SavedStreamPosition SavedPosition(DeclsCursor);
5201
5202 ReadingKindTracker ReadingKind(Read_Type, *this);
5203
5204 // Note that we are loading a type record.
5205 Deserializing AType(this);
5206
5207 unsigned Idx = 0;
5208 DeclsCursor.JumpToBit(Loc.Offset);
5209 RecordData Record;
5210 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005211 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005212 case TYPE_EXT_QUAL: {
5213 if (Record.size() != 2) {
5214 Error("Incorrect encoding of extended qualifier type");
5215 return QualType();
5216 }
5217 QualType Base = readType(*Loc.F, Record, Idx);
5218 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5219 return Context.getQualifiedType(Base, Quals);
5220 }
5221
5222 case TYPE_COMPLEX: {
5223 if (Record.size() != 1) {
5224 Error("Incorrect encoding of complex type");
5225 return QualType();
5226 }
5227 QualType ElemType = readType(*Loc.F, Record, Idx);
5228 return Context.getComplexType(ElemType);
5229 }
5230
5231 case TYPE_POINTER: {
5232 if (Record.size() != 1) {
5233 Error("Incorrect encoding of pointer type");
5234 return QualType();
5235 }
5236 QualType PointeeType = readType(*Loc.F, Record, Idx);
5237 return Context.getPointerType(PointeeType);
5238 }
5239
Reid Kleckner8a365022013-06-24 17:51:48 +00005240 case TYPE_DECAYED: {
5241 if (Record.size() != 1) {
5242 Error("Incorrect encoding of decayed type");
5243 return QualType();
5244 }
5245 QualType OriginalType = readType(*Loc.F, Record, Idx);
5246 QualType DT = Context.getAdjustedParameterType(OriginalType);
5247 if (!isa<DecayedType>(DT))
5248 Error("Decayed type does not decay");
5249 return DT;
5250 }
5251
Reid Kleckner0503a872013-12-05 01:23:43 +00005252 case TYPE_ADJUSTED: {
5253 if (Record.size() != 2) {
5254 Error("Incorrect encoding of adjusted type");
5255 return QualType();
5256 }
5257 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5258 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5259 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5260 }
5261
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 case TYPE_BLOCK_POINTER: {
5263 if (Record.size() != 1) {
5264 Error("Incorrect encoding of block pointer type");
5265 return QualType();
5266 }
5267 QualType PointeeType = readType(*Loc.F, Record, Idx);
5268 return Context.getBlockPointerType(PointeeType);
5269 }
5270
5271 case TYPE_LVALUE_REFERENCE: {
5272 if (Record.size() != 2) {
5273 Error("Incorrect encoding of lvalue reference type");
5274 return QualType();
5275 }
5276 QualType PointeeType = readType(*Loc.F, Record, Idx);
5277 return Context.getLValueReferenceType(PointeeType, Record[1]);
5278 }
5279
5280 case TYPE_RVALUE_REFERENCE: {
5281 if (Record.size() != 1) {
5282 Error("Incorrect encoding of rvalue reference type");
5283 return QualType();
5284 }
5285 QualType PointeeType = readType(*Loc.F, Record, Idx);
5286 return Context.getRValueReferenceType(PointeeType);
5287 }
5288
5289 case TYPE_MEMBER_POINTER: {
5290 if (Record.size() != 2) {
5291 Error("Incorrect encoding of member pointer type");
5292 return QualType();
5293 }
5294 QualType PointeeType = readType(*Loc.F, Record, Idx);
5295 QualType ClassType = readType(*Loc.F, Record, Idx);
5296 if (PointeeType.isNull() || ClassType.isNull())
5297 return QualType();
5298
5299 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5300 }
5301
5302 case TYPE_CONSTANT_ARRAY: {
5303 QualType ElementType = readType(*Loc.F, Record, Idx);
5304 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5305 unsigned IndexTypeQuals = Record[2];
5306 unsigned Idx = 3;
5307 llvm::APInt Size = ReadAPInt(Record, Idx);
5308 return Context.getConstantArrayType(ElementType, Size,
5309 ASM, IndexTypeQuals);
5310 }
5311
5312 case TYPE_INCOMPLETE_ARRAY: {
5313 QualType ElementType = readType(*Loc.F, Record, Idx);
5314 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5315 unsigned IndexTypeQuals = Record[2];
5316 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5317 }
5318
5319 case TYPE_VARIABLE_ARRAY: {
5320 QualType ElementType = readType(*Loc.F, Record, Idx);
5321 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5322 unsigned IndexTypeQuals = Record[2];
5323 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5324 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5325 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5326 ASM, IndexTypeQuals,
5327 SourceRange(LBLoc, RBLoc));
5328 }
5329
5330 case TYPE_VECTOR: {
5331 if (Record.size() != 3) {
5332 Error("incorrect encoding of vector type in AST file");
5333 return QualType();
5334 }
5335
5336 QualType ElementType = readType(*Loc.F, Record, Idx);
5337 unsigned NumElements = Record[1];
5338 unsigned VecKind = Record[2];
5339 return Context.getVectorType(ElementType, NumElements,
5340 (VectorType::VectorKind)VecKind);
5341 }
5342
5343 case TYPE_EXT_VECTOR: {
5344 if (Record.size() != 3) {
5345 Error("incorrect encoding of extended vector type in AST file");
5346 return QualType();
5347 }
5348
5349 QualType ElementType = readType(*Loc.F, Record, Idx);
5350 unsigned NumElements = Record[1];
5351 return Context.getExtVectorType(ElementType, NumElements);
5352 }
5353
5354 case TYPE_FUNCTION_NO_PROTO: {
5355 if (Record.size() != 6) {
5356 Error("incorrect encoding of no-proto function type");
5357 return QualType();
5358 }
5359 QualType ResultType = readType(*Loc.F, Record, Idx);
5360 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5361 (CallingConv)Record[4], Record[5]);
5362 return Context.getFunctionNoProtoType(ResultType, Info);
5363 }
5364
5365 case TYPE_FUNCTION_PROTO: {
5366 QualType ResultType = readType(*Loc.F, Record, Idx);
5367
5368 FunctionProtoType::ExtProtoInfo EPI;
5369 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5370 /*hasregparm*/ Record[2],
5371 /*regparm*/ Record[3],
5372 static_cast<CallingConv>(Record[4]),
5373 /*produces*/ Record[5]);
5374
5375 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005376
5377 EPI.Variadic = Record[Idx++];
5378 EPI.HasTrailingReturn = Record[Idx++];
5379 EPI.TypeQuals = Record[Idx++];
5380 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005381 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005382 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005383
5384 unsigned NumParams = Record[Idx++];
5385 SmallVector<QualType, 16> ParamTypes;
5386 for (unsigned I = 0; I != NumParams; ++I)
5387 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5388
Jordan Rose5c382722013-03-08 21:51:21 +00005389 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 }
5391
5392 case TYPE_UNRESOLVED_USING: {
5393 unsigned Idx = 0;
5394 return Context.getTypeDeclType(
5395 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5396 }
5397
5398 case TYPE_TYPEDEF: {
5399 if (Record.size() != 2) {
5400 Error("incorrect encoding of typedef type");
5401 return QualType();
5402 }
5403 unsigned Idx = 0;
5404 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5405 QualType Canonical = readType(*Loc.F, Record, Idx);
5406 if (!Canonical.isNull())
5407 Canonical = Context.getCanonicalType(Canonical);
5408 return Context.getTypedefType(Decl, Canonical);
5409 }
5410
5411 case TYPE_TYPEOF_EXPR:
5412 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5413
5414 case TYPE_TYPEOF: {
5415 if (Record.size() != 1) {
5416 Error("incorrect encoding of typeof(type) in AST file");
5417 return QualType();
5418 }
5419 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5420 return Context.getTypeOfType(UnderlyingType);
5421 }
5422
5423 case TYPE_DECLTYPE: {
5424 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5425 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5426 }
5427
5428 case TYPE_UNARY_TRANSFORM: {
5429 QualType BaseType = readType(*Loc.F, Record, Idx);
5430 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5431 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5432 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5433 }
5434
Richard Smith74aeef52013-04-26 16:15:35 +00005435 case TYPE_AUTO: {
5436 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005437 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005438 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005439 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005441
5442 case TYPE_RECORD: {
5443 if (Record.size() != 2) {
5444 Error("incorrect encoding of record type");
5445 return QualType();
5446 }
5447 unsigned Idx = 0;
5448 bool IsDependent = Record[Idx++];
5449 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5450 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5451 QualType T = Context.getRecordType(RD);
5452 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5453 return T;
5454 }
5455
5456 case TYPE_ENUM: {
5457 if (Record.size() != 2) {
5458 Error("incorrect encoding of enum type");
5459 return QualType();
5460 }
5461 unsigned Idx = 0;
5462 bool IsDependent = Record[Idx++];
5463 QualType T
5464 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5465 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5466 return T;
5467 }
5468
5469 case TYPE_ATTRIBUTED: {
5470 if (Record.size() != 3) {
5471 Error("incorrect encoding of attributed type");
5472 return QualType();
5473 }
5474 QualType modifiedType = readType(*Loc.F, Record, Idx);
5475 QualType equivalentType = readType(*Loc.F, Record, Idx);
5476 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5477 return Context.getAttributedType(kind, modifiedType, equivalentType);
5478 }
5479
5480 case TYPE_PAREN: {
5481 if (Record.size() != 1) {
5482 Error("incorrect encoding of paren type");
5483 return QualType();
5484 }
5485 QualType InnerType = readType(*Loc.F, Record, Idx);
5486 return Context.getParenType(InnerType);
5487 }
5488
5489 case TYPE_PACK_EXPANSION: {
5490 if (Record.size() != 2) {
5491 Error("incorrect encoding of pack expansion type");
5492 return QualType();
5493 }
5494 QualType Pattern = readType(*Loc.F, Record, Idx);
5495 if (Pattern.isNull())
5496 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005497 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 if (Record[1])
5499 NumExpansions = Record[1] - 1;
5500 return Context.getPackExpansionType(Pattern, NumExpansions);
5501 }
5502
5503 case TYPE_ELABORATED: {
5504 unsigned Idx = 0;
5505 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5506 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5507 QualType NamedType = readType(*Loc.F, Record, Idx);
5508 return Context.getElaboratedType(Keyword, NNS, NamedType);
5509 }
5510
5511 case TYPE_OBJC_INTERFACE: {
5512 unsigned Idx = 0;
5513 ObjCInterfaceDecl *ItfD
5514 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5515 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5516 }
5517
5518 case TYPE_OBJC_OBJECT: {
5519 unsigned Idx = 0;
5520 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005521 unsigned NumTypeArgs = Record[Idx++];
5522 SmallVector<QualType, 4> TypeArgs;
5523 for (unsigned I = 0; I != NumTypeArgs; ++I)
5524 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005525 unsigned NumProtos = Record[Idx++];
5526 SmallVector<ObjCProtocolDecl*, 4> Protos;
5527 for (unsigned I = 0; I != NumProtos; ++I)
5528 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005529 bool IsKindOf = Record[Idx++];
5530 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005531 }
5532
5533 case TYPE_OBJC_OBJECT_POINTER: {
5534 unsigned Idx = 0;
5535 QualType Pointee = readType(*Loc.F, Record, Idx);
5536 return Context.getObjCObjectPointerType(Pointee);
5537 }
5538
5539 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5540 unsigned Idx = 0;
5541 QualType Parm = readType(*Loc.F, Record, Idx);
5542 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005543 return Context.getSubstTemplateTypeParmType(
5544 cast<TemplateTypeParmType>(Parm),
5545 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005546 }
5547
5548 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5549 unsigned Idx = 0;
5550 QualType Parm = readType(*Loc.F, Record, Idx);
5551 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5552 return Context.getSubstTemplateTypeParmPackType(
5553 cast<TemplateTypeParmType>(Parm),
5554 ArgPack);
5555 }
5556
5557 case TYPE_INJECTED_CLASS_NAME: {
5558 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5559 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5560 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5561 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005562 const Type *T = nullptr;
5563 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5564 if (const Type *Existing = DI->getTypeForDecl()) {
5565 T = Existing;
5566 break;
5567 }
5568 }
5569 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005570 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005571 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5572 DI->setTypeForDecl(T);
5573 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005574 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 }
5576
5577 case TYPE_TEMPLATE_TYPE_PARM: {
5578 unsigned Idx = 0;
5579 unsigned Depth = Record[Idx++];
5580 unsigned Index = Record[Idx++];
5581 bool Pack = Record[Idx++];
5582 TemplateTypeParmDecl *D
5583 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5584 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5585 }
5586
5587 case TYPE_DEPENDENT_NAME: {
5588 unsigned Idx = 0;
5589 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5590 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005591 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005592 QualType Canon = readType(*Loc.F, Record, Idx);
5593 if (!Canon.isNull())
5594 Canon = Context.getCanonicalType(Canon);
5595 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5596 }
5597
5598 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5599 unsigned Idx = 0;
5600 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5601 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005602 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005603 unsigned NumArgs = Record[Idx++];
5604 SmallVector<TemplateArgument, 8> Args;
5605 Args.reserve(NumArgs);
5606 while (NumArgs--)
5607 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5608 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5609 Args.size(), Args.data());
5610 }
5611
5612 case TYPE_DEPENDENT_SIZED_ARRAY: {
5613 unsigned Idx = 0;
5614
5615 // ArrayType
5616 QualType ElementType = readType(*Loc.F, Record, Idx);
5617 ArrayType::ArraySizeModifier ASM
5618 = (ArrayType::ArraySizeModifier)Record[Idx++];
5619 unsigned IndexTypeQuals = Record[Idx++];
5620
5621 // DependentSizedArrayType
5622 Expr *NumElts = ReadExpr(*Loc.F);
5623 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5624
5625 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5626 IndexTypeQuals, Brackets);
5627 }
5628
5629 case TYPE_TEMPLATE_SPECIALIZATION: {
5630 unsigned Idx = 0;
5631 bool IsDependent = Record[Idx++];
5632 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5633 SmallVector<TemplateArgument, 8> Args;
5634 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5635 QualType Underlying = readType(*Loc.F, Record, Idx);
5636 QualType T;
5637 if (Underlying.isNull())
5638 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5639 Args.size());
5640 else
5641 T = Context.getTemplateSpecializationType(Name, Args.data(),
5642 Args.size(), Underlying);
5643 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5644 return T;
5645 }
5646
5647 case TYPE_ATOMIC: {
5648 if (Record.size() != 1) {
5649 Error("Incorrect encoding of atomic type");
5650 return QualType();
5651 }
5652 QualType ValueType = readType(*Loc.F, Record, Idx);
5653 return Context.getAtomicType(ValueType);
5654 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005655
5656 case TYPE_PIPE: {
5657 if (Record.size() != 1) {
5658 Error("Incorrect encoding of pipe type");
5659 return QualType();
5660 }
5661
5662 // Reading the pipe element type.
5663 QualType ElementType = readType(*Loc.F, Record, Idx);
5664 return Context.getPipeType(ElementType);
5665 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 }
5667 llvm_unreachable("Invalid TypeCode!");
5668}
5669
Richard Smith564417a2014-03-20 21:47:22 +00005670void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5671 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005672 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005673 const RecordData &Record, unsigned &Idx) {
5674 ExceptionSpecificationType EST =
5675 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005676 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005677 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005678 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005679 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005680 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005681 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005682 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005683 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005684 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5685 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005686 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005687 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005688 }
5689}
5690
Guy Benyei11169dd2012-12-18 14:30:41 +00005691class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5692 ASTReader &Reader;
5693 ModuleFile &F;
5694 const ASTReader::RecordData &Record;
5695 unsigned &Idx;
5696
5697 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5698 unsigned &I) {
5699 return Reader.ReadSourceLocation(F, R, I);
5700 }
5701
5702 template<typename T>
5703 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5704 return Reader.ReadDeclAs<T>(F, Record, Idx);
5705 }
5706
5707public:
5708 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5709 const ASTReader::RecordData &Record, unsigned &Idx)
5710 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5711 { }
5712
5713 // We want compile-time assurance that we've enumerated all of
5714 // these, so unfortunately we have to declare them first, then
5715 // define them out-of-line.
5716#define ABSTRACT_TYPELOC(CLASS, PARENT)
5717#define TYPELOC(CLASS, PARENT) \
5718 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5719#include "clang/AST/TypeLocNodes.def"
5720
5721 void VisitFunctionTypeLoc(FunctionTypeLoc);
5722 void VisitArrayTypeLoc(ArrayTypeLoc);
5723};
5724
5725void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5726 // nothing to do
5727}
5728void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5729 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5730 if (TL.needsExtraLocalData()) {
5731 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5732 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5733 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5734 TL.setModeAttr(Record[Idx++]);
5735 }
5736}
5737void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5738 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5739}
5740void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5741 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5742}
Reid Kleckner8a365022013-06-24 17:51:48 +00005743void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5744 // nothing to do
5745}
Reid Kleckner0503a872013-12-05 01:23:43 +00005746void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5747 // nothing to do
5748}
Guy Benyei11169dd2012-12-18 14:30:41 +00005749void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5750 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5751}
5752void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5753 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5756 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5759 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5760 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5761}
5762void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5763 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5764 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5765 if (Record[Idx++])
5766 TL.setSizeExpr(Reader.ReadExpr(F));
5767 else
Craig Toppera13603a2014-05-22 05:54:18 +00005768 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005769}
5770void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5771 VisitArrayTypeLoc(TL);
5772}
5773void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5774 VisitArrayTypeLoc(TL);
5775}
5776void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5777 VisitArrayTypeLoc(TL);
5778}
5779void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5780 DependentSizedArrayTypeLoc TL) {
5781 VisitArrayTypeLoc(TL);
5782}
5783void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5784 DependentSizedExtVectorTypeLoc TL) {
5785 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5786}
5787void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5788 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5789}
5790void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5791 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5792}
5793void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5794 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5795 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5796 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5797 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005798 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5799 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005800 }
5801}
5802void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5803 VisitFunctionTypeLoc(TL);
5804}
5805void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5806 VisitFunctionTypeLoc(TL);
5807}
5808void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810}
5811void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5812 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5813}
5814void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5815 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5816 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5817 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5818}
5819void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5820 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5821 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5822 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5823 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5824}
5825void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5826 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5829 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5830 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5831 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5832 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5833}
5834void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5835 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836}
5837void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5838 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5839}
5840void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5841 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5842}
5843void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5844 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5845 if (TL.hasAttrOperand()) {
5846 SourceRange range;
5847 range.setBegin(ReadSourceLocation(Record, Idx));
5848 range.setEnd(ReadSourceLocation(Record, Idx));
5849 TL.setAttrOperandParensRange(range);
5850 }
5851 if (TL.hasAttrExprOperand()) {
5852 if (Record[Idx++])
5853 TL.setAttrExprOperand(Reader.ReadExpr(F));
5854 else
Craig Toppera13603a2014-05-22 05:54:18 +00005855 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005856 } else if (TL.hasAttrEnumOperand())
5857 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5858}
5859void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5860 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5861}
5862void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5863 SubstTemplateTypeParmTypeLoc TL) {
5864 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5865}
5866void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5867 SubstTemplateTypeParmPackTypeLoc TL) {
5868 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5869}
5870void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5871 TemplateSpecializationTypeLoc TL) {
5872 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5873 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5874 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5875 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5876 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5877 TL.setArgLocInfo(i,
5878 Reader.GetTemplateArgumentLocInfo(F,
5879 TL.getTypePtr()->getArg(i).getKind(),
5880 Record, Idx));
5881}
5882void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5883 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5884 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5885}
5886void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5887 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5888 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5889}
5890void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5891 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5892}
5893void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5894 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5895 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5896 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5899 DependentTemplateSpecializationTypeLoc TL) {
5900 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5901 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5902 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5903 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5904 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5905 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5906 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5907 TL.setArgLocInfo(I,
5908 Reader.GetTemplateArgumentLocInfo(F,
5909 TL.getTypePtr()->getArg(I).getKind(),
5910 Record, Idx));
5911}
5912void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5913 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5914}
5915void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5916 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5917}
5918void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5919 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005920 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5921 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5922 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5923 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5924 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5925 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5927 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5928}
5929void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5930 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5931}
5932void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5933 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5934 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5935 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5936}
Xiuli Pan9c14e282016-01-09 12:53:17 +00005937void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5938 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5939}
Guy Benyei11169dd2012-12-18 14:30:41 +00005940
5941TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5942 const RecordData &Record,
5943 unsigned &Idx) {
5944 QualType InfoTy = readType(F, Record, Idx);
5945 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005946 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005947
5948 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5949 TypeLocReader TLR(*this, F, Record, Idx);
5950 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5951 TLR.Visit(TL);
5952 return TInfo;
5953}
5954
5955QualType ASTReader::GetType(TypeID ID) {
5956 unsigned FastQuals = ID & Qualifiers::FastMask;
5957 unsigned Index = ID >> Qualifiers::FastWidth;
5958
5959 if (Index < NUM_PREDEF_TYPE_IDS) {
5960 QualType T;
5961 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005962 case PREDEF_TYPE_NULL_ID:
5963 return QualType();
5964 case PREDEF_TYPE_VOID_ID:
5965 T = Context.VoidTy;
5966 break;
5967 case PREDEF_TYPE_BOOL_ID:
5968 T = Context.BoolTy;
5969 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005970
5971 case PREDEF_TYPE_CHAR_U_ID:
5972 case PREDEF_TYPE_CHAR_S_ID:
5973 // FIXME: Check that the signedness of CharTy is correct!
5974 T = Context.CharTy;
5975 break;
5976
Alexey Baderbdf7c842015-09-15 12:18:29 +00005977 case PREDEF_TYPE_UCHAR_ID:
5978 T = Context.UnsignedCharTy;
5979 break;
5980 case PREDEF_TYPE_USHORT_ID:
5981 T = Context.UnsignedShortTy;
5982 break;
5983 case PREDEF_TYPE_UINT_ID:
5984 T = Context.UnsignedIntTy;
5985 break;
5986 case PREDEF_TYPE_ULONG_ID:
5987 T = Context.UnsignedLongTy;
5988 break;
5989 case PREDEF_TYPE_ULONGLONG_ID:
5990 T = Context.UnsignedLongLongTy;
5991 break;
5992 case PREDEF_TYPE_UINT128_ID:
5993 T = Context.UnsignedInt128Ty;
5994 break;
5995 case PREDEF_TYPE_SCHAR_ID:
5996 T = Context.SignedCharTy;
5997 break;
5998 case PREDEF_TYPE_WCHAR_ID:
5999 T = Context.WCharTy;
6000 break;
6001 case PREDEF_TYPE_SHORT_ID:
6002 T = Context.ShortTy;
6003 break;
6004 case PREDEF_TYPE_INT_ID:
6005 T = Context.IntTy;
6006 break;
6007 case PREDEF_TYPE_LONG_ID:
6008 T = Context.LongTy;
6009 break;
6010 case PREDEF_TYPE_LONGLONG_ID:
6011 T = Context.LongLongTy;
6012 break;
6013 case PREDEF_TYPE_INT128_ID:
6014 T = Context.Int128Ty;
6015 break;
6016 case PREDEF_TYPE_HALF_ID:
6017 T = Context.HalfTy;
6018 break;
6019 case PREDEF_TYPE_FLOAT_ID:
6020 T = Context.FloatTy;
6021 break;
6022 case PREDEF_TYPE_DOUBLE_ID:
6023 T = Context.DoubleTy;
6024 break;
6025 case PREDEF_TYPE_LONGDOUBLE_ID:
6026 T = Context.LongDoubleTy;
6027 break;
6028 case PREDEF_TYPE_OVERLOAD_ID:
6029 T = Context.OverloadTy;
6030 break;
6031 case PREDEF_TYPE_BOUND_MEMBER:
6032 T = Context.BoundMemberTy;
6033 break;
6034 case PREDEF_TYPE_PSEUDO_OBJECT:
6035 T = Context.PseudoObjectTy;
6036 break;
6037 case PREDEF_TYPE_DEPENDENT_ID:
6038 T = Context.DependentTy;
6039 break;
6040 case PREDEF_TYPE_UNKNOWN_ANY:
6041 T = Context.UnknownAnyTy;
6042 break;
6043 case PREDEF_TYPE_NULLPTR_ID:
6044 T = Context.NullPtrTy;
6045 break;
6046 case PREDEF_TYPE_CHAR16_ID:
6047 T = Context.Char16Ty;
6048 break;
6049 case PREDEF_TYPE_CHAR32_ID:
6050 T = Context.Char32Ty;
6051 break;
6052 case PREDEF_TYPE_OBJC_ID:
6053 T = Context.ObjCBuiltinIdTy;
6054 break;
6055 case PREDEF_TYPE_OBJC_CLASS:
6056 T = Context.ObjCBuiltinClassTy;
6057 break;
6058 case PREDEF_TYPE_OBJC_SEL:
6059 T = Context.ObjCBuiltinSelTy;
6060 break;
6061 case PREDEF_TYPE_IMAGE1D_ID:
6062 T = Context.OCLImage1dTy;
6063 break;
6064 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6065 T = Context.OCLImage1dArrayTy;
6066 break;
6067 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6068 T = Context.OCLImage1dBufferTy;
6069 break;
6070 case PREDEF_TYPE_IMAGE2D_ID:
6071 T = Context.OCLImage2dTy;
6072 break;
6073 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6074 T = Context.OCLImage2dArrayTy;
6075 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006076 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6077 T = Context.OCLImage2dDepthTy;
6078 break;
6079 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6080 T = Context.OCLImage2dArrayDepthTy;
6081 break;
6082 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6083 T = Context.OCLImage2dMSAATy;
6084 break;
6085 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6086 T = Context.OCLImage2dArrayMSAATy;
6087 break;
6088 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6089 T = Context.OCLImage2dMSAADepthTy;
6090 break;
6091 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6092 T = Context.OCLImage2dArrayMSAADepthTy;
6093 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006094 case PREDEF_TYPE_IMAGE3D_ID:
6095 T = Context.OCLImage3dTy;
6096 break;
6097 case PREDEF_TYPE_SAMPLER_ID:
6098 T = Context.OCLSamplerTy;
6099 break;
6100 case PREDEF_TYPE_EVENT_ID:
6101 T = Context.OCLEventTy;
6102 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006103 case PREDEF_TYPE_CLK_EVENT_ID:
6104 T = Context.OCLClkEventTy;
6105 break;
6106 case PREDEF_TYPE_QUEUE_ID:
6107 T = Context.OCLQueueTy;
6108 break;
6109 case PREDEF_TYPE_NDRANGE_ID:
6110 T = Context.OCLNDRangeTy;
6111 break;
6112 case PREDEF_TYPE_RESERVE_ID_ID:
6113 T = Context.OCLReserveIDTy;
6114 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006115 case PREDEF_TYPE_AUTO_DEDUCT:
6116 T = Context.getAutoDeductType();
6117 break;
6118
6119 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6120 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 break;
6122
6123 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6124 T = Context.ARCUnbridgedCastTy;
6125 break;
6126
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 case PREDEF_TYPE_BUILTIN_FN:
6128 T = Context.BuiltinFnTy;
6129 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006130
6131 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6132 T = Context.OMPArraySectionTy;
6133 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 }
6135
6136 assert(!T.isNull() && "Unknown predefined type");
6137 return T.withFastQualifiers(FastQuals);
6138 }
6139
6140 Index -= NUM_PREDEF_TYPE_IDS;
6141 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6142 if (TypesLoaded[Index].isNull()) {
6143 TypesLoaded[Index] = readTypeRecord(Index);
6144 if (TypesLoaded[Index].isNull())
6145 return QualType();
6146
6147 TypesLoaded[Index]->setFromAST();
6148 if (DeserializationListener)
6149 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6150 TypesLoaded[Index]);
6151 }
6152
6153 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6154}
6155
6156QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6157 return GetType(getGlobalTypeID(F, LocalID));
6158}
6159
6160serialization::TypeID
6161ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6162 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6163 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6164
6165 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6166 return LocalID;
6167
6168 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6169 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6170 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6171
6172 unsigned GlobalIndex = LocalIndex + I->second;
6173 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6174}
6175
6176TemplateArgumentLocInfo
6177ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6178 TemplateArgument::ArgKind Kind,
6179 const RecordData &Record,
6180 unsigned &Index) {
6181 switch (Kind) {
6182 case TemplateArgument::Expression:
6183 return ReadExpr(F);
6184 case TemplateArgument::Type:
6185 return GetTypeSourceInfo(F, Record, Index);
6186 case TemplateArgument::Template: {
6187 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6188 Index);
6189 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6190 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6191 SourceLocation());
6192 }
6193 case TemplateArgument::TemplateExpansion: {
6194 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6195 Index);
6196 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6197 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6198 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6199 EllipsisLoc);
6200 }
6201 case TemplateArgument::Null:
6202 case TemplateArgument::Integral:
6203 case TemplateArgument::Declaration:
6204 case TemplateArgument::NullPtr:
6205 case TemplateArgument::Pack:
6206 // FIXME: Is this right?
6207 return TemplateArgumentLocInfo();
6208 }
6209 llvm_unreachable("unexpected template argument loc");
6210}
6211
6212TemplateArgumentLoc
6213ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6214 const RecordData &Record, unsigned &Index) {
6215 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6216
6217 if (Arg.getKind() == TemplateArgument::Expression) {
6218 if (Record[Index++]) // bool InfoHasSameExpr.
6219 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6220 }
6221 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6222 Record, Index));
6223}
6224
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006225const ASTTemplateArgumentListInfo*
6226ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6227 const RecordData &Record,
6228 unsigned &Index) {
6229 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6230 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6231 unsigned NumArgsAsWritten = Record[Index++];
6232 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6233 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6234 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6235 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6236}
6237
Guy Benyei11169dd2012-12-18 14:30:41 +00006238Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6239 return GetDecl(ID);
6240}
6241
Richard Smith50895422015-01-31 03:04:55 +00006242template<typename TemplateSpecializationDecl>
6243static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6244 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6245 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6246}
6247
Richard Smith053f6c62014-05-16 23:01:30 +00006248void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006249 if (NumCurrentElementsDeserializing) {
6250 // We arrange to not care about the complete redeclaration chain while we're
6251 // deserializing. Just remember that the AST has marked this one as complete
6252 // but that it's not actually complete yet, so we know we still need to
6253 // complete it later.
6254 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6255 return;
6256 }
6257
Richard Smith053f6c62014-05-16 23:01:30 +00006258 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6259
Richard Smith053f6c62014-05-16 23:01:30 +00006260 // If this is a named declaration, complete it by looking it up
6261 // within its context.
6262 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006263 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006264 // all mergeable entities within it.
6265 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6266 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6267 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006268 if (!getContext().getLangOpts().CPlusPlus &&
6269 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006270 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006271 // the identifier instead. (For C++ modules, we don't store decls
6272 // in the serialized identifier table, so we do the lookup in the TU.)
6273 auto *II = Name.getAsIdentifierInfo();
6274 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006275 if (II->isOutOfDate())
6276 updateOutOfDateIdentifier(*II);
6277 } else
6278 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006279 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006280 // Find all declarations of this kind from the relevant context.
6281 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6282 auto *DC = cast<DeclContext>(DCDecl);
6283 SmallVector<Decl*, 8> Decls;
6284 FindExternalLexicalDecls(
6285 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6286 }
Richard Smith053f6c62014-05-16 23:01:30 +00006287 }
6288 }
Richard Smith50895422015-01-31 03:04:55 +00006289
6290 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6291 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6292 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6293 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6294 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6295 if (auto *Template = FD->getPrimaryTemplate())
6296 Template->LoadLazySpecializations();
6297 }
Richard Smith053f6c62014-05-16 23:01:30 +00006298}
6299
Richard Smithc2bb8182015-03-24 06:36:48 +00006300uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6301 const RecordData &Record,
6302 unsigned &Idx) {
6303 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6304 Error("malformed AST file: missing C++ ctor initializers");
6305 return 0;
6306 }
6307
6308 unsigned LocalID = Record[Idx++];
6309 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6310}
6311
6312CXXCtorInitializer **
6313ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6314 RecordLocation Loc = getLocalBitOffset(Offset);
6315 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6316 SavedStreamPosition SavedPosition(Cursor);
6317 Cursor.JumpToBit(Loc.Offset);
6318 ReadingKindTracker ReadingKind(Read_Decl, *this);
6319
6320 RecordData Record;
6321 unsigned Code = Cursor.ReadCode();
6322 unsigned RecCode = Cursor.readRecord(Code, Record);
6323 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6324 Error("malformed AST file: missing C++ ctor initializers");
6325 return nullptr;
6326 }
6327
6328 unsigned Idx = 0;
6329 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6330}
6331
Richard Smithcd45dbc2014-04-19 03:48:30 +00006332uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6333 const RecordData &Record,
6334 unsigned &Idx) {
6335 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6336 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006337 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006338 }
6339
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 unsigned LocalID = Record[Idx++];
6341 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6342}
6343
6344CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6345 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006346 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 SavedStreamPosition SavedPosition(Cursor);
6348 Cursor.JumpToBit(Loc.Offset);
6349 ReadingKindTracker ReadingKind(Read_Decl, *this);
6350 RecordData Record;
6351 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006352 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006354 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006355 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 }
6357
6358 unsigned Idx = 0;
6359 unsigned NumBases = Record[Idx++];
6360 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6361 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6362 for (unsigned I = 0; I != NumBases; ++I)
6363 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6364 return Bases;
6365}
6366
6367serialization::DeclID
6368ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6369 if (LocalID < NUM_PREDEF_DECL_IDS)
6370 return LocalID;
6371
6372 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6373 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6374 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6375
6376 return LocalID + I->second;
6377}
6378
6379bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6380 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006381 // Predefined decls aren't from any module.
6382 if (ID < NUM_PREDEF_DECL_IDS)
6383 return false;
6384
Richard Smithbcda1a92015-07-12 23:51:20 +00006385 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6386 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006387}
6388
Douglas Gregor9f782892013-01-21 15:25:38 +00006389ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006391 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006392 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6393 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6394 return I->second;
6395}
6396
6397SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6398 if (ID < NUM_PREDEF_DECL_IDS)
6399 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006400
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6402
6403 if (Index > DeclsLoaded.size()) {
6404 Error("declaration ID out-of-range for AST file");
6405 return SourceLocation();
6406 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006407
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 if (Decl *D = DeclsLoaded[Index])
6409 return D->getLocation();
6410
6411 unsigned RawLocation = 0;
6412 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6413 return ReadSourceLocation(*Rec.F, RawLocation);
6414}
6415
Richard Smithfe620d22015-03-05 23:24:12 +00006416static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6417 switch (ID) {
6418 case PREDEF_DECL_NULL_ID:
6419 return nullptr;
6420
6421 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6422 return Context.getTranslationUnitDecl();
6423
6424 case PREDEF_DECL_OBJC_ID_ID:
6425 return Context.getObjCIdDecl();
6426
6427 case PREDEF_DECL_OBJC_SEL_ID:
6428 return Context.getObjCSelDecl();
6429
6430 case PREDEF_DECL_OBJC_CLASS_ID:
6431 return Context.getObjCClassDecl();
6432
6433 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6434 return Context.getObjCProtocolDecl();
6435
6436 case PREDEF_DECL_INT_128_ID:
6437 return Context.getInt128Decl();
6438
6439 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6440 return Context.getUInt128Decl();
6441
6442 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6443 return Context.getObjCInstanceTypeDecl();
6444
6445 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6446 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006447
Richard Smith9b88a4c2015-07-27 05:40:23 +00006448 case PREDEF_DECL_VA_LIST_TAG:
6449 return Context.getVaListTagDecl();
6450
Charles Davisc7d5c942015-09-17 20:55:33 +00006451 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6452 return Context.getBuiltinMSVaListDecl();
6453
Richard Smithf19e1272015-03-07 00:04:49 +00006454 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6455 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006456
6457 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6458 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006459
6460 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6461 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006462
6463 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6464 return Context.getCFConstantStringTagDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006465 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006466 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006467}
6468
Richard Smithcd45dbc2014-04-19 03:48:30 +00006469Decl *ASTReader::GetExistingDecl(DeclID ID) {
6470 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006471 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6472 if (D) {
6473 // Track that we have merged the declaration with ID \p ID into the
6474 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006475 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006476 if (Merged.empty())
6477 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006478 }
Richard Smithfe620d22015-03-05 23:24:12 +00006479 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006481
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6483
6484 if (Index >= DeclsLoaded.size()) {
6485 assert(0 && "declaration ID out-of-range for AST file");
6486 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006487 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006489
6490 return DeclsLoaded[Index];
6491}
6492
6493Decl *ASTReader::GetDecl(DeclID ID) {
6494 if (ID < NUM_PREDEF_DECL_IDS)
6495 return GetExistingDecl(ID);
6496
6497 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6498
6499 if (Index >= DeclsLoaded.size()) {
6500 assert(0 && "declaration ID out-of-range for AST file");
6501 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006502 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006503 }
6504
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 if (!DeclsLoaded[Index]) {
6506 ReadDeclRecord(ID);
6507 if (DeserializationListener)
6508 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6509 }
6510
6511 return DeclsLoaded[Index];
6512}
6513
6514DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6515 DeclID GlobalID) {
6516 if (GlobalID < NUM_PREDEF_DECL_IDS)
6517 return GlobalID;
6518
6519 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6520 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6521 ModuleFile *Owner = I->second;
6522
6523 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6524 = M.GlobalToLocalDeclIDs.find(Owner);
6525 if (Pos == M.GlobalToLocalDeclIDs.end())
6526 return 0;
6527
6528 return GlobalID - Owner->BaseDeclID + Pos->second;
6529}
6530
6531serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6532 const RecordData &Record,
6533 unsigned &Idx) {
6534 if (Idx >= Record.size()) {
6535 Error("Corrupted AST file");
6536 return 0;
6537 }
6538
6539 return getGlobalDeclID(F, Record[Idx++]);
6540}
6541
6542/// \brief Resolve the offset of a statement into a statement.
6543///
6544/// This operation will read a new statement from the external
6545/// source each time it is called, and is meant to be used via a
6546/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6547Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6548 // Switch case IDs are per Decl.
6549 ClearSwitchCaseIDs();
6550
6551 // Offset here is a global offset across the entire chain.
6552 RecordLocation Loc = getLocalBitOffset(Offset);
6553 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6554 return ReadStmtFromStream(*Loc.F);
6555}
6556
Richard Smith3cb15722015-08-05 22:41:45 +00006557void ASTReader::FindExternalLexicalDecls(
6558 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6559 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006560 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6561
Richard Smith9ccdd932015-08-06 22:14:12 +00006562 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006563 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6564 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6565 auto K = (Decl::Kind)+LexicalDecls[I];
6566 if (!IsKindWeWant(K))
6567 continue;
6568
6569 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6570
6571 // Don't add predefined declarations to the lexical context more
6572 // than once.
6573 if (ID < NUM_PREDEF_DECL_IDS) {
6574 if (PredefsVisited[ID])
6575 continue;
6576
6577 PredefsVisited[ID] = true;
6578 }
6579
6580 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006581 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006582 if (!DC->isDeclInLexicalTraversal(D))
6583 Decls.push_back(D);
6584 }
6585 }
6586 };
6587
6588 if (isa<TranslationUnitDecl>(DC)) {
6589 for (auto Lexical : TULexicalDecls)
6590 Visit(Lexical.first, Lexical.second);
6591 } else {
6592 auto I = LexicalDecls.find(DC);
6593 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006594 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006595 }
6596
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006598}
6599
6600namespace {
6601
6602class DeclIDComp {
6603 ASTReader &Reader;
6604 ModuleFile &Mod;
6605
6606public:
6607 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6608
6609 bool operator()(LocalDeclID L, LocalDeclID R) const {
6610 SourceLocation LHS = getLocation(L);
6611 SourceLocation RHS = getLocation(R);
6612 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6613 }
6614
6615 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6616 SourceLocation RHS = getLocation(R);
6617 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6618 }
6619
6620 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6621 SourceLocation LHS = getLocation(L);
6622 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6623 }
6624
6625 SourceLocation getLocation(LocalDeclID ID) const {
6626 return Reader.getSourceManager().getFileLoc(
6627 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6628 }
6629};
6630
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006631}
Guy Benyei11169dd2012-12-18 14:30:41 +00006632
6633void ASTReader::FindFileRegionDecls(FileID File,
6634 unsigned Offset, unsigned Length,
6635 SmallVectorImpl<Decl *> &Decls) {
6636 SourceManager &SM = getSourceManager();
6637
6638 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6639 if (I == FileDeclIDs.end())
6640 return;
6641
6642 FileDeclsInfo &DInfo = I->second;
6643 if (DInfo.Decls.empty())
6644 return;
6645
6646 SourceLocation
6647 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6648 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6649
6650 DeclIDComp DIDComp(*this, *DInfo.Mod);
6651 ArrayRef<serialization::LocalDeclID>::iterator
6652 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6653 BeginLoc, DIDComp);
6654 if (BeginIt != DInfo.Decls.begin())
6655 --BeginIt;
6656
6657 // If we are pointing at a top-level decl inside an objc container, we need
6658 // to backtrack until we find it otherwise we will fail to report that the
6659 // region overlaps with an objc container.
6660 while (BeginIt != DInfo.Decls.begin() &&
6661 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6662 ->isTopLevelDeclInObjCContainer())
6663 --BeginIt;
6664
6665 ArrayRef<serialization::LocalDeclID>::iterator
6666 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6667 EndLoc, DIDComp);
6668 if (EndIt != DInfo.Decls.end())
6669 ++EndIt;
6670
6671 for (ArrayRef<serialization::LocalDeclID>::iterator
6672 DIt = BeginIt; DIt != EndIt; ++DIt)
6673 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6674}
6675
Richard Smith9ce12e32013-02-07 03:30:24 +00006676bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006677ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6678 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006679 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 "DeclContext has no visible decls in storage");
6681 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006682 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006683
Richard Smithd88a7f12015-09-01 20:35:42 +00006684 auto It = Lookups.find(DC);
6685 if (It == Lookups.end())
6686 return false;
6687
Richard Smith8c913ec2014-08-14 02:21:01 +00006688 Deserializing LookupResults(this);
6689
Richard Smithd88a7f12015-09-01 20:35:42 +00006690 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006692 for (DeclID ID : It->second.Table.find(Name)) {
6693 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6694 if (ND->getDeclName() == Name)
6695 Decls.push_back(ND);
6696 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 ++NumVisibleDeclContextsRead;
6699 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006700 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006701}
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6704 if (!DC->hasExternalVisibleStorage())
6705 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006706
6707 auto It = Lookups.find(DC);
6708 assert(It != Lookups.end() &&
6709 "have external visible storage but no lookup tables");
6710
Craig Topper79be4cd2013-07-05 04:33:53 +00006711 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006712
Richard Smithd88a7f12015-09-01 20:35:42 +00006713 for (DeclID ID : It->second.Table.findAll()) {
6714 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6715 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 }
6717
Guy Benyei11169dd2012-12-18 14:30:41 +00006718 ++NumVisibleDeclContextsRead;
6719
Craig Topper79be4cd2013-07-05 04:33:53 +00006720 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6722 }
6723 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6724}
6725
Richard Smithd88a7f12015-09-01 20:35:42 +00006726const serialization::reader::DeclContextLookupTable *
6727ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6728 auto I = Lookups.find(Primary);
6729 return I == Lookups.end() ? nullptr : &I->second;
6730}
6731
Guy Benyei11169dd2012-12-18 14:30:41 +00006732/// \brief Under non-PCH compilation the consumer receives the objc methods
6733/// before receiving the implementation, and codegen depends on this.
6734/// We simulate this by deserializing and passing to consumer the methods of the
6735/// implementation before passing the deserialized implementation decl.
6736static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6737 ASTConsumer *Consumer) {
6738 assert(ImplD && Consumer);
6739
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006740 for (auto *I : ImplD->methods())
6741 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006742
6743 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6744}
6745
6746void ASTReader::PassInterestingDeclsToConsumer() {
6747 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006748
6749 if (PassingDeclsToConsumer)
6750 return;
6751
6752 // Guard variable to avoid recursively redoing the process of passing
6753 // decls to consumer.
6754 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6755 true);
6756
Richard Smith9e2341d2015-03-23 03:25:59 +00006757 // Ensure that we've loaded all potentially-interesting declarations
6758 // that need to be eagerly loaded.
6759 for (auto ID : EagerlyDeserializedDecls)
6760 GetDecl(ID);
6761 EagerlyDeserializedDecls.clear();
6762
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 while (!InterestingDecls.empty()) {
6764 Decl *D = InterestingDecls.front();
6765 InterestingDecls.pop_front();
6766
6767 PassInterestingDeclToConsumer(D);
6768 }
6769}
6770
6771void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6772 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6773 PassObjCImplDeclToConsumer(ImplD, Consumer);
6774 else
6775 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6776}
6777
6778void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6779 this->Consumer = Consumer;
6780
Richard Smith9e2341d2015-03-23 03:25:59 +00006781 if (Consumer)
6782 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006783
6784 if (DeserializationListener)
6785 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006786}
6787
6788void ASTReader::PrintStats() {
6789 std::fprintf(stderr, "*** AST File Statistics:\n");
6790
6791 unsigned NumTypesLoaded
6792 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6793 QualType());
6794 unsigned NumDeclsLoaded
6795 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006796 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 unsigned NumIdentifiersLoaded
6798 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6799 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006800 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006801 unsigned NumMacrosLoaded
6802 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6803 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006804 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 unsigned NumSelectorsLoaded
6806 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6807 SelectorsLoaded.end(),
6808 Selector());
6809
6810 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6811 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6812 NumSLocEntriesRead, TotalNumSLocEntries,
6813 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6814 if (!TypesLoaded.empty())
6815 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6816 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6817 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6818 if (!DeclsLoaded.empty())
6819 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6820 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6821 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6822 if (!IdentifiersLoaded.empty())
6823 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6824 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6825 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6826 if (!MacrosLoaded.empty())
6827 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6828 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6829 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6830 if (!SelectorsLoaded.empty())
6831 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6832 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6833 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6834 if (TotalNumStatements)
6835 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6836 NumStatementsRead, TotalNumStatements,
6837 ((float)NumStatementsRead/TotalNumStatements * 100));
6838 if (TotalNumMacros)
6839 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6840 NumMacrosRead, TotalNumMacros,
6841 ((float)NumMacrosRead/TotalNumMacros * 100));
6842 if (TotalLexicalDeclContexts)
6843 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6844 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6845 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6846 * 100));
6847 if (TotalVisibleDeclContexts)
6848 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6849 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6850 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6851 * 100));
6852 if (TotalNumMethodPoolEntries) {
6853 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6854 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6855 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6856 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006858 if (NumMethodPoolLookups) {
6859 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6860 NumMethodPoolHits, NumMethodPoolLookups,
6861 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6862 }
6863 if (NumMethodPoolTableLookups) {
6864 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6865 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6866 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6867 * 100.0));
6868 }
6869
Douglas Gregor00a50f72013-01-25 00:38:33 +00006870 if (NumIdentifierLookupHits) {
6871 std::fprintf(stderr,
6872 " %u / %u identifier table lookups succeeded (%f%%)\n",
6873 NumIdentifierLookupHits, NumIdentifierLookups,
6874 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6875 }
6876
Douglas Gregore060e572013-01-25 01:03:03 +00006877 if (GlobalIndex) {
6878 std::fprintf(stderr, "\n");
6879 GlobalIndex->printStats();
6880 }
6881
Guy Benyei11169dd2012-12-18 14:30:41 +00006882 std::fprintf(stderr, "\n");
6883 dump();
6884 std::fprintf(stderr, "\n");
6885}
6886
6887template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6888static void
6889dumpModuleIDMap(StringRef Name,
6890 const ContinuousRangeMap<Key, ModuleFile *,
6891 InitialCapacity> &Map) {
6892 if (Map.begin() == Map.end())
6893 return;
6894
6895 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6896 llvm::errs() << Name << ":\n";
6897 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6898 I != IEnd; ++I) {
6899 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6900 << "\n";
6901 }
6902}
6903
Yaron Kerencdae9412016-01-29 19:38:18 +00006904LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6906 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6907 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6908 dumpModuleIDMap("Global type map", GlobalTypeMap);
6909 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6910 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6911 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6912 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6913 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6914 dumpModuleIDMap("Global preprocessed entity map",
6915 GlobalPreprocessedEntityMap);
6916
6917 llvm::errs() << "\n*** PCH/Modules Loaded:";
6918 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6919 MEnd = ModuleMgr.end();
6920 M != MEnd; ++M)
6921 (*M)->dump();
6922}
6923
6924/// Return the amount of memory used by memory buffers, breaking down
6925/// by heap-backed versus mmap'ed memory.
6926void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6927 for (ModuleConstIterator I = ModuleMgr.begin(),
6928 E = ModuleMgr.end(); I != E; ++I) {
6929 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6930 size_t bytes = buf->getBufferSize();
6931 switch (buf->getBufferKind()) {
6932 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6933 sizes.malloc_bytes += bytes;
6934 break;
6935 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6936 sizes.mmap_bytes += bytes;
6937 break;
6938 }
6939 }
6940 }
6941}
6942
6943void ASTReader::InitializeSema(Sema &S) {
6944 SemaObj = &S;
6945 S.addExternalSource(this);
6946
6947 // Makes sure any declarations that were deserialized "too early"
6948 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006949 for (uint64_t ID : PreloadedDeclIDs) {
6950 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6951 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006953 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006954
Richard Smith3d8e97e2013-10-18 06:54:39 +00006955 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 if (!FPPragmaOptions.empty()) {
6957 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6958 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6959 }
6960
Richard Smith3d8e97e2013-10-18 06:54:39 +00006961 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 if (!OpenCLExtensions.empty()) {
6963 unsigned I = 0;
6964#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6965#include "clang/Basic/OpenCLExtensions.def"
6966
6967 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6968 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006969
6970 UpdateSema();
6971}
6972
6973void ASTReader::UpdateSema() {
6974 assert(SemaObj && "no Sema to update");
6975
6976 // Load the offsets of the declarations that Sema references.
6977 // They will be lazily deserialized when needed.
6978 if (!SemaDeclRefs.empty()) {
6979 assert(SemaDeclRefs.size() % 2 == 0);
6980 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6981 if (!SemaObj->StdNamespace)
6982 SemaObj->StdNamespace = SemaDeclRefs[I];
6983 if (!SemaObj->StdBadAlloc)
6984 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6985 }
6986 SemaDeclRefs.clear();
6987 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006988
6989 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6990 // encountered the pragma in the source.
6991 if(OptimizeOffPragmaLocation.isValid())
6992 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006993}
6994
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006995IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 // Note that we are loading an identifier.
6997 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006998
Douglas Gregor7211ac12013-01-25 23:32:03 +00006999 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007000 NumIdentifierLookups,
7001 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007002
7003 // We don't need to do identifier table lookups in C++ modules (we preload
7004 // all interesting declarations, and don't need to use the scope for name
7005 // lookups). Perform the lookup in PCH files, though, since we don't build
7006 // a complete initial identifier table if we're carrying on from a PCH.
7007 if (Context.getLangOpts().CPlusPlus) {
7008 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007009 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007010 break;
7011 } else {
7012 // If there is a global index, look there first to determine which modules
7013 // provably do not have any results for this identifier.
7014 GlobalModuleIndex::HitSet Hits;
7015 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7016 if (!loadGlobalIndex()) {
7017 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7018 HitsPtr = &Hits;
7019 }
7020 }
7021
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007022 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007023 }
7024
Guy Benyei11169dd2012-12-18 14:30:41 +00007025 IdentifierInfo *II = Visitor.getIdentifierInfo();
7026 markIdentifierUpToDate(II);
7027 return II;
7028}
7029
7030namespace clang {
7031 /// \brief An identifier-lookup iterator that enumerates all of the
7032 /// identifiers stored within a set of AST files.
7033 class ASTIdentifierIterator : public IdentifierIterator {
7034 /// \brief The AST reader whose identifiers are being enumerated.
7035 const ASTReader &Reader;
7036
7037 /// \brief The current index into the chain of AST files stored in
7038 /// the AST reader.
7039 unsigned Index;
7040
7041 /// \brief The current position within the identifier lookup table
7042 /// of the current AST file.
7043 ASTIdentifierLookupTable::key_iterator Current;
7044
7045 /// \brief The end position within the identifier lookup table of
7046 /// the current AST file.
7047 ASTIdentifierLookupTable::key_iterator End;
7048
7049 public:
7050 explicit ASTIdentifierIterator(const ASTReader &Reader);
7051
Craig Topper3e89dfe2014-03-13 02:13:41 +00007052 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007054}
Guy Benyei11169dd2012-12-18 14:30:41 +00007055
7056ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7057 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7058 ASTIdentifierLookupTable *IdTable
7059 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7060 Current = IdTable->key_begin();
7061 End = IdTable->key_end();
7062}
7063
7064StringRef ASTIdentifierIterator::Next() {
7065 while (Current == End) {
7066 // If we have exhausted all of our AST files, we're done.
7067 if (Index == 0)
7068 return StringRef();
7069
7070 --Index;
7071 ASTIdentifierLookupTable *IdTable
7072 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7073 IdentifierLookupTable;
7074 Current = IdTable->key_begin();
7075 End = IdTable->key_end();
7076 }
7077
7078 // We have any identifiers remaining in the current AST file; return
7079 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007080 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007082 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007083}
7084
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007085IdentifierIterator *ASTReader::getIdentifiers() {
7086 if (!loadGlobalIndex())
7087 return GlobalIndex->createIdentifierIterator();
7088
Guy Benyei11169dd2012-12-18 14:30:41 +00007089 return new ASTIdentifierIterator(*this);
7090}
7091
7092namespace clang { namespace serialization {
7093 class ReadMethodPoolVisitor {
7094 ASTReader &Reader;
7095 Selector Sel;
7096 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007097 unsigned InstanceBits;
7098 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007099 bool InstanceHasMoreThanOneDecl;
7100 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007101 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7102 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007103
7104 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007105 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007106 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007107 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007108 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7109 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007110
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007111 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 if (!M.SelectorLookupTable)
7113 return false;
7114
7115 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007116 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 return true;
7118
Richard Smithbdf2d932015-07-30 03:37:16 +00007119 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 ASTSelectorLookupTable *PoolTable
7121 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007122 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 if (Pos == PoolTable->end())
7124 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007125
Richard Smithbdf2d932015-07-30 03:37:16 +00007126 ++Reader.NumMethodPoolTableHits;
7127 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 // FIXME: Not quite happy with the statistics here. We probably should
7129 // disable this tracking when called via LoadSelector.
7130 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007131 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007132 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007133 if (Reader.DeserializationListener)
7134 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007135
Richard Smithbdf2d932015-07-30 03:37:16 +00007136 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7137 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7138 InstanceBits = Data.InstanceBits;
7139 FactoryBits = Data.FactoryBits;
7140 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7141 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007142 return true;
7143 }
7144
7145 /// \brief Retrieve the instance methods found by this visitor.
7146 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7147 return InstanceMethods;
7148 }
7149
7150 /// \brief Retrieve the instance methods found by this visitor.
7151 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7152 return FactoryMethods;
7153 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007154
7155 unsigned getInstanceBits() const { return InstanceBits; }
7156 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007157 bool instanceHasMoreThanOneDecl() const {
7158 return InstanceHasMoreThanOneDecl;
7159 }
7160 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007162} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007163
7164/// \brief Add the given set of methods to the method list.
7165static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7166 ObjCMethodList &List) {
7167 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7168 S.addMethodToGlobalList(&List, Methods[I]);
7169 }
7170}
7171
7172void ASTReader::ReadMethodPool(Selector Sel) {
7173 // Get the selector generation and update it to the current generation.
7174 unsigned &Generation = SelectorGeneration[Sel];
7175 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007176 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007177
7178 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007179 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007181 ModuleMgr.visit(Visitor);
7182
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007184 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007186
7187 ++NumMethodPoolHits;
7188
Guy Benyei11169dd2012-12-18 14:30:41 +00007189 if (!getSema())
7190 return;
7191
7192 Sema &S = *getSema();
7193 Sema::GlobalMethodPool::iterator Pos
7194 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007195
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007196 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007197 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007198 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007199 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007200
7201 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7202 // when building a module we keep every method individually and may need to
7203 // update hasMoreThanOneDecl as we add the methods.
7204 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7205 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007206}
7207
7208void ASTReader::ReadKnownNamespaces(
7209 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7210 Namespaces.clear();
7211
7212 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7213 if (NamespaceDecl *Namespace
7214 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7215 Namespaces.push_back(Namespace);
7216 }
7217}
7218
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007219void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007220 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007221 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7222 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007223 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007224 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007225 Undefined.insert(std::make_pair(D, Loc));
7226 }
7227}
Nick Lewycky8334af82013-01-26 00:35:08 +00007228
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007229void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7230 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7231 Exprs) {
7232 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7233 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7234 uint64_t Count = DelayedDeleteExprs[Idx++];
7235 for (uint64_t C = 0; C < Count; ++C) {
7236 SourceLocation DeleteLoc =
7237 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7238 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7239 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7240 }
7241 }
7242}
7243
Guy Benyei11169dd2012-12-18 14:30:41 +00007244void ASTReader::ReadTentativeDefinitions(
7245 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7246 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7247 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7248 if (Var)
7249 TentativeDefs.push_back(Var);
7250 }
7251 TentativeDefinitions.clear();
7252}
7253
7254void ASTReader::ReadUnusedFileScopedDecls(
7255 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7256 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7257 DeclaratorDecl *D
7258 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7259 if (D)
7260 Decls.push_back(D);
7261 }
7262 UnusedFileScopedDecls.clear();
7263}
7264
7265void ASTReader::ReadDelegatingConstructors(
7266 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7267 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7268 CXXConstructorDecl *D
7269 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7270 if (D)
7271 Decls.push_back(D);
7272 }
7273 DelegatingCtorDecls.clear();
7274}
7275
7276void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7277 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7278 TypedefNameDecl *D
7279 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7280 if (D)
7281 Decls.push_back(D);
7282 }
7283 ExtVectorDecls.clear();
7284}
7285
Nico Weber72889432014-09-06 01:25:55 +00007286void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7287 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7288 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7289 ++I) {
7290 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7291 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7292 if (D)
7293 Decls.insert(D);
7294 }
7295 UnusedLocalTypedefNameCandidates.clear();
7296}
7297
Guy Benyei11169dd2012-12-18 14:30:41 +00007298void ASTReader::ReadReferencedSelectors(
7299 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7300 if (ReferencedSelectorsData.empty())
7301 return;
7302
7303 // If there are @selector references added them to its pool. This is for
7304 // implementation of -Wselector.
7305 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7306 unsigned I = 0;
7307 while (I < DataSize) {
7308 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7309 SourceLocation SelLoc
7310 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7311 Sels.push_back(std::make_pair(Sel, SelLoc));
7312 }
7313 ReferencedSelectorsData.clear();
7314}
7315
7316void ASTReader::ReadWeakUndeclaredIdentifiers(
7317 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7318 if (WeakUndeclaredIdentifiers.empty())
7319 return;
7320
7321 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7322 IdentifierInfo *WeakId
7323 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7324 IdentifierInfo *AliasId
7325 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7326 SourceLocation Loc
7327 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7328 bool Used = WeakUndeclaredIdentifiers[I++];
7329 WeakInfo WI(AliasId, Loc);
7330 WI.setUsed(Used);
7331 WeakIDs.push_back(std::make_pair(WeakId, WI));
7332 }
7333 WeakUndeclaredIdentifiers.clear();
7334}
7335
7336void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7337 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7338 ExternalVTableUse VT;
7339 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7340 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7341 VT.DefinitionRequired = VTableUses[Idx++];
7342 VTables.push_back(VT);
7343 }
7344
7345 VTableUses.clear();
7346}
7347
7348void ASTReader::ReadPendingInstantiations(
7349 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7350 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7351 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7352 SourceLocation Loc
7353 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7354
7355 Pending.push_back(std::make_pair(D, Loc));
7356 }
7357 PendingInstantiations.clear();
7358}
7359
Richard Smithe40f2ba2013-08-07 21:41:30 +00007360void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007361 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007362 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7363 /* In loop */) {
7364 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7365
7366 LateParsedTemplate *LT = new LateParsedTemplate;
7367 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7368
7369 ModuleFile *F = getOwningModuleFile(LT->D);
7370 assert(F && "No module");
7371
7372 unsigned TokN = LateParsedTemplates[Idx++];
7373 LT->Toks.reserve(TokN);
7374 for (unsigned T = 0; T < TokN; ++T)
7375 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7376
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007377 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007378 }
7379
7380 LateParsedTemplates.clear();
7381}
7382
Guy Benyei11169dd2012-12-18 14:30:41 +00007383void ASTReader::LoadSelector(Selector Sel) {
7384 // It would be complicated to avoid reading the methods anyway. So don't.
7385 ReadMethodPool(Sel);
7386}
7387
7388void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7389 assert(ID && "Non-zero identifier ID required");
7390 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7391 IdentifiersLoaded[ID - 1] = II;
7392 if (DeserializationListener)
7393 DeserializationListener->IdentifierRead(ID, II);
7394}
7395
7396/// \brief Set the globally-visible declarations associated with the given
7397/// identifier.
7398///
7399/// If the AST reader is currently in a state where the given declaration IDs
7400/// cannot safely be resolved, they are queued until it is safe to resolve
7401/// them.
7402///
7403/// \param II an IdentifierInfo that refers to one or more globally-visible
7404/// declarations.
7405///
7406/// \param DeclIDs the set of declaration IDs with the name @p II that are
7407/// visible at global scope.
7408///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007409/// \param Decls if non-null, this vector will be populated with the set of
7410/// deserialized declarations. These declarations will not be pushed into
7411/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007412void
7413ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7414 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007415 SmallVectorImpl<Decl *> *Decls) {
7416 if (NumCurrentElementsDeserializing && !Decls) {
7417 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007418 return;
7419 }
7420
7421 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007422 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 // Queue this declaration so that it will be added to the
7424 // translation unit scope and identifier's declaration chain
7425 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007426 PreloadedDeclIDs.push_back(DeclIDs[I]);
7427 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007429
7430 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7431
7432 // If we're simply supposed to record the declarations, do so now.
7433 if (Decls) {
7434 Decls->push_back(D);
7435 continue;
7436 }
7437
7438 // Introduce this declaration into the translation-unit scope
7439 // and add it to the declaration chain for this identifier, so
7440 // that (unqualified) name lookup will find it.
7441 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 }
7443}
7444
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007445IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007447 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007448
7449 if (IdentifiersLoaded.empty()) {
7450 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007451 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 }
7453
7454 ID -= 1;
7455 if (!IdentifiersLoaded[ID]) {
7456 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7457 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7458 ModuleFile *M = I->second;
7459 unsigned Index = ID - M->BaseIdentifierID;
7460 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7461
7462 // All of the strings in the AST file are preceded by a 16-bit length.
7463 // Extract that 16-bit length to avoid having to execute strlen().
7464 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7465 // unsigned integers. This is important to avoid integer overflow when
7466 // we cast them to 'unsigned'.
7467 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7468 unsigned StrLen = (((unsigned) StrLenPtr[0])
7469 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007470 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7471 IdentifiersLoaded[ID] = &II;
7472 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007474 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 }
7476
7477 return IdentifiersLoaded[ID];
7478}
7479
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007480IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7481 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007482}
7483
7484IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7485 if (LocalID < NUM_PREDEF_IDENT_IDS)
7486 return LocalID;
7487
7488 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7489 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7490 assert(I != M.IdentifierRemap.end()
7491 && "Invalid index into identifier index remap");
7492
7493 return LocalID + I->second;
7494}
7495
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007496MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007497 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007498 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007499
7500 if (MacrosLoaded.empty()) {
7501 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007502 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 }
7504
7505 ID -= NUM_PREDEF_MACRO_IDS;
7506 if (!MacrosLoaded[ID]) {
7507 GlobalMacroMapType::iterator I
7508 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7509 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7510 ModuleFile *M = I->second;
7511 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007512 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7513
7514 if (DeserializationListener)
7515 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7516 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 }
7518
7519 return MacrosLoaded[ID];
7520}
7521
7522MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7523 if (LocalID < NUM_PREDEF_MACRO_IDS)
7524 return LocalID;
7525
7526 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7527 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7528 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7529
7530 return LocalID + I->second;
7531}
7532
7533serialization::SubmoduleID
7534ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7535 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7536 return LocalID;
7537
7538 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7539 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7540 assert(I != M.SubmoduleRemap.end()
7541 && "Invalid index into submodule index remap");
7542
7543 return LocalID + I->second;
7544}
7545
7546Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7547 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7548 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007549 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007550 }
7551
7552 if (GlobalID > SubmodulesLoaded.size()) {
7553 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007554 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 }
7556
7557 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7558}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007559
7560Module *ASTReader::getModule(unsigned ID) {
7561 return getSubmodule(ID);
7562}
7563
Richard Smithd88a7f12015-09-01 20:35:42 +00007564ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7565 if (ID & 1) {
7566 // It's a module, look it up by submodule ID.
7567 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7568 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7569 } else {
7570 // It's a prefix (preamble, PCH, ...). Look it up by index.
7571 unsigned IndexFromEnd = ID >> 1;
7572 assert(IndexFromEnd && "got reference to unknown module file");
7573 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7574 }
7575}
7576
7577unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7578 if (!F)
7579 return 1;
7580
7581 // For a file representing a module, use the submodule ID of the top-level
7582 // module as the file ID. For any other kind of file, the number of such
7583 // files loaded beforehand will be the same on reload.
7584 // FIXME: Is this true even if we have an explicit module file and a PCH?
7585 if (F->isModule())
7586 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7587
7588 auto PCHModules = getModuleManager().pch_modules();
7589 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7590 assert(I != PCHModules.end() && "emitting reference to unknown file");
7591 return (I - PCHModules.end()) << 1;
7592}
7593
Adrian Prantl15bcf702015-06-30 17:39:43 +00007594llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7595ASTReader::getSourceDescriptor(unsigned ID) {
7596 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007597 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007598
7599 // If there is only a single PCH, return it instead.
7600 // Chained PCH are not suported.
7601 if (ModuleMgr.size() == 1) {
7602 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007603 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7604 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir,
7605 MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007606 }
7607 return None;
7608}
7609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7611 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7612}
7613
7614Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7615 if (ID == 0)
7616 return Selector();
7617
7618 if (ID > SelectorsLoaded.size()) {
7619 Error("selector ID out of range in AST file");
7620 return Selector();
7621 }
7622
Craig Toppera13603a2014-05-22 05:54:18 +00007623 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 // Load this selector from the selector table.
7625 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7626 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7627 ModuleFile &M = *I->second;
7628 ASTSelectorLookupTrait Trait(*this, M);
7629 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7630 SelectorsLoaded[ID - 1] =
7631 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7632 if (DeserializationListener)
7633 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7634 }
7635
7636 return SelectorsLoaded[ID - 1];
7637}
7638
7639Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7640 return DecodeSelector(ID);
7641}
7642
7643uint32_t ASTReader::GetNumExternalSelectors() {
7644 // ID 0 (the null selector) is considered an external selector.
7645 return getTotalNumSelectors() + 1;
7646}
7647
7648serialization::SelectorID
7649ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7650 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7651 return LocalID;
7652
7653 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7654 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7655 assert(I != M.SelectorRemap.end()
7656 && "Invalid index into selector index remap");
7657
7658 return LocalID + I->second;
7659}
7660
7661DeclarationName
7662ASTReader::ReadDeclarationName(ModuleFile &F,
7663 const RecordData &Record, unsigned &Idx) {
7664 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7665 switch (Kind) {
7666 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007667 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007668
7669 case DeclarationName::ObjCZeroArgSelector:
7670 case DeclarationName::ObjCOneArgSelector:
7671 case DeclarationName::ObjCMultiArgSelector:
7672 return DeclarationName(ReadSelector(F, Record, Idx));
7673
7674 case DeclarationName::CXXConstructorName:
7675 return Context.DeclarationNames.getCXXConstructorName(
7676 Context.getCanonicalType(readType(F, Record, Idx)));
7677
7678 case DeclarationName::CXXDestructorName:
7679 return Context.DeclarationNames.getCXXDestructorName(
7680 Context.getCanonicalType(readType(F, Record, Idx)));
7681
7682 case DeclarationName::CXXConversionFunctionName:
7683 return Context.DeclarationNames.getCXXConversionFunctionName(
7684 Context.getCanonicalType(readType(F, Record, Idx)));
7685
7686 case DeclarationName::CXXOperatorName:
7687 return Context.DeclarationNames.getCXXOperatorName(
7688 (OverloadedOperatorKind)Record[Idx++]);
7689
7690 case DeclarationName::CXXLiteralOperatorName:
7691 return Context.DeclarationNames.getCXXLiteralOperatorName(
7692 GetIdentifierInfo(F, Record, Idx));
7693
7694 case DeclarationName::CXXUsingDirective:
7695 return DeclarationName::getUsingDirectiveName();
7696 }
7697
7698 llvm_unreachable("Invalid NameKind!");
7699}
7700
7701void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7702 DeclarationNameLoc &DNLoc,
7703 DeclarationName Name,
7704 const RecordData &Record, unsigned &Idx) {
7705 switch (Name.getNameKind()) {
7706 case DeclarationName::CXXConstructorName:
7707 case DeclarationName::CXXDestructorName:
7708 case DeclarationName::CXXConversionFunctionName:
7709 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7710 break;
7711
7712 case DeclarationName::CXXOperatorName:
7713 DNLoc.CXXOperatorName.BeginOpNameLoc
7714 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7715 DNLoc.CXXOperatorName.EndOpNameLoc
7716 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7717 break;
7718
7719 case DeclarationName::CXXLiteralOperatorName:
7720 DNLoc.CXXLiteralOperatorName.OpNameLoc
7721 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7722 break;
7723
7724 case DeclarationName::Identifier:
7725 case DeclarationName::ObjCZeroArgSelector:
7726 case DeclarationName::ObjCOneArgSelector:
7727 case DeclarationName::ObjCMultiArgSelector:
7728 case DeclarationName::CXXUsingDirective:
7729 break;
7730 }
7731}
7732
7733void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7734 DeclarationNameInfo &NameInfo,
7735 const RecordData &Record, unsigned &Idx) {
7736 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7737 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7738 DeclarationNameLoc DNLoc;
7739 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7740 NameInfo.setInfo(DNLoc);
7741}
7742
7743void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7744 const RecordData &Record, unsigned &Idx) {
7745 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7746 unsigned NumTPLists = Record[Idx++];
7747 Info.NumTemplParamLists = NumTPLists;
7748 if (NumTPLists) {
7749 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7750 for (unsigned i=0; i != NumTPLists; ++i)
7751 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7752 }
7753}
7754
7755TemplateName
7756ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7757 unsigned &Idx) {
7758 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7759 switch (Kind) {
7760 case TemplateName::Template:
7761 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7762
7763 case TemplateName::OverloadedTemplate: {
7764 unsigned size = Record[Idx++];
7765 UnresolvedSet<8> Decls;
7766 while (size--)
7767 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7768
7769 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7770 }
7771
7772 case TemplateName::QualifiedTemplate: {
7773 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7774 bool hasTemplKeyword = Record[Idx++];
7775 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7776 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7777 }
7778
7779 case TemplateName::DependentTemplate: {
7780 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7781 if (Record[Idx++]) // isIdentifier
7782 return Context.getDependentTemplateName(NNS,
7783 GetIdentifierInfo(F, Record,
7784 Idx));
7785 return Context.getDependentTemplateName(NNS,
7786 (OverloadedOperatorKind)Record[Idx++]);
7787 }
7788
7789 case TemplateName::SubstTemplateTemplateParm: {
7790 TemplateTemplateParmDecl *param
7791 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7792 if (!param) return TemplateName();
7793 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7794 return Context.getSubstTemplateTemplateParm(param, replacement);
7795 }
7796
7797 case TemplateName::SubstTemplateTemplateParmPack: {
7798 TemplateTemplateParmDecl *Param
7799 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7800 if (!Param)
7801 return TemplateName();
7802
7803 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7804 if (ArgPack.getKind() != TemplateArgument::Pack)
7805 return TemplateName();
7806
7807 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7808 }
7809 }
7810
7811 llvm_unreachable("Unhandled template name kind!");
7812}
7813
Richard Smith2bb3c342015-08-09 01:05:31 +00007814TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7815 const RecordData &Record,
7816 unsigned &Idx,
7817 bool Canonicalize) {
7818 if (Canonicalize) {
7819 // The caller wants a canonical template argument. Sometimes the AST only
7820 // wants template arguments in canonical form (particularly as the template
7821 // argument lists of template specializations) so ensure we preserve that
7822 // canonical form across serialization.
7823 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7824 return Context.getCanonicalTemplateArgument(Arg);
7825 }
7826
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7828 switch (Kind) {
7829 case TemplateArgument::Null:
7830 return TemplateArgument();
7831 case TemplateArgument::Type:
7832 return TemplateArgument(readType(F, Record, Idx));
7833 case TemplateArgument::Declaration: {
7834 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007835 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007836 }
7837 case TemplateArgument::NullPtr:
7838 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7839 case TemplateArgument::Integral: {
7840 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7841 QualType T = readType(F, Record, Idx);
7842 return TemplateArgument(Context, Value, T);
7843 }
7844 case TemplateArgument::Template:
7845 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7846 case TemplateArgument::TemplateExpansion: {
7847 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007848 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 if (unsigned NumExpansions = Record[Idx++])
7850 NumTemplateExpansions = NumExpansions - 1;
7851 return TemplateArgument(Name, NumTemplateExpansions);
7852 }
7853 case TemplateArgument::Expression:
7854 return TemplateArgument(ReadExpr(F));
7855 case TemplateArgument::Pack: {
7856 unsigned NumArgs = Record[Idx++];
7857 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7858 for (unsigned I = 0; I != NumArgs; ++I)
7859 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007860 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007861 }
7862 }
7863
7864 llvm_unreachable("Unhandled template argument kind!");
7865}
7866
7867TemplateParameterList *
7868ASTReader::ReadTemplateParameterList(ModuleFile &F,
7869 const RecordData &Record, unsigned &Idx) {
7870 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7871 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7872 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7873
7874 unsigned NumParams = Record[Idx++];
7875 SmallVector<NamedDecl *, 16> Params;
7876 Params.reserve(NumParams);
7877 while (NumParams--)
7878 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7879
7880 TemplateParameterList* TemplateParams =
7881 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
David Majnemer902f8c62015-12-27 07:16:27 +00007882 Params, RAngleLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 return TemplateParams;
7884}
7885
7886void
7887ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007888ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007889 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007890 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 unsigned NumTemplateArgs = Record[Idx++];
7892 TemplArgs.reserve(NumTemplateArgs);
7893 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007894 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007895}
7896
7897/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007898void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 const RecordData &Record, unsigned &Idx) {
7900 unsigned NumDecls = Record[Idx++];
7901 Set.reserve(Context, NumDecls);
7902 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007903 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007905 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007906 }
7907}
7908
7909CXXBaseSpecifier
7910ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7911 const RecordData &Record, unsigned &Idx) {
7912 bool isVirtual = static_cast<bool>(Record[Idx++]);
7913 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7914 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7915 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7916 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7917 SourceRange Range = ReadSourceRange(F, Record, Idx);
7918 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7919 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7920 EllipsisLoc);
7921 Result.setInheritConstructors(inheritConstructors);
7922 return Result;
7923}
7924
Richard Smithc2bb8182015-03-24 06:36:48 +00007925CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007926ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7927 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007928 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007929 assert(NumInitializers && "wrote ctor initializers but have no inits");
7930 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7931 for (unsigned i = 0; i != NumInitializers; ++i) {
7932 TypeSourceInfo *TInfo = nullptr;
7933 bool IsBaseVirtual = false;
7934 FieldDecl *Member = nullptr;
7935 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007936
Richard Smithc2bb8182015-03-24 06:36:48 +00007937 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7938 switch (Type) {
7939 case CTOR_INITIALIZER_BASE:
7940 TInfo = GetTypeSourceInfo(F, Record, Idx);
7941 IsBaseVirtual = Record[Idx++];
7942 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007943
Richard Smithc2bb8182015-03-24 06:36:48 +00007944 case CTOR_INITIALIZER_DELEGATING:
7945 TInfo = GetTypeSourceInfo(F, Record, Idx);
7946 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007947
Richard Smithc2bb8182015-03-24 06:36:48 +00007948 case CTOR_INITIALIZER_MEMBER:
7949 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7950 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007951
Richard Smithc2bb8182015-03-24 06:36:48 +00007952 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7953 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7954 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007956
7957 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7958 Expr *Init = ReadExpr(F);
7959 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7960 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7961 bool IsWritten = Record[Idx++];
7962 unsigned SourceOrderOrNumArrayIndices;
7963 SmallVector<VarDecl *, 8> Indices;
7964 if (IsWritten) {
7965 SourceOrderOrNumArrayIndices = Record[Idx++];
7966 } else {
7967 SourceOrderOrNumArrayIndices = Record[Idx++];
7968 Indices.reserve(SourceOrderOrNumArrayIndices);
7969 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7970 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7971 }
7972
7973 CXXCtorInitializer *BOMInit;
7974 if (Type == CTOR_INITIALIZER_BASE) {
7975 BOMInit = new (Context)
7976 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7977 RParenLoc, MemberOrEllipsisLoc);
7978 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7979 BOMInit = new (Context)
7980 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7981 } else if (IsWritten) {
7982 if (Member)
7983 BOMInit = new (Context) CXXCtorInitializer(
7984 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7985 else
7986 BOMInit = new (Context)
7987 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7988 LParenLoc, Init, RParenLoc);
7989 } else {
7990 if (IndirectMember) {
7991 assert(Indices.empty() && "Indirect field improperly initialized");
7992 BOMInit = new (Context)
7993 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7994 LParenLoc, Init, RParenLoc);
7995 } else {
7996 BOMInit = CXXCtorInitializer::Create(
7997 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7998 Indices.data(), Indices.size());
7999 }
8000 }
8001
8002 if (IsWritten)
8003 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8004 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 }
8006
Richard Smithc2bb8182015-03-24 06:36:48 +00008007 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008008}
8009
8010NestedNameSpecifier *
8011ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8012 const RecordData &Record, unsigned &Idx) {
8013 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008014 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 for (unsigned I = 0; I != N; ++I) {
8016 NestedNameSpecifier::SpecifierKind Kind
8017 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8018 switch (Kind) {
8019 case NestedNameSpecifier::Identifier: {
8020 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8021 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8022 break;
8023 }
8024
8025 case NestedNameSpecifier::Namespace: {
8026 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8027 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8028 break;
8029 }
8030
8031 case NestedNameSpecifier::NamespaceAlias: {
8032 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8033 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8034 break;
8035 }
8036
8037 case NestedNameSpecifier::TypeSpec:
8038 case NestedNameSpecifier::TypeSpecWithTemplate: {
8039 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8040 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008041 return nullptr;
8042
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 bool Template = Record[Idx++];
8044 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8045 break;
8046 }
8047
8048 case NestedNameSpecifier::Global: {
8049 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8050 // No associated value, and there can't be a prefix.
8051 break;
8052 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008053
8054 case NestedNameSpecifier::Super: {
8055 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8056 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8057 break;
8058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 }
8060 Prev = NNS;
8061 }
8062 return NNS;
8063}
8064
8065NestedNameSpecifierLoc
8066ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8067 unsigned &Idx) {
8068 unsigned N = Record[Idx++];
8069 NestedNameSpecifierLocBuilder Builder;
8070 for (unsigned I = 0; I != N; ++I) {
8071 NestedNameSpecifier::SpecifierKind Kind
8072 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8073 switch (Kind) {
8074 case NestedNameSpecifier::Identifier: {
8075 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8076 SourceRange Range = ReadSourceRange(F, Record, Idx);
8077 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8078 break;
8079 }
8080
8081 case NestedNameSpecifier::Namespace: {
8082 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8083 SourceRange Range = ReadSourceRange(F, Record, Idx);
8084 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8085 break;
8086 }
8087
8088 case NestedNameSpecifier::NamespaceAlias: {
8089 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8090 SourceRange Range = ReadSourceRange(F, Record, Idx);
8091 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8092 break;
8093 }
8094
8095 case NestedNameSpecifier::TypeSpec:
8096 case NestedNameSpecifier::TypeSpecWithTemplate: {
8097 bool Template = Record[Idx++];
8098 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8099 if (!T)
8100 return NestedNameSpecifierLoc();
8101 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8102
8103 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8104 Builder.Extend(Context,
8105 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8106 T->getTypeLoc(), ColonColonLoc);
8107 break;
8108 }
8109
8110 case NestedNameSpecifier::Global: {
8111 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8112 Builder.MakeGlobal(Context, ColonColonLoc);
8113 break;
8114 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008115
8116 case NestedNameSpecifier::Super: {
8117 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8118 SourceRange Range = ReadSourceRange(F, Record, Idx);
8119 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8120 break;
8121 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 }
8123 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008124
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 return Builder.getWithLocInContext(Context);
8126}
8127
8128SourceRange
8129ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8130 unsigned &Idx) {
8131 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8132 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8133 return SourceRange(beg, end);
8134}
8135
8136/// \brief Read an integral value
8137llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8138 unsigned BitWidth = Record[Idx++];
8139 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8140 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8141 Idx += NumWords;
8142 return Result;
8143}
8144
8145/// \brief Read a signed integral value
8146llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8147 bool isUnsigned = Record[Idx++];
8148 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8149}
8150
8151/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008152llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8153 const llvm::fltSemantics &Sem,
8154 unsigned &Idx) {
8155 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008156}
8157
8158// \brief Read a string
8159std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8160 unsigned Len = Record[Idx++];
8161 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8162 Idx += Len;
8163 return Result;
8164}
8165
Richard Smith7ed1bc92014-12-05 22:42:13 +00008166std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8167 unsigned &Idx) {
8168 std::string Filename = ReadString(Record, Idx);
8169 ResolveImportedPath(F, Filename);
8170 return Filename;
8171}
8172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8174 unsigned &Idx) {
8175 unsigned Major = Record[Idx++];
8176 unsigned Minor = Record[Idx++];
8177 unsigned Subminor = Record[Idx++];
8178 if (Minor == 0)
8179 return VersionTuple(Major);
8180 if (Subminor == 0)
8181 return VersionTuple(Major, Minor - 1);
8182 return VersionTuple(Major, Minor - 1, Subminor - 1);
8183}
8184
8185CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8186 const RecordData &Record,
8187 unsigned &Idx) {
8188 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8189 return CXXTemporary::Create(Context, Decl);
8190}
8191
8192DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008193 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008194}
8195
8196DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8197 return Diags.Report(Loc, DiagID);
8198}
8199
8200/// \brief Retrieve the identifier table associated with the
8201/// preprocessor.
8202IdentifierTable &ASTReader::getIdentifierTable() {
8203 return PP.getIdentifierTable();
8204}
8205
8206/// \brief Record that the given ID maps to the given switch-case
8207/// statement.
8208void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008209 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 "Already have a SwitchCase with this ID");
8211 (*CurrSwitchCaseStmts)[ID] = SC;
8212}
8213
8214/// \brief Retrieve the switch-case statement with the given ID.
8215SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008216 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 return (*CurrSwitchCaseStmts)[ID];
8218}
8219
8220void ASTReader::ClearSwitchCaseIDs() {
8221 CurrSwitchCaseStmts->clear();
8222}
8223
8224void ASTReader::ReadComments() {
8225 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008226 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 serialization::ModuleFile *> >::iterator
8228 I = CommentsCursors.begin(),
8229 E = CommentsCursors.end();
8230 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008231 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008232 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 serialization::ModuleFile &F = *I->second;
8234 SavedStreamPosition SavedPosition(Cursor);
8235
8236 RecordData Record;
8237 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008238 llvm::BitstreamEntry Entry =
8239 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008240
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008241 switch (Entry.Kind) {
8242 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8243 case llvm::BitstreamEntry::Error:
8244 Error("malformed block record in AST file");
8245 return;
8246 case llvm::BitstreamEntry::EndBlock:
8247 goto NextCursor;
8248 case llvm::BitstreamEntry::Record:
8249 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 }
8252
8253 // Read a record.
8254 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008255 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 case COMMENTS_RAW_COMMENT: {
8257 unsigned Idx = 0;
8258 SourceRange SR = ReadSourceRange(F, Record, Idx);
8259 RawComment::CommentKind Kind =
8260 (RawComment::CommentKind) Record[Idx++];
8261 bool IsTrailingComment = Record[Idx++];
8262 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008263 Comments.push_back(new (Context) RawComment(
8264 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8265 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008266 break;
8267 }
8268 }
8269 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008270 NextCursor:
8271 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008273}
8274
Richard Smithcd45dbc2014-04-19 03:48:30 +00008275std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8276 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008277 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008278 return M->getFullModuleName();
8279
8280 // Otherwise, use the name of the top-level module the decl is within.
8281 if (ModuleFile *M = getOwningModuleFile(D))
8282 return M->ModuleName;
8283
8284 // Not from a module.
8285 return "";
8286}
8287
Guy Benyei11169dd2012-12-18 14:30:41 +00008288void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008289 while (!PendingIdentifierInfos.empty() ||
8290 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008291 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008292 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 // If any identifiers with corresponding top-level declarations have
8294 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008295 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8296 TopLevelDeclsMap;
8297 TopLevelDeclsMap TopLevelDecls;
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008300 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008301 SmallVector<uint32_t, 4> DeclIDs =
8302 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008303 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008304
8305 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008306 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008307
Richard Smith851072e2014-05-19 20:59:20 +00008308 // For each decl chain that we wanted to complete while deserializing, mark
8309 // it as "still needs to be completed".
8310 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8311 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8312 }
8313 PendingIncompleteDeclChains.clear();
8314
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008316 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008317 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008318 PendingDeclChains.clear();
8319
Douglas Gregor6168bd22013-02-18 15:53:43 +00008320 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008321 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8322 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008323 IdentifierInfo *II = TLD->first;
8324 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008325 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008326 }
8327 }
8328
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 // Load any pending macro definitions.
8330 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008331 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8332 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8333 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8334 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008335 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008336 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008337 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008338 if (Info.M->Kind != MK_ImplicitModule &&
8339 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008340 resolvePendingMacro(II, Info);
8341 }
8342 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008343 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008344 ++IDIdx) {
8345 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008346 if (Info.M->Kind == MK_ImplicitModule ||
8347 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008348 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 }
8350 }
8351 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008352
8353 // Wire up the DeclContexts for Decls that we delayed setting until
8354 // recursive loading is completed.
8355 while (!PendingDeclContextInfos.empty()) {
8356 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8357 PendingDeclContextInfos.pop_front();
8358 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8359 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8360 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8361 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008362
Richard Smithd1c46742014-04-30 02:24:17 +00008363 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008364 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008365 auto Update = PendingUpdateRecords.pop_back_val();
8366 ReadingKindTracker ReadingKind(Read_Decl, *this);
8367 loadDeclUpdateRecords(Update.first, Update.second);
8368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 }
Richard Smith8a639892015-01-24 01:07:20 +00008370
8371 // At this point, all update records for loaded decls are in place, so any
8372 // fake class definitions should have become real.
8373 assert(PendingFakeDefinitionData.empty() &&
8374 "faked up a class definition but never saw the real one");
8375
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 // If we deserialized any C++ or Objective-C class definitions, any
8377 // Objective-C protocol definitions, or any redeclarable templates, make sure
8378 // that all redeclarations point to the definitions. Note that this can only
8379 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008380 for (Decl *D : PendingDefinitions) {
8381 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008382 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 // Make sure that the TagType points at the definition.
8384 const_cast<TagType*>(TagT)->decl = TD;
8385 }
Richard Smith8ce51082015-03-11 01:44:51 +00008386
Craig Topperc6914d02014-08-25 04:15:02 +00008387 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008388 for (auto *R = getMostRecentExistingDecl(RD); R;
8389 R = R->getPreviousDecl()) {
8390 assert((R == D) ==
8391 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008392 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008393 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008394 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008395 }
8396
8397 continue;
8398 }
Richard Smith8ce51082015-03-11 01:44:51 +00008399
Craig Topperc6914d02014-08-25 04:15:02 +00008400 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 // Make sure that the ObjCInterfaceType points at the definition.
8402 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8403 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008404
8405 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8406 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 continue;
8409 }
Richard Smith8ce51082015-03-11 01:44:51 +00008410
Craig Topperc6914d02014-08-25 04:15:02 +00008411 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008412 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8413 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8414
Guy Benyei11169dd2012-12-18 14:30:41 +00008415 continue;
8416 }
Richard Smith8ce51082015-03-11 01:44:51 +00008417
Craig Topperc6914d02014-08-25 04:15:02 +00008418 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008419 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8420 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008421 }
8422 PendingDefinitions.clear();
8423
8424 // Load the bodies of any functions or methods we've encountered. We do
8425 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008426 // have been fully wired up (hasBody relies on this).
8427 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008428 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8429 PBEnd = PendingBodies.end();
8430 PB != PBEnd; ++PB) {
8431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8432 // FIXME: Check for =delete/=default?
8433 // FIXME: Complain about ODR violations here?
8434 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8435 FD->setLazyBody(PB->second);
8436 continue;
8437 }
8438
8439 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8440 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8441 MD->setLazyBody(PB->second);
8442 }
8443 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008444
8445 // Do some cleanup.
8446 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8447 getContext().deduplicateMergedDefinitonsFor(ND);
8448 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008449}
8450
8451void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008452 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8453 return;
8454
Richard Smitha0ce9c42014-07-29 23:23:27 +00008455 // Trigger the import of the full definition of each class that had any
8456 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008457 // These updates may in turn find and diagnose some ODR failures, so take
8458 // ownership of the set first.
8459 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8460 PendingOdrMergeFailures.clear();
8461 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008462 Merge.first->buildLookup();
8463 Merge.first->decls_begin();
8464 Merge.first->bases_begin();
8465 Merge.first->vbases_begin();
8466 for (auto *RD : Merge.second) {
8467 RD->decls_begin();
8468 RD->bases_begin();
8469 RD->vbases_begin();
8470 }
8471 }
8472
8473 // For each declaration from a merged context, check that the canonical
8474 // definition of that context also contains a declaration of the same
8475 // entity.
8476 //
8477 // Caution: this loop does things that might invalidate iterators into
8478 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8479 while (!PendingOdrMergeChecks.empty()) {
8480 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8481
8482 // FIXME: Skip over implicit declarations for now. This matters for things
8483 // like implicitly-declared special member functions. This isn't entirely
8484 // correct; we can end up with multiple unmerged declarations of the same
8485 // implicit entity.
8486 if (D->isImplicit())
8487 continue;
8488
8489 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008490
8491 bool Found = false;
8492 const Decl *DCanon = D->getCanonicalDecl();
8493
Richard Smith01bdb7a2014-08-28 05:44:07 +00008494 for (auto RI : D->redecls()) {
8495 if (RI->getLexicalDeclContext() == CanonDef) {
8496 Found = true;
8497 break;
8498 }
8499 }
8500 if (Found)
8501 continue;
8502
Richard Smith0f4e2c42015-08-06 04:23:48 +00008503 // Quick check failed, time to do the slow thing. Note, we can't just
8504 // look up the name of D in CanonDef here, because the member that is
8505 // in CanonDef might not be found by name lookup (it might have been
8506 // replaced by a more recent declaration in the lookup table), and we
8507 // can't necessarily find it in the redeclaration chain because it might
8508 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008509 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008510 for (auto *CanonMember : CanonDef->decls()) {
8511 if (CanonMember->getCanonicalDecl() == DCanon) {
8512 // This can happen if the declaration is merely mergeable and not
8513 // actually redeclarable (we looked for redeclarations earlier).
8514 //
8515 // FIXME: We should be able to detect this more efficiently, without
8516 // pulling in all of the members of CanonDef.
8517 Found = true;
8518 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008519 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008520 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8521 if (ND->getDeclName() == D->getDeclName())
8522 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008523 }
8524
8525 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008526 // The AST doesn't like TagDecls becoming invalid after they've been
8527 // completed. We only really need to mark FieldDecls as invalid here.
8528 if (!isa<TagDecl>(D))
8529 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008530
8531 // Ensure we don't accidentally recursively enter deserialization while
8532 // we're producing our diagnostic.
8533 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008534
8535 std::string CanonDefModule =
8536 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8537 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8538 << D << getOwningModuleNameForDiagnostic(D)
8539 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8540
8541 if (Candidates.empty())
8542 Diag(cast<Decl>(CanonDef)->getLocation(),
8543 diag::note_module_odr_violation_no_possible_decls) << D;
8544 else {
8545 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8546 Diag(Candidates[I]->getLocation(),
8547 diag::note_module_odr_violation_possible_decl)
8548 << Candidates[I];
8549 }
8550
8551 DiagnosedOdrMergeFailures.insert(CanonDef);
8552 }
8553 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008554
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008555 if (OdrMergeFailures.empty())
8556 return;
8557
8558 // Ensure we don't accidentally recursively enter deserialization while
8559 // we're producing our diagnostics.
8560 Deserializing RecursionGuard(this);
8561
Richard Smithcd45dbc2014-04-19 03:48:30 +00008562 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008563 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008564 // If we've already pointed out a specific problem with this class, don't
8565 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008566 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008567 continue;
8568
8569 bool Diagnosed = false;
8570 for (auto *RD : Merge.second) {
8571 // Multiple different declarations got merged together; tell the user
8572 // where they came from.
8573 if (Merge.first != RD) {
8574 // FIXME: Walk the definition, figure out what's different,
8575 // and diagnose that.
8576 if (!Diagnosed) {
8577 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8578 Diag(Merge.first->getLocation(),
8579 diag::err_module_odr_violation_different_definitions)
8580 << Merge.first << Module.empty() << Module;
8581 Diagnosed = true;
8582 }
8583
8584 Diag(RD->getLocation(),
8585 diag::note_module_odr_violation_different_definitions)
8586 << getOwningModuleNameForDiagnostic(RD);
8587 }
8588 }
8589
8590 if (!Diagnosed) {
8591 // All definitions are updates to the same declaration. This happens if a
8592 // module instantiates the declaration of a class template specialization
8593 // and two or more other modules instantiate its definition.
8594 //
8595 // FIXME: Indicate which modules had instantiations of this definition.
8596 // FIXME: How can this even happen?
8597 Diag(Merge.first->getLocation(),
8598 diag::err_module_odr_violation_different_instantiations)
8599 << Merge.first;
8600 }
8601 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008602}
8603
Richard Smithce18a182015-07-14 00:26:00 +00008604void ASTReader::StartedDeserializing() {
8605 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8606 ReadTimer->startTimer();
8607}
8608
Guy Benyei11169dd2012-12-18 14:30:41 +00008609void ASTReader::FinishedDeserializing() {
8610 assert(NumCurrentElementsDeserializing &&
8611 "FinishedDeserializing not paired with StartedDeserializing");
8612 if (NumCurrentElementsDeserializing == 1) {
8613 // We decrease NumCurrentElementsDeserializing only after pending actions
8614 // are finished, to avoid recursively re-calling finishPendingActions().
8615 finishPendingActions();
8616 }
8617 --NumCurrentElementsDeserializing;
8618
Richard Smitha0ce9c42014-07-29 23:23:27 +00008619 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008620 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008621 while (!PendingExceptionSpecUpdates.empty()) {
8622 auto Updates = std::move(PendingExceptionSpecUpdates);
8623 PendingExceptionSpecUpdates.clear();
8624 for (auto Update : Updates) {
8625 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008626 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008627 if (auto *Listener = Context.getASTMutationListener())
8628 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008629 for (auto *Redecl : Update.second->redecls())
8630 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008631 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008632 }
8633
Richard Smithce18a182015-07-14 00:26:00 +00008634 if (ReadTimer)
8635 ReadTimer->stopTimer();
8636
Richard Smith0f4e2c42015-08-06 04:23:48 +00008637 diagnoseOdrViolations();
8638
Richard Smith04d05b52014-03-23 00:27:18 +00008639 // We are not in recursive loading, so it's safe to pass the "interesting"
8640 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008641 if (Consumer)
8642 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008643 }
8644}
8645
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008646void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008647 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8648 // Remove any fake results before adding any real ones.
8649 auto It = PendingFakeLookupResults.find(II);
8650 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008651 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008652 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008653 // FIXME: this works around module+PCH performance issue.
8654 // Rather than erase the result from the map, which is O(n), just clear
8655 // the vector of NamedDecls.
8656 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008657 }
8658 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008659
8660 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8661 SemaObj->TUScope->AddDecl(D);
8662 } else if (SemaObj->TUScope) {
8663 // Adding the decl to IdResolver may have failed because it was already in
8664 // (even though it was not added in scope). If it is already in, make sure
8665 // it gets in the scope as well.
8666 if (std::find(SemaObj->IdResolver.begin(Name),
8667 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8668 SemaObj->TUScope->AddDecl(D);
8669 }
8670}
8671
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008672ASTReader::ASTReader(
8673 Preprocessor &PP, ASTContext &Context,
8674 const PCHContainerReader &PCHContainerRdr,
8675 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8676 StringRef isysroot, bool DisableValidation,
8677 bool AllowASTWithCompilerErrors,
8678 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8679 bool UseGlobalIndex,
8680 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008681 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008682 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008683 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008684 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008685 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008686 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008687 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008688 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8689 AllowConfigurationMismatch(AllowConfigurationMismatch),
8690 ValidateSystemInputs(ValidateSystemInputs),
8691 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008692 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8693 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8694 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8695 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008696 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8697 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8698 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8699 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8700 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8701 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008702 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008704
8705 for (const auto &Ext : Extensions) {
8706 auto BlockName = Ext->getExtensionMetadata().BlockName;
8707 auto Known = ModuleFileExtensions.find(BlockName);
8708 if (Known != ModuleFileExtensions.end()) {
8709 Diags.Report(diag::warn_duplicate_module_file_extension)
8710 << BlockName;
8711 continue;
8712 }
8713
8714 ModuleFileExtensions.insert({BlockName, Ext});
8715 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008716}
8717
8718ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008719 if (OwnsDeserializationListener)
8720 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008721}