blob: 0677ee4dbdff82db1738cf135d5a3a730eec3a21 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000051#include "llvm/Support/Compression.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000052#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000057#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000059#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000061#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000062
63using namespace clang;
64using namespace clang::serialization;
65using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000066using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Ben Langmuircb69b572014-03-07 06:40:32 +000068
69//===----------------------------------------------------------------------===//
70// ChainedASTReaderListener implementation
71//===----------------------------------------------------------------------===//
72
73bool
74ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
75 return First->ReadFullVersionInformation(FullVersion) ||
76 Second->ReadFullVersionInformation(FullVersion);
77}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000078void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
79 First->ReadModuleName(ModuleName);
80 Second->ReadModuleName(ModuleName);
81}
82void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
83 First->ReadModuleMapFile(ModuleMapPath);
84 Second->ReadModuleMapFile(ModuleMapPath);
85}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000086bool
87ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
88 bool Complain,
89 bool AllowCompatibleDifferences) {
90 return First->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences) ||
92 Second->ReadLanguageOptions(LangOpts, Complain,
93 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000094}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000095bool ChainedASTReaderListener::ReadTargetOptions(
96 const TargetOptions &TargetOpts, bool Complain,
97 bool AllowCompatibleDifferences) {
98 return First->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences) ||
100 Second->ReadTargetOptions(TargetOpts, Complain,
101 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000102}
103bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000104 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000105 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
106 Second->ReadDiagnosticOptions(DiagOpts, Complain);
107}
108bool
109ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
110 bool Complain) {
111 return First->ReadFileSystemOptions(FSOpts, Complain) ||
112 Second->ReadFileSystemOptions(FSOpts, Complain);
113}
114
115bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000116 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
117 bool Complain) {
118 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain) ||
120 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
121 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000122}
123bool ChainedASTReaderListener::ReadPreprocessorOptions(
124 const PreprocessorOptions &PPOpts, bool Complain,
125 std::string &SuggestedPredefines) {
126 return First->ReadPreprocessorOptions(PPOpts, Complain,
127 SuggestedPredefines) ||
128 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
129}
130void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
131 unsigned Value) {
132 First->ReadCounter(M, Value);
133 Second->ReadCounter(M, Value);
134}
135bool ChainedASTReaderListener::needsInputFileVisitation() {
136 return First->needsInputFileVisitation() ||
137 Second->needsInputFileVisitation();
138}
139bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
140 return First->needsSystemInputFileVisitation() ||
141 Second->needsSystemInputFileVisitation();
142}
Richard Smith216a3bd2015-08-13 17:57:10 +0000143void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
144 ModuleKind Kind) {
145 First->visitModuleFile(Filename, Kind);
146 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000147}
Ben Langmuircb69b572014-03-07 06:40:32 +0000148bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000149 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000150 bool isOverridden,
151 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000152 bool Continue = false;
153 if (First->needsInputFileVisitation() &&
154 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000155 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
156 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000157 if (Second->needsInputFileVisitation() &&
158 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000159 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
160 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000161 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000162}
163
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000164void ChainedASTReaderListener::readModuleFileExtension(
165 const ModuleFileExtensionMetadata &Metadata) {
166 First->readModuleFileExtension(Metadata);
167 Second->readModuleFileExtension(Metadata);
168}
169
Guy Benyei11169dd2012-12-18 14:30:41 +0000170//===----------------------------------------------------------------------===//
171// PCH validator implementation
172//===----------------------------------------------------------------------===//
173
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000174ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000175
176/// \brief Compare the given set of language options against an existing set of
177/// language options.
178///
179/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000180/// \param AllowCompatibleDifferences If true, differences between compatible
181/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000182///
183/// \returns true if the languagae options mis-match, false otherwise.
184static bool checkLanguageOptions(const LangOptions &LangOpts,
185 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000186 DiagnosticsEngine *Diags,
187 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000188#define LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_mismatch) \
192 << Description << LangOpts.Name << ExistingLangOpts.Name; \
193 return true; \
194 }
195
196#define VALUE_LANGOPT(Name, Bits, Default, Description) \
197 if (ExistingLangOpts.Name != LangOpts.Name) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
204#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
205 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
206 if (Diags) \
207 Diags->Report(diag::err_pch_langopt_value_mismatch) \
208 << Description; \
209 return true; \
210 }
211
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000212#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
213 if (!AllowCompatibleDifferences) \
214 LANGOPT(Name, Bits, Default, Description)
215
216#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
217 if (!AllowCompatibleDifferences) \
218 ENUM_LANGOPT(Name, Bits, Default, Description)
219
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000220#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
221 if (!AllowCompatibleDifferences) \
222 VALUE_LANGOPT(Name, Bits, Default, Description)
223
Guy Benyei11169dd2012-12-18 14:30:41 +0000224#define BENIGN_LANGOPT(Name, Bits, Default, Description)
225#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000226#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000227#include "clang/Basic/LangOptions.def"
228
Ben Langmuircd98cb72015-06-23 18:20:18 +0000229 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
230 if (Diags)
231 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
232 return true;
233 }
234
Guy Benyei11169dd2012-12-18 14:30:41 +0000235 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
236 if (Diags)
237 Diags->Report(diag::err_pch_langopt_value_mismatch)
238 << "target Objective-C runtime";
239 return true;
240 }
241
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000242 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
243 LangOpts.CommentOpts.BlockCommandNames) {
244 if (Diags)
245 Diags->Report(diag::err_pch_langopt_value_mismatch)
246 << "block command names";
247 return true;
248 }
249
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 return false;
251}
252
253/// \brief Compare the given set of target options against an existing set of
254/// target options.
255///
256/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
257///
258/// \returns true if the target options mis-match, false otherwise.
259static bool checkTargetOptions(const TargetOptions &TargetOpts,
260 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261 DiagnosticsEngine *Diags,
262 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000263#define CHECK_TARGET_OPT(Field, Name) \
264 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
265 if (Diags) \
266 Diags->Report(diag::err_pch_targetopt_mismatch) \
267 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
268 return true; \
269 }
270
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000271 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000272 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000273 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000274
275 // We can tolerate different CPUs in many cases, notably when one CPU
276 // supports a strict superset of another. When allowing compatible
277 // differences skip this check.
278 if (!AllowCompatibleDifferences)
279 CHECK_TARGET_OPT(CPU, "target CPU");
280
Guy Benyei11169dd2012-12-18 14:30:41 +0000281#undef CHECK_TARGET_OPT
282
283 // Compare feature sets.
284 SmallVector<StringRef, 4> ExistingFeatures(
285 ExistingTargetOpts.FeaturesAsWritten.begin(),
286 ExistingTargetOpts.FeaturesAsWritten.end());
287 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
288 TargetOpts.FeaturesAsWritten.end());
289 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
290 std::sort(ReadFeatures.begin(), ReadFeatures.end());
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 // We compute the set difference in both directions explicitly so that we can
293 // diagnose the differences differently.
294 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
295 std::set_difference(
296 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
297 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
298 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
299 ExistingFeatures.begin(), ExistingFeatures.end(),
300 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000301
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000302 // If we are allowing compatible differences and the read feature set is
303 // a strict subset of the existing feature set, there is nothing to diagnose.
304 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
305 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000306
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000307 if (Diags) {
308 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 << /* is-existing-feature */ false << Feature;
311 for (StringRef Feature : UnmatchedExistingFeatures)
312 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
313 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 }
315
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000316 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000317}
318
319bool
320PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000321 bool Complain,
322 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 const LangOptions &ExistingLangOpts = PP.getLangOpts();
324 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000325 Complain ? &Reader.Diags : nullptr,
326 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000327}
328
329bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000330 bool Complain,
331 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
333 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000334 Complain ? &Reader.Diags : nullptr,
335 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000336}
337
338namespace {
339 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
340 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000341 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
342 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000343}
344
Ben Langmuirb92de022014-04-29 16:25:26 +0000345static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
346 DiagnosticsEngine &Diags,
347 bool Complain) {
348 typedef DiagnosticsEngine::Level Level;
349
350 // Check current mappings for new -Werror mappings, and the stored mappings
351 // for cases that were explicitly mapped to *not* be errors that are now
352 // errors because of options like -Werror.
353 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
354
355 for (DiagnosticsEngine *MappingSource : MappingSources) {
356 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
357 diag::kind DiagID = DiagIDMappingPair.first;
358 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
359 if (CurLevel < DiagnosticsEngine::Error)
360 continue; // not significant
361 Level StoredLevel =
362 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
363 if (StoredLevel < DiagnosticsEngine::Error) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
366 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
367 return true;
368 }
369 }
370 }
371
372 return false;
373}
374
Alp Tokerac4e8e52014-06-22 21:58:33 +0000375static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
376 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
377 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
378 return true;
379 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000380}
381
382static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
383 DiagnosticsEngine &Diags,
384 bool IsSystem, bool Complain) {
385 // Top-level options
386 if (IsSystem) {
387 if (Diags.getSuppressSystemWarnings())
388 return false;
389 // If -Wsystem-headers was not enabled before, be conservative
390 if (StoredDiags.getSuppressSystemWarnings()) {
391 if (Complain)
392 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
393 return true;
394 }
395 }
396
397 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
398 if (Complain)
399 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
400 return true;
401 }
402
403 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
404 !StoredDiags.getEnableAllWarnings()) {
405 if (Complain)
406 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
407 return true;
408 }
409
410 if (isExtHandlingFromDiagsError(Diags) &&
411 !isExtHandlingFromDiagsError(StoredDiags)) {
412 if (Complain)
413 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
414 return true;
415 }
416
417 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
418}
419
420bool PCHValidator::ReadDiagnosticOptions(
421 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
422 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
423 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
424 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000425 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000426 // This should never fail, because we would have processed these options
427 // before writing them to an ASTFile.
428 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
429
430 ModuleManager &ModuleMgr = Reader.getModuleManager();
431 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
432
433 // If the original import came from a file explicitly generated by the user,
434 // don't check the diagnostic mappings.
435 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000436 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000437 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
438 // the transitive closure of its imports, since unrelated modules cannot be
439 // imported until after this module finishes validation.
440 ModuleFile *TopImport = *ModuleMgr.rbegin();
441 while (!TopImport->ImportedBy.empty())
442 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000443 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000444 return false;
445
446 StringRef ModuleName = TopImport->ModuleName;
447 assert(!ModuleName.empty() && "diagnostic options read before module name");
448
449 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
450 assert(M && "missing module");
451
452 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
453 // contains the union of their flags.
454 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
455}
456
Guy Benyei11169dd2012-12-18 14:30:41 +0000457/// \brief Collect the macro definitions provided by the given preprocessor
458/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000459static void
460collectMacroDefinitions(const PreprocessorOptions &PPOpts,
461 MacroDefinitionsMap &Macros,
462 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
464 StringRef Macro = PPOpts.Macros[I].first;
465 bool IsUndef = PPOpts.Macros[I].second;
466
467 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
468 StringRef MacroName = MacroPair.first;
469 StringRef MacroBody = MacroPair.second;
470
471 // For an #undef'd macro, we only care about the name.
472 if (IsUndef) {
473 if (MacroNames && !Macros.count(MacroName))
474 MacroNames->push_back(MacroName);
475
476 Macros[MacroName] = std::make_pair("", true);
477 continue;
478 }
479
480 // For a #define'd macro, figure out the actual definition.
481 if (MacroName.size() == Macro.size())
482 MacroBody = "1";
483 else {
484 // Note: GCC drops anything following an end-of-line character.
485 StringRef::size_type End = MacroBody.find_first_of("\n\r");
486 MacroBody = MacroBody.substr(0, End);
487 }
488
489 if (MacroNames && !Macros.count(MacroName))
490 MacroNames->push_back(MacroName);
491 Macros[MacroName] = std::make_pair(MacroBody, false);
492 }
493}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000494
Guy Benyei11169dd2012-12-18 14:30:41 +0000495/// \brief Check the preprocessor options deserialized from the control block
496/// against the preprocessor options in an existing preprocessor.
497///
498/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
499static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
500 const PreprocessorOptions &ExistingPPOpts,
501 DiagnosticsEngine *Diags,
502 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000503 std::string &SuggestedPredefines,
504 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000505 // Check macro definitions.
506 MacroDefinitionsMap ASTFileMacros;
507 collectMacroDefinitions(PPOpts, ASTFileMacros);
508 MacroDefinitionsMap ExistingMacros;
509 SmallVector<StringRef, 4> ExistingMacroNames;
510 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
511
512 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
513 // Dig out the macro definition in the existing preprocessor options.
514 StringRef MacroName = ExistingMacroNames[I];
515 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
516
517 // Check whether we know anything about this macro name or not.
518 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
519 = ASTFileMacros.find(MacroName);
520 if (Known == ASTFileMacros.end()) {
521 // FIXME: Check whether this identifier was referenced anywhere in the
522 // AST file. If so, we should reject the AST file. Unfortunately, this
523 // information isn't in the control block. What shall we do about it?
524
525 if (Existing.second) {
526 SuggestedPredefines += "#undef ";
527 SuggestedPredefines += MacroName.str();
528 SuggestedPredefines += '\n';
529 } else {
530 SuggestedPredefines += "#define ";
531 SuggestedPredefines += MacroName.str();
532 SuggestedPredefines += ' ';
533 SuggestedPredefines += Existing.first.str();
534 SuggestedPredefines += '\n';
535 }
536 continue;
537 }
538
539 // If the macro was defined in one but undef'd in the other, we have a
540 // conflict.
541 if (Existing.second != Known->second.second) {
542 if (Diags) {
543 Diags->Report(diag::err_pch_macro_def_undef)
544 << MacroName << Known->second.second;
545 }
546 return true;
547 }
548
549 // If the macro was #undef'd in both, or if the macro bodies are identical,
550 // it's fine.
551 if (Existing.second || Existing.first == Known->second.first)
552 continue;
553
554 // The macro bodies differ; complain.
555 if (Diags) {
556 Diags->Report(diag::err_pch_macro_def_conflict)
557 << MacroName << Known->second.first << Existing.first;
558 }
559 return true;
560 }
561
562 // Check whether we're using predefines.
563 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
564 if (Diags) {
565 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
566 }
567 return true;
568 }
569
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000570 // Detailed record is important since it is used for the module cache hash.
571 if (LangOpts.Modules &&
572 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
573 if (Diags) {
574 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
575 }
576 return true;
577 }
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 // Compute the #include and #include_macros lines we need.
580 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
581 StringRef File = ExistingPPOpts.Includes[I];
582 if (File == ExistingPPOpts.ImplicitPCHInclude)
583 continue;
584
585 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
586 != PPOpts.Includes.end())
587 continue;
588
589 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000590 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591 SuggestedPredefines += "\"\n";
592 }
593
594 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
595 StringRef File = ExistingPPOpts.MacroIncludes[I];
596 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
597 File)
598 != PPOpts.MacroIncludes.end())
599 continue;
600
601 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000602 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 SuggestedPredefines += "\"\n##\n";
604 }
605
606 return false;
607}
608
609bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
610 bool Complain,
611 std::string &SuggestedPredefines) {
612 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
613
614 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000615 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000616 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000617 SuggestedPredefines,
618 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000619}
620
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000621/// Check the header search options deserialized from the control block
622/// against the header search options in an existing preprocessor.
623///
624/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
625static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 StringRef ExistingModuleCachePath,
628 DiagnosticsEngine *Diags,
629 const LangOptions &LangOpts) {
630 if (LangOpts.Modules) {
631 if (SpecificModuleCachePath != ExistingModuleCachePath) {
632 if (Diags)
633 Diags->Report(diag::err_pch_modulecache_mismatch)
634 << SpecificModuleCachePath << ExistingModuleCachePath;
635 return true;
636 }
637 }
638
639 return false;
640}
641
642bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
643 StringRef SpecificModuleCachePath,
644 bool Complain) {
645 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
646 PP.getHeaderSearchInfo().getModuleCachePath(),
647 Complain ? &Reader.Diags : nullptr,
648 PP.getLangOpts());
649}
650
Guy Benyei11169dd2012-12-18 14:30:41 +0000651void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
652 PP.setCounterValue(Value);
653}
654
655//===----------------------------------------------------------------------===//
656// AST reader implementation
657//===----------------------------------------------------------------------===//
658
Nico Weber824285e2014-05-08 04:26:47 +0000659void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
660 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000661 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000662 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000663}
664
665
666
667unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
668 return serialization::ComputeHash(Sel);
669}
670
671
672std::pair<unsigned, unsigned>
673ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000674 using namespace llvm::support;
675 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
676 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 return std::make_pair(KeyLen, DataLen);
678}
679
680ASTSelectorLookupTrait::internal_key_type
681ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000682 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000683 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
685 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
686 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000687 if (N == 0)
688 return SelTable.getNullarySelector(FirstII);
689 else if (N == 1)
690 return SelTable.getUnarySelector(FirstII);
691
692 SmallVector<IdentifierInfo *, 16> Args;
693 Args.push_back(FirstII);
694 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 Args.push_back(Reader.getLocalIdentifier(
696 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000697
698 return SelTable.getSelector(N, Args.data());
699}
700
701ASTSelectorLookupTrait::data_type
702ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
703 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000705
706 data_type Result;
707
Justin Bogner57ba0b22014-03-28 22:03:24 +0000708 Result.ID = Reader.getGlobalSelectorID(
709 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000710 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
711 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
712 Result.InstanceBits = FullInstanceBits & 0x3;
713 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
714 Result.FactoryBits = FullFactoryBits & 0x3;
715 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
716 unsigned NumInstanceMethods = FullInstanceBits >> 3;
717 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000718
719 // Load instance methods
720 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000721 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
722 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 Result.Instance.push_back(Method);
724 }
725
726 // Load factory methods
727 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000728 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
729 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 Result.Factory.push_back(Method);
731 }
732
733 return Result;
734}
735
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000736unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
737 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000738}
739
740std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000741ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000742 using namespace llvm::support;
743 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
744 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 return std::make_pair(KeyLen, DataLen);
746}
747
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000748ASTIdentifierLookupTraitBase::internal_key_type
749ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000750 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000751 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000752}
753
Douglas Gregordcf25082013-02-11 18:16:18 +0000754/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000755static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
756 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000757 return II.hadMacroDefinition() ||
758 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000759 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000761 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
762 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000763}
764
Richard Smith76c2f2c2015-07-17 20:09:43 +0000765static bool readBit(unsigned &Bits) {
766 bool Value = Bits & 0x1;
767 Bits >>= 1;
768 return Value;
769}
770
Richard Smith79bf9202015-08-24 03:33:22 +0000771IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
772 using namespace llvm::support;
773 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
774 return Reader.getGlobalIdentifierID(F, RawID >> 1);
775}
776
Richard Smitheb4b58f62016-02-05 01:40:54 +0000777static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
778 if (!II.isFromAST()) {
779 II.setIsFromAST();
780 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
781 if (isInterestingIdentifier(Reader, II, IsModule))
782 II.setChangedSinceDeserialization();
783 }
784}
785
Guy Benyei11169dd2012-12-18 14:30:41 +0000786IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
787 const unsigned char* d,
788 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000789 using namespace llvm::support;
790 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 bool IsInteresting = RawID & 0x01;
792
793 // Wipe out the "is interesting" bit.
794 RawID = RawID >> 1;
795
Richard Smith76c2f2c2015-07-17 20:09:43 +0000796 // Build the IdentifierInfo and link the identifier ID with it.
797 IdentifierInfo *II = KnownII;
798 if (!II) {
799 II = &Reader.getIdentifierTable().getOwn(k);
800 KnownII = II;
801 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000802 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000803 Reader.markIdentifierUpToDate(II);
804
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
806 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000807 // For uninteresting identifiers, there's nothing else to do. Just notify
808 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 return II;
811 }
812
Justin Bogner57ba0b22014-03-28 22:03:24 +0000813 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
814 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000815 bool CPlusPlusOperatorKeyword = readBit(Bits);
816 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000817 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000818 bool Poisoned = readBit(Bits);
819 bool ExtensionToken = readBit(Bits);
820 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000821
822 assert(Bits == 0 && "Extra bits in the identifier?");
823 DataLen -= 8;
824
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 // Set or check the various bits in the IdentifierInfo structure.
826 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000827 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000828 II->revertTokenIDToIdentifier();
829 if (!F.isModule())
830 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
831 else if (HasRevertedBuiltin && II->getBuiltinID()) {
832 II->revertBuiltin();
833 assert((II->hasRevertedBuiltin() ||
834 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
835 "Incorrect ObjC keyword or builtin ID");
836 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 assert(II->isExtensionToken() == ExtensionToken &&
838 "Incorrect extension token flag");
839 (void)ExtensionToken;
840 if (Poisoned)
841 II->setIsPoisoned(true);
842 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
843 "Incorrect C++ operator keyword flag");
844 (void)CPlusPlusOperatorKeyword;
845
846 // If this identifier is a macro, deserialize the macro
847 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000848 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000849 uint32_t MacroDirectivesOffset =
850 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000851 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000852
Richard Smithd7329392015-04-21 21:46:32 +0000853 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 }
855
856 Reader.SetIdentifierInfo(ID, II);
857
858 // Read all of the declarations visible at global scope with this
859 // name.
860 if (DataLen > 0) {
861 SmallVector<uint32_t, 4> DeclIDs;
862 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000863 DeclIDs.push_back(Reader.getGlobalDeclID(
864 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 Reader.SetGloballyVisibleDecls(II, DeclIDs);
866 }
867
868 return II;
869}
870
Richard Smitha06c7e62015-08-26 23:55:49 +0000871DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
872 : Kind(Name.getNameKind()) {
873 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000875 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 break;
877 case DeclarationName::ObjCZeroArgSelector:
878 case DeclarationName::ObjCOneArgSelector:
879 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000880 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 break;
882 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000883 Data = Name.getCXXOverloadedOperator();
884 break;
885 case DeclarationName::CXXLiteralOperatorName:
886 Data = (uint64_t)Name.getCXXLiteralIdentifier();
887 break;
888 case DeclarationName::CXXConstructorName:
889 case DeclarationName::CXXDestructorName:
890 case DeclarationName::CXXConversionFunctionName:
891 case DeclarationName::CXXUsingDirective:
892 Data = 0;
893 break;
894 }
895}
896
897unsigned DeclarationNameKey::getHash() const {
898 llvm::FoldingSetNodeID ID;
899 ID.AddInteger(Kind);
900
901 switch (Kind) {
902 case DeclarationName::Identifier:
903 case DeclarationName::CXXLiteralOperatorName:
904 ID.AddString(((IdentifierInfo*)Data)->getName());
905 break;
906 case DeclarationName::ObjCZeroArgSelector:
907 case DeclarationName::ObjCOneArgSelector:
908 case DeclarationName::ObjCMultiArgSelector:
909 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
910 break;
911 case DeclarationName::CXXOperatorName:
912 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 break;
914 case DeclarationName::CXXConstructorName:
915 case DeclarationName::CXXDestructorName:
916 case DeclarationName::CXXConversionFunctionName:
917 case DeclarationName::CXXUsingDirective:
918 break;
919 }
920
921 return ID.ComputeHash();
922}
923
Richard Smithd88a7f12015-09-01 20:35:42 +0000924ModuleFile *
925ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
926 using namespace llvm::support;
927 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
928 return Reader.getLocalModuleFile(F, ModuleFileID);
929}
930
Guy Benyei11169dd2012-12-18 14:30:41 +0000931std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000932ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 using namespace llvm::support;
934 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
935 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 return std::make_pair(KeyLen, DataLen);
937}
938
Richard Smitha06c7e62015-08-26 23:55:49 +0000939ASTDeclContextNameLookupTrait::internal_key_type
940ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000942
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 auto Kind = (DeclarationName::NameKind)*d++;
944 uint64_t Data;
945 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000947 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 break;
950 case DeclarationName::ObjCZeroArgSelector:
951 case DeclarationName::ObjCOneArgSelector:
952 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000953 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000954 (uint64_t)Reader.getLocalSelector(
955 F, endian::readNext<uint32_t, little, unaligned>(
956 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 break;
958 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000959 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000962 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000963 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 break;
965 case DeclarationName::CXXConstructorName:
966 case DeclarationName::CXXDestructorName:
967 case DeclarationName::CXXConversionFunctionName:
968 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000969 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 break;
971 }
972
Richard Smitha06c7e62015-08-26 23:55:49 +0000973 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000974}
975
Richard Smithd88a7f12015-09-01 20:35:42 +0000976void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
977 const unsigned char *d,
978 unsigned DataLen,
979 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000980 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000981 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
982 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
983 Val.insert(Reader.getGlobalDeclID(F, LocalID));
984 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000985}
986
Richard Smith0f4e2c42015-08-06 04:23:48 +0000987bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
988 BitstreamCursor &Cursor,
989 uint64_t Offset,
990 DeclContext *DC) {
991 assert(Offset != 0);
992
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000994 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995
Richard Smith0f4e2c42015-08-06 04:23:48 +0000996 RecordData Record;
997 StringRef Blob;
998 unsigned Code = Cursor.ReadCode();
999 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1000 if (RecCode != DECL_CONTEXT_LEXICAL) {
1001 Error("Expected lexical block");
1002 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 }
1004
Richard Smith82f8fcd2015-08-06 22:07:25 +00001005 assert(!isa<TranslationUnitDecl>(DC) &&
1006 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001007 // If we are handling a C++ class template instantiation, we can see multiple
1008 // lexical updates for the same record. It's important that we select only one
1009 // of them, so that field numbering works properly. Just pick the first one we
1010 // see.
1011 auto &Lex = LexicalDecls[DC];
1012 if (!Lex.first) {
1013 Lex = std::make_pair(
1014 &M, llvm::makeArrayRef(
1015 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1016 Blob.data()),
1017 Blob.size() / 4));
1018 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001019 DC->setHasExternalLexicalStorage(true);
1020 return false;
1021}
Guy Benyei11169dd2012-12-18 14:30:41 +00001022
Richard Smith0f4e2c42015-08-06 04:23:48 +00001023bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1024 BitstreamCursor &Cursor,
1025 uint64_t Offset,
1026 DeclID ID) {
1027 assert(Offset != 0);
1028
1029 SavedStreamPosition SavedPosition(Cursor);
1030 Cursor.JumpToBit(Offset);
1031
1032 RecordData Record;
1033 StringRef Blob;
1034 unsigned Code = Cursor.ReadCode();
1035 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1036 if (RecCode != DECL_CONTEXT_VISIBLE) {
1037 Error("Expected visible lookup table block");
1038 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 }
1040
Richard Smith0f4e2c42015-08-06 04:23:48 +00001041 // We can't safely determine the primary context yet, so delay attaching the
1042 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001043 auto *Data = (const unsigned char*)Blob.data();
1044 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 return false;
1046}
1047
1048void ASTReader::Error(StringRef Msg) {
1049 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001050 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1051 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001052 Diag(diag::note_module_cache_path)
1053 << PP.getHeaderSearchInfo().getModuleCachePath();
1054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001055}
1056
1057void ASTReader::Error(unsigned DiagID,
1058 StringRef Arg1, StringRef Arg2) {
1059 if (Diags.isDiagnosticInFlight())
1060 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1061 else
1062 Diag(DiagID) << Arg1 << Arg2;
1063}
1064
1065//===----------------------------------------------------------------------===//
1066// Source Manager Deserialization
1067//===----------------------------------------------------------------------===//
1068
1069/// \brief Read the line table in the source manager block.
1070/// \returns true if there was an error.
1071bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001072 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001073 unsigned Idx = 0;
1074 LineTableInfo &LineTable = SourceMgr.getLineTable();
1075
1076 // Parse the file names
1077 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001078 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001080 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1082 }
Richard Smith63078492015-09-01 07:41:55 +00001083 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001084
1085 // Parse the line entries
1086 std::vector<LineEntry> Entries;
1087 while (Idx < Record.size()) {
1088 int FID = Record[Idx++];
1089 assert(FID >= 0 && "Serialized line entries for non-local file.");
1090 // Remap FileID from 1-based old view.
1091 FID += F.SLocEntryBaseID - 1;
1092
1093 // Extract the line entries
1094 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001095 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 Entries.clear();
1097 Entries.reserve(NumEntries);
1098 for (unsigned I = 0; I != NumEntries; ++I) {
1099 unsigned FileOffset = Record[Idx++];
1100 unsigned LineNo = Record[Idx++];
1101 int FilenameID = FileIDs[Record[Idx++]];
1102 SrcMgr::CharacteristicKind FileKind
1103 = (SrcMgr::CharacteristicKind)Record[Idx++];
1104 unsigned IncludeOffset = Record[Idx++];
1105 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1106 FileKind, IncludeOffset));
1107 }
1108 LineTable.AddEntry(FileID::get(FID), Entries);
1109 }
1110
1111 return false;
1112}
1113
1114/// \brief Read a source manager block
1115bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1116 using namespace SrcMgr;
1117
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001118 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001119
1120 // Set the source-location entry cursor to the current position in
1121 // the stream. This cursor will be used to read the contents of the
1122 // source manager block initially, and then lazily read
1123 // source-location entries as needed.
1124 SLocEntryCursor = F.Stream;
1125
1126 // The stream itself is going to skip over the source manager block.
1127 if (F.Stream.SkipBlock()) {
1128 Error("malformed block record in AST file");
1129 return true;
1130 }
1131
1132 // Enter the source manager block.
1133 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1134 Error("malformed source manager block record in AST file");
1135 return true;
1136 }
1137
1138 RecordData Record;
1139 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001140 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1141
1142 switch (E.Kind) {
1143 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1144 case llvm::BitstreamEntry::Error:
1145 Error("malformed block record in AST file");
1146 return true;
1147 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001149 case llvm::BitstreamEntry::Record:
1150 // The interesting case.
1151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001153
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001156 StringRef Blob;
1157 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 default: // Default behavior: ignore.
1159 break;
1160
1161 case SM_SLOC_FILE_ENTRY:
1162 case SM_SLOC_BUFFER_ENTRY:
1163 case SM_SLOC_EXPANSION_ENTRY:
1164 // Once we hit one of the source location entries, we're done.
1165 return false;
1166 }
1167 }
1168}
1169
1170/// \brief If a header file is not found at the path that we expect it to be
1171/// and the PCH file was moved from its original location, try to resolve the
1172/// file by assuming that header+PCH were moved together and the header is in
1173/// the same place relative to the PCH.
1174static std::string
1175resolveFileRelativeToOriginalDir(const std::string &Filename,
1176 const std::string &OriginalDir,
1177 const std::string &CurrDir) {
1178 assert(OriginalDir != CurrDir &&
1179 "No point trying to resolve the file if the PCH dir didn't change");
1180 using namespace llvm::sys;
1181 SmallString<128> filePath(Filename);
1182 fs::make_absolute(filePath);
1183 assert(path::is_absolute(OriginalDir));
1184 SmallString<128> currPCHPath(CurrDir);
1185
1186 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1187 fileDirE = path::end(path::parent_path(filePath));
1188 path::const_iterator origDirI = path::begin(OriginalDir),
1189 origDirE = path::end(OriginalDir);
1190 // Skip the common path components from filePath and OriginalDir.
1191 while (fileDirI != fileDirE && origDirI != origDirE &&
1192 *fileDirI == *origDirI) {
1193 ++fileDirI;
1194 ++origDirI;
1195 }
1196 for (; origDirI != origDirE; ++origDirI)
1197 path::append(currPCHPath, "..");
1198 path::append(currPCHPath, fileDirI, fileDirE);
1199 path::append(currPCHPath, path::filename(Filename));
1200 return currPCHPath.str();
1201}
1202
1203bool ASTReader::ReadSLocEntry(int ID) {
1204 if (ID == 0)
1205 return false;
1206
1207 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1208 Error("source location entry ID out-of-range for AST file");
1209 return true;
1210 }
1211
Richard Smithaada85c2016-02-06 02:06:43 +00001212 // Local helper to read the (possibly-compressed) buffer data following the
1213 // entry record.
1214 auto ReadBuffer = [this](
1215 BitstreamCursor &SLocEntryCursor,
1216 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1217 RecordData Record;
1218 StringRef Blob;
1219 unsigned Code = SLocEntryCursor.ReadCode();
1220 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1221
1222 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1223 SmallString<0> Uncompressed;
1224 if (llvm::zlib::uncompress(Blob, Uncompressed, Record[0]) !=
1225 llvm::zlib::StatusOK) {
1226 Error("could not decompress embedded file contents");
1227 return nullptr;
1228 }
1229 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1230 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1231 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1232 } else {
1233 Error("AST record has invalid code");
1234 return nullptr;
1235 }
1236 };
1237
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1239 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001240 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 unsigned BaseOffset = F->SLocEntryBaseOffset;
1242
1243 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001244 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1245 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 Error("incorrectly-formatted source location entry in AST file");
1247 return true;
1248 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001249
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001251 StringRef Blob;
1252 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 default:
1254 Error("incorrectly-formatted source location entry in AST file");
1255 return true;
1256
1257 case SM_SLOC_FILE_ENTRY: {
1258 // We will detect whether a file changed and return 'Failure' for it, but
1259 // we will also try to fail gracefully by setting up the SLocEntry.
1260 unsigned InputID = Record[4];
1261 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001262 const FileEntry *File = IF.getFile();
1263 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001264
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001265 // Note that we only check if a File was returned. If it was out-of-date
1266 // we have complained but we will continue creating a FileID to recover
1267 // gracefully.
1268 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 return true;
1270
1271 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1272 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1273 // This is the module's main file.
1274 IncludeLoc = getImportLocation(F);
1275 }
1276 SrcMgr::CharacteristicKind
1277 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1278 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1279 ID, BaseOffset + Record[0]);
1280 SrcMgr::FileInfo &FileInfo =
1281 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1282 FileInfo.NumCreatedFIDs = Record[5];
1283 if (Record[3])
1284 FileInfo.setHasLineDirectives();
1285
1286 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1287 unsigned NumFileDecls = Record[7];
1288 if (NumFileDecls) {
1289 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1290 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1291 NumFileDecls));
1292 }
Richard Smithaada85c2016-02-06 02:06:43 +00001293
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 const SrcMgr::ContentCache *ContentCache
1295 = SourceMgr.getOrCreateContentCache(File,
1296 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1297 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001298 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1299 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001300 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1301 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001303 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 }
1305
1306 break;
1307 }
1308
1309 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001310 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 unsigned Offset = Record[0];
1312 SrcMgr::CharacteristicKind
1313 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1314 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001315 if (IncludeLoc.isInvalid() &&
1316 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 IncludeLoc = getImportLocation(F);
1318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001319
Richard Smithaada85c2016-02-06 02:06:43 +00001320 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1321 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001323 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001324 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 break;
1326 }
1327
1328 case SM_SLOC_EXPANSION_ENTRY: {
1329 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1330 SourceMgr.createExpansionLoc(SpellingLoc,
1331 ReadSourceLocation(*F, Record[2]),
1332 ReadSourceLocation(*F, Record[3]),
1333 Record[4],
1334 ID,
1335 BaseOffset + Record[0]);
1336 break;
1337 }
1338 }
1339
1340 return false;
1341}
1342
1343std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1344 if (ID == 0)
1345 return std::make_pair(SourceLocation(), "");
1346
1347 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1348 Error("source location entry ID out-of-range for AST file");
1349 return std::make_pair(SourceLocation(), "");
1350 }
1351
1352 // Find which module file this entry lands in.
1353 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001354 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 return std::make_pair(SourceLocation(), "");
1356
1357 // FIXME: Can we map this down to a particular submodule? That would be
1358 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001359 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001360}
1361
1362/// \brief Find the location where the module F is imported.
1363SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1364 if (F->ImportLoc.isValid())
1365 return F->ImportLoc;
1366
1367 // Otherwise we have a PCH. It's considered to be "imported" at the first
1368 // location of its includer.
1369 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001370 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001371 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001372 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 return F->ImportedBy[0]->FirstLoc;
1375}
1376
1377/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1378/// specified cursor. Read the abbreviations that are at the top of the block
1379/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001380bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001381 if (Cursor.EnterSubBlock(BlockID))
1382 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001383
1384 while (true) {
1385 uint64_t Offset = Cursor.GetCurrentBitNo();
1386 unsigned Code = Cursor.ReadCode();
1387
1388 // We expect all abbrevs to be at the start of the block.
1389 if (Code != llvm::bitc::DEFINE_ABBREV) {
1390 Cursor.JumpToBit(Offset);
1391 return false;
1392 }
1393 Cursor.ReadAbbrevRecord();
1394 }
1395}
1396
Richard Smithe40f2ba2013-08-07 21:41:30 +00001397Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001398 unsigned &Idx) {
1399 Token Tok;
1400 Tok.startToken();
1401 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1402 Tok.setLength(Record[Idx++]);
1403 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1404 Tok.setIdentifierInfo(II);
1405 Tok.setKind((tok::TokenKind)Record[Idx++]);
1406 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1407 return Tok;
1408}
1409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001411 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001412
1413 // Keep track of where we are in the stream, then jump back there
1414 // after reading this macro.
1415 SavedStreamPosition SavedPosition(Stream);
1416
1417 Stream.JumpToBit(Offset);
1418 RecordData Record;
1419 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001420 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001423 // Advance to the next record, but if we get to the end of the block, don't
1424 // pop it (removing all the abbreviations from the cursor) since we want to
1425 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001426 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001427 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1428
1429 switch (Entry.Kind) {
1430 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1431 case llvm::BitstreamEntry::Error:
1432 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001433 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001434 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001435 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001436 case llvm::BitstreamEntry::Record:
1437 // The interesting case.
1438 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 }
1440
1441 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 Record.clear();
1443 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001444 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001446 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001447 case PP_MACRO_DIRECTIVE_HISTORY:
1448 return Macro;
1449
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 case PP_MACRO_OBJECT_LIKE:
1451 case PP_MACRO_FUNCTION_LIKE: {
1452 // If we already have a macro, that means that we've hit the end
1453 // of the definition of the macro we were looking for. We're
1454 // done.
1455 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001456 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001457
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001458 unsigned NextIndex = 1; // Skip identifier ID.
1459 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001461 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001462 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001464 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001465
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1467 // Decode function-like macro info.
1468 bool isC99VarArgs = Record[NextIndex++];
1469 bool isGNUVarArgs = Record[NextIndex++];
1470 bool hasCommaPasting = Record[NextIndex++];
1471 MacroArgs.clear();
1472 unsigned NumArgs = Record[NextIndex++];
1473 for (unsigned i = 0; i != NumArgs; ++i)
1474 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1475
1476 // Install function-like macro info.
1477 MI->setIsFunctionLike();
1478 if (isC99VarArgs) MI->setIsC99Varargs();
1479 if (isGNUVarArgs) MI->setIsGNUVarargs();
1480 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001481 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001482 }
1483
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 // Remember that we saw this macro last so that we add the tokens that
1485 // form its body to it.
1486 Macro = MI;
1487
1488 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1489 Record[NextIndex]) {
1490 // We have a macro definition. Register the association
1491 PreprocessedEntityID
1492 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1493 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001494 PreprocessingRecord::PPEntityID PPID =
1495 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1496 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1497 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001498 if (PPDef)
1499 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 }
1501
1502 ++NumMacrosRead;
1503 break;
1504 }
1505
1506 case PP_TOKEN: {
1507 // If we see a TOKEN before a PP_MACRO_*, then the file is
1508 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001509 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001510
John McCallf413f5e2013-05-03 00:10:13 +00001511 unsigned Idx = 0;
1512 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 Macro->AddTokenToBody(Tok);
1514 break;
1515 }
1516 }
1517 }
1518}
1519
1520PreprocessedEntityID
1521ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1522 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1523 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1524 assert(I != M.PreprocessedEntityRemap.end()
1525 && "Invalid index into preprocessed entity index remap");
1526
1527 return LocalID + I->second;
1528}
1529
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001530unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1531 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001535HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001536 internal_key_type ikey = {FE->getSize(),
1537 M.HasTimestamps ? FE->getModificationTime() : 0,
1538 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001539 return ikey;
1540}
Guy Benyei11169dd2012-12-18 14:30:41 +00001541
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001542bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001543 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 return false;
1545
Richard Smith7ed1bc92014-12-05 22:42:13 +00001546 if (llvm::sys::path::is_absolute(a.Filename) &&
1547 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001548 return true;
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001551 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001552 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1553 if (!Key.Imported)
1554 return FileMgr.getFile(Key.Filename);
1555
1556 std::string Resolved = Key.Filename;
1557 Reader.ResolveImportedPath(M, Resolved);
1558 return FileMgr.getFile(Resolved);
1559 };
1560
1561 const FileEntry *FEA = GetFile(a);
1562 const FileEntry *FEB = GetFile(b);
1563 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001564}
1565
1566std::pair<unsigned, unsigned>
1567HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001568 using namespace llvm::support;
1569 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001571 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001572}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001573
1574HeaderFileInfoTrait::internal_key_type
1575HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001576 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001577 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001578 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1579 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001580 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001581 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001582 return ikey;
1583}
1584
Guy Benyei11169dd2012-12-18 14:30:41 +00001585HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001586HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 unsigned DataLen) {
1588 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001589 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 HeaderFileInfo HFI;
1591 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001592 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1593 HFI.isImport |= (Flags >> 4) & 0x01;
1594 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1595 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001597 // FIXME: Find a better way to handle this. Maybe just store a
1598 // "has been included" flag?
1599 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1600 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001601 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1602 M, endian::readNext<uint32_t, little, unaligned>(d));
1603 if (unsigned FrameworkOffset =
1604 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 // The framework offset is 1 greater than the actual offset,
1606 // since 0 is used as an indicator for "no framework name".
1607 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1608 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1609 }
Richard Smith386bb072015-08-18 23:42:23 +00001610
1611 assert((End - d) % 4 == 0 &&
1612 "Wrong data length in HeaderFileInfo deserialization");
1613 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001614 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001615 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1616 LocalSMID >>= 2;
1617
1618 // This header is part of a module. Associate it with the module to enable
1619 // implicit module import.
1620 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1621 Module *Mod = Reader.getSubmodule(GlobalSMID);
1622 FileManager &FileMgr = Reader.getFileManager();
1623 ModuleMap &ModMap =
1624 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1625
1626 std::string Filename = key.Filename;
1627 if (key.Imported)
1628 Reader.ResolveImportedPath(M, Filename);
1629 // FIXME: This is not always the right filename-as-written, but we're not
1630 // going to use this information to rebuild the module, so it doesn't make
1631 // a lot of difference.
1632 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001633 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1634 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001635 }
1636
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 // This HeaderFileInfo was externally loaded.
1638 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001639 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 return HFI;
1641}
1642
Richard Smithd7329392015-04-21 21:46:32 +00001643void ASTReader::addPendingMacro(IdentifierInfo *II,
1644 ModuleFile *M,
1645 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001646 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1647 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001648}
1649
1650void ASTReader::ReadDefinedMacros() {
1651 // Note that we are loading defined macros.
1652 Deserializing Macros(this);
1653
Pete Cooper57d3f142015-07-30 17:22:52 +00001654 for (auto &I : llvm::reverse(ModuleMgr)) {
1655 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001656
1657 // If there was no preprocessor block, skip this file.
1658 if (!MacroCursor.getBitStreamReader())
1659 continue;
1660
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001661 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001662 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001663
1664 RecordData Record;
1665 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001666 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1667
1668 switch (E.Kind) {
1669 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1670 case llvm::BitstreamEntry::Error:
1671 Error("malformed block record in AST file");
1672 return;
1673 case llvm::BitstreamEntry::EndBlock:
1674 goto NextCursor;
1675
1676 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001677 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001678 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001679 default: // Default behavior: ignore.
1680 break;
1681
1682 case PP_MACRO_OBJECT_LIKE:
1683 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001684 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001685 break;
1686
1687 case PP_TOKEN:
1688 // Ignore tokens.
1689 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001691 break;
1692 }
1693 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001694 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 }
1696}
1697
1698namespace {
1699 /// \brief Visitor class used to look up identifirs in an AST file.
1700 class IdentifierLookupVisitor {
1701 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001702 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001704 unsigned &NumIdentifierLookups;
1705 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001707
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1710 unsigned &NumIdentifierLookups,
1711 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001712 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1713 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001714 NumIdentifierLookups(NumIdentifierLookups),
1715 NumIdentifierLookupHits(NumIdentifierLookupHits),
1716 Found()
1717 {
1718 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001719
1720 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001722 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001724
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 ASTIdentifierLookupTable *IdTable
1726 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1727 if (!IdTable)
1728 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001729
1730 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001731 Found);
1732 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001733 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001734 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001735 if (Pos == IdTable->end())
1736 return false;
1737
1738 // Dereferencing the iterator has the effect of building the
1739 // IdentifierInfo node and populating it with the various
1740 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001741 ++NumIdentifierLookupHits;
1742 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 return true;
1744 }
1745
1746 // \brief Retrieve the identifier info found within the module
1747 // files.
1748 IdentifierInfo *getIdentifierInfo() const { return Found; }
1749 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001750}
Guy Benyei11169dd2012-12-18 14:30:41 +00001751
1752void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1753 // Note that we are loading an identifier.
1754 Deserializing AnIdentifier(this);
1755
1756 unsigned PriorGeneration = 0;
1757 if (getContext().getLangOpts().Modules)
1758 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001759
1760 // If there is a global index, look there first to determine which modules
1761 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001762 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001763 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001764 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001765 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1766 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001767 }
1768 }
1769
Douglas Gregor7211ac12013-01-25 23:32:03 +00001770 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001771 NumIdentifierLookups,
1772 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001773 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 markIdentifierUpToDate(&II);
1775}
1776
1777void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1778 if (!II)
1779 return;
1780
1781 II->setOutOfDate(false);
1782
1783 // Update the generation for this identifier.
1784 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001785 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001786}
1787
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1789 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001790 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001791
1792 BitstreamCursor &Cursor = M.MacroCursor;
1793 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001794 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001795
Richard Smith713369b2015-04-23 20:40:50 +00001796 struct ModuleMacroRecord {
1797 SubmoduleID SubModID;
1798 MacroInfo *MI;
1799 SmallVector<SubmoduleID, 8> Overrides;
1800 };
1801 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802
Richard Smithd7329392015-04-21 21:46:32 +00001803 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1804 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1805 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001806 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001807 while (true) {
1808 llvm::BitstreamEntry Entry =
1809 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1810 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001816 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001817 case PP_MACRO_DIRECTIVE_HISTORY:
1818 break;
1819
1820 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001821 ModuleMacros.push_back(ModuleMacroRecord());
1822 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001823 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1824 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001825 for (int I = 2, N = Record.size(); I != N; ++I)
1826 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001827 continue;
1828 }
1829
1830 default:
1831 Error("malformed block record in AST file");
1832 return;
1833 }
1834
1835 // We found the macro directive history; that's the last record
1836 // for this macro.
1837 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001838 }
1839
Richard Smithd7329392015-04-21 21:46:32 +00001840 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001841 {
1842 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001843 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001844 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001845 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001846 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001847 Module *Mod = getSubmodule(ModID);
1848 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001849 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001850 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001851 }
1852
1853 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001854 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001855 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001856 }
1857 }
1858
1859 // Don't read the directive history for a module; we don't have anywhere
1860 // to put it.
1861 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1862 return;
1863
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001865 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001866 unsigned Idx = 0, N = Record.size();
1867 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001868 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001870 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1871 switch (K) {
1872 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001873 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001874 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001875 break;
1876 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001877 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001878 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001879 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001880 }
1881 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001882 bool isPublic = Record[Idx++];
1883 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1884 break;
1885 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001886
1887 if (!Latest)
1888 Latest = MD;
1889 if (Earliest)
1890 Earliest->setPrevious(MD);
1891 Earliest = MD;
1892 }
1893
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001894 if (Latest)
1895 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001896}
1897
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001898ASTReader::InputFileInfo
1899ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001900 // Go find this input file.
1901 BitstreamCursor &Cursor = F.InputFilesCursor;
1902 SavedStreamPosition SavedPosition(Cursor);
1903 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1904
1905 unsigned Code = Cursor.ReadCode();
1906 RecordData Record;
1907 StringRef Blob;
1908
1909 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1910 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1911 "invalid record type for input file");
1912 (void)Result;
1913
1914 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001915 InputFileInfo R;
1916 R.StoredSize = static_cast<off_t>(Record[1]);
1917 R.StoredTime = static_cast<time_t>(Record[2]);
1918 R.Overridden = static_cast<bool>(Record[3]);
1919 R.Transient = static_cast<bool>(Record[4]);
1920 R.Filename = Blob;
1921 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001922 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001923}
1924
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001925InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 // If this ID is bogus, just return an empty input file.
1927 if (ID == 0 || ID > F.InputFilesLoaded.size())
1928 return InputFile();
1929
1930 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001931 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 return F.InputFilesLoaded[ID-1];
1933
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001934 if (F.InputFilesLoaded[ID-1].isNotFound())
1935 return InputFile();
1936
Guy Benyei11169dd2012-12-18 14:30:41 +00001937 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001938 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 SavedStreamPosition SavedPosition(Cursor);
1940 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1941
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001942 InputFileInfo FI = readInputFileInfo(F, ID);
1943 off_t StoredSize = FI.StoredSize;
1944 time_t StoredTime = FI.StoredTime;
1945 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001946 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001947 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001948
Richard Smitha8cfffa2015-11-26 02:04:16 +00001949 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00001950
1951 // If we didn't find the file, resolve it relative to the
1952 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001953 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 F.OriginalDir != CurrentDir) {
1955 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1956 F.OriginalDir,
1957 CurrentDir);
1958 if (!Resolved.empty())
1959 File = FileMgr.getFile(Resolved);
1960 }
1961
1962 // For an overridden file, create a virtual file with the stored
1963 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001964 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00001965 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00001966
Craig Toppera13603a2014-05-22 05:54:18 +00001967 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001968 if (Complain) {
1969 std::string ErrorStr = "could not find file '";
1970 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001971 ErrorStr += "' referenced by AST file '";
1972 ErrorStr += F.FileName;
1973 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001974 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001975 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001976 // Record that we didn't find the file.
1977 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1978 return InputFile();
1979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001980
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 // Check if there was a request to override the contents of the file
1982 // that was part of the precompiled header. Overridding such a file
1983 // can lead to problems when lexing using the source locations from the
1984 // PCH.
1985 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00001986 // FIXME: Reject if the overrides are different.
1987 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 if (Complain)
1989 Error(diag::err_fe_pch_file_overridden, Filename);
1990 // After emitting the diagnostic, recover by disabling the override so
1991 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001992 //
1993 // FIXME: This recovery is just as broken as the original state; there may
1994 // be another precompiled module that's using the overridden contents, or
1995 // we might be half way through parsing it. Instead, we should treat the
1996 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 SM.disableFileContentsOverride(File);
1998 // The FileEntry is a virtual file entry with the size of the contents
1999 // that would override the original contents. Set it to the original's
2000 // size/time.
2001 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2002 StoredSize, StoredTime);
2003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002004
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 bool IsOutOfDate = false;
2006
2007 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002008 if (!Overridden && //
2009 (StoredSize != File->getSize() ||
2010#if defined(LLVM_ON_WIN32)
2011 false
2012#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 // In our regression testing, the Windows file system seems to
2014 // have inconsistent modification times that sometimes
2015 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002016 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00002017 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
2018 (StoredTime && StoredTime != File->getModificationTime() &&
2019 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00002020#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002021 )) {
2022 if (Complain) {
2023 // Build a list of the PCH imports that got us here (in reverse).
2024 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2025 while (ImportStack.back()->ImportedBy.size() > 0)
2026 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002027
Ben Langmuir198c1682014-03-07 07:27:49 +00002028 // The top-level PCH is stale.
2029 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2030 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002031
Ben Langmuir198c1682014-03-07 07:27:49 +00002032 // Print the import stack.
2033 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2034 Diag(diag::note_pch_required_by)
2035 << Filename << ImportStack[0]->FileName;
2036 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002037 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002038 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002039 }
2040
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 if (!Diags.isDiagnosticInFlight())
2042 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 }
2044
Ben Langmuir198c1682014-03-07 07:27:49 +00002045 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002047 // FIXME: If the file is overridden and we've already opened it,
2048 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002049
Richard Smitha8cfffa2015-11-26 02:04:16 +00002050 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002051
2052 // Note that we've loaded this input file.
2053 F.InputFilesLoaded[ID-1] = IF;
2054 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002055}
2056
Richard Smith7ed1bc92014-12-05 22:42:13 +00002057/// \brief If we are loading a relocatable PCH or module file, and the filename
2058/// is not an absolute path, add the system or module root to the beginning of
2059/// the file name.
2060void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2061 // Resolve relative to the base directory, if we have one.
2062 if (!M.BaseDirectory.empty())
2063 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002064}
2065
Richard Smith7ed1bc92014-12-05 22:42:13 +00002066void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002067 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2068 return;
2069
Richard Smith7ed1bc92014-12-05 22:42:13 +00002070 SmallString<128> Buffer;
2071 llvm::sys::path::append(Buffer, Prefix, Filename);
2072 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002073}
2074
Richard Smith0f99d6a2015-08-09 08:48:41 +00002075static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2076 switch (ARR) {
2077 case ASTReader::Failure: return true;
2078 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2079 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2080 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2081 case ASTReader::ConfigurationMismatch:
2082 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2083 case ASTReader::HadErrors: return true;
2084 case ASTReader::Success: return false;
2085 }
2086
2087 llvm_unreachable("unknown ASTReadResult");
2088}
2089
Richard Smith0516b182015-09-08 19:40:14 +00002090ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2091 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2092 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2093 std::string &SuggestedPredefines) {
2094 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2095 return Failure;
2096
2097 // Read all of the records in the options block.
2098 RecordData Record;
2099 ASTReadResult Result = Success;
2100 while (1) {
2101 llvm::BitstreamEntry Entry = Stream.advance();
2102
2103 switch (Entry.Kind) {
2104 case llvm::BitstreamEntry::Error:
2105 case llvm::BitstreamEntry::SubBlock:
2106 return Failure;
2107
2108 case llvm::BitstreamEntry::EndBlock:
2109 return Result;
2110
2111 case llvm::BitstreamEntry::Record:
2112 // The interesting case.
2113 break;
2114 }
2115
2116 // Read and process a record.
2117 Record.clear();
2118 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2119 case LANGUAGE_OPTIONS: {
2120 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2121 if (ParseLanguageOptions(Record, Complain, Listener,
2122 AllowCompatibleConfigurationMismatch))
2123 Result = ConfigurationMismatch;
2124 break;
2125 }
2126
2127 case TARGET_OPTIONS: {
2128 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2129 if (ParseTargetOptions(Record, Complain, Listener,
2130 AllowCompatibleConfigurationMismatch))
2131 Result = ConfigurationMismatch;
2132 break;
2133 }
2134
2135 case DIAGNOSTIC_OPTIONS: {
2136 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2137 if (!AllowCompatibleConfigurationMismatch &&
2138 ParseDiagnosticOptions(Record, Complain, Listener))
2139 return OutOfDate;
2140 break;
2141 }
2142
2143 case FILE_SYSTEM_OPTIONS: {
2144 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2145 if (!AllowCompatibleConfigurationMismatch &&
2146 ParseFileSystemOptions(Record, Complain, Listener))
2147 Result = ConfigurationMismatch;
2148 break;
2149 }
2150
2151 case HEADER_SEARCH_OPTIONS: {
2152 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2153 if (!AllowCompatibleConfigurationMismatch &&
2154 ParseHeaderSearchOptions(Record, Complain, Listener))
2155 Result = ConfigurationMismatch;
2156 break;
2157 }
2158
2159 case PREPROCESSOR_OPTIONS:
2160 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2161 if (!AllowCompatibleConfigurationMismatch &&
2162 ParsePreprocessorOptions(Record, Complain, Listener,
2163 SuggestedPredefines))
2164 Result = ConfigurationMismatch;
2165 break;
2166 }
2167 }
2168}
2169
Guy Benyei11169dd2012-12-18 14:30:41 +00002170ASTReader::ASTReadResult
2171ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002172 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002173 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002175 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002176 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002177
2178 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2179 Error("malformed block record in AST file");
2180 return Failure;
2181 }
2182
2183 // Read all of the records and blocks in the control block.
2184 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002185 unsigned NumInputs = 0;
2186 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002187 while (1) {
2188 llvm::BitstreamEntry Entry = Stream.advance();
2189
2190 switch (Entry.Kind) {
2191 case llvm::BitstreamEntry::Error:
2192 Error("malformed block record in AST file");
2193 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002194 case llvm::BitstreamEntry::EndBlock: {
2195 // Validate input files.
2196 const HeaderSearchOptions &HSOpts =
2197 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002198
Richard Smitha1825302014-10-23 22:18:29 +00002199 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002200 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2201 // loaded module files, ignore missing inputs.
2202 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002203 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002204
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002205 // If we are reading a module, we will create a verification timestamp,
2206 // so we verify all input files. Otherwise, verify only user input
2207 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002208
2209 unsigned N = NumUserInputs;
2210 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002211 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002212 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002213 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002214 N = NumInputs;
2215
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002216 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002217 InputFile IF = getInputFile(F, I+1, Complain);
2218 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002222
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002223 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002224 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002225
Ben Langmuircb69b572014-03-07 06:40:32 +00002226 if (Listener && Listener->needsInputFileVisitation()) {
2227 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2228 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002229 for (unsigned I = 0; I < N; ++I) {
2230 bool IsSystem = I >= NumUserInputs;
2231 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002232 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2233 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002234 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002235 }
2236
Richard Smith8a308ec2015-11-05 00:54:55 +00002237 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002238 }
2239
Chris Lattnere7b154b2013-01-19 21:39:22 +00002240 case llvm::BitstreamEntry::SubBlock:
2241 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 case INPUT_FILES_BLOCK_ID:
2243 F.InputFilesCursor = Stream;
2244 if (Stream.SkipBlock() || // Skip with the main cursor
2245 // Read the abbreviations
2246 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2247 Error("malformed block record in AST file");
2248 return Failure;
2249 }
2250 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002251
2252 case OPTIONS_BLOCK_ID:
2253 // If we're reading the first module for this group, check its options
2254 // are compatible with ours. For modules it imports, no further checking
2255 // is required, because we checked them when we built it.
2256 if (Listener && !ImportedBy) {
2257 // Should we allow the configuration of the module file to differ from
2258 // the configuration of the current translation unit in a compatible
2259 // way?
2260 //
2261 // FIXME: Allow this for files explicitly specified with -include-pch.
2262 bool AllowCompatibleConfigurationMismatch =
2263 F.Kind == MK_ExplicitModule;
2264
Richard Smith8a308ec2015-11-05 00:54:55 +00002265 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2266 AllowCompatibleConfigurationMismatch,
2267 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002268 if (Result == Failure) {
2269 Error("malformed block record in AST file");
2270 return Result;
2271 }
2272
Richard Smith8a308ec2015-11-05 00:54:55 +00002273 if (DisableValidation ||
2274 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2275 Result = Success;
2276
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002277 // If we can't load the module, exit early since we likely
2278 // will rebuild the module anyway. The stream may be in the
2279 // middle of a block.
2280 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002281 return Result;
2282 } else if (Stream.SkipBlock()) {
2283 Error("malformed block record in AST file");
2284 return Failure;
2285 }
2286 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002287
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002289 if (Stream.SkipBlock()) {
2290 Error("malformed block record in AST file");
2291 return Failure;
2292 }
2293 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002295
2296 case llvm::BitstreamEntry::Record:
2297 // The interesting case.
2298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 }
2300
2301 // Read and process a record.
2302 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002303 StringRef Blob;
2304 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 case METADATA: {
2306 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2307 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002308 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2309 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 return VersionMismatch;
2311 }
2312
Richard Smithe75ee0f2015-08-17 07:13:32 +00002313 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2315 Diag(diag::err_pch_with_compiler_errors);
2316 return HadErrors;
2317 }
2318
2319 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002320 // Relative paths in a relocatable PCH are relative to our sysroot.
2321 if (F.RelocatablePCH)
2322 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323
Richard Smithe75ee0f2015-08-17 07:13:32 +00002324 F.HasTimestamps = Record[5];
2325
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002327 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2329 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002330 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 return VersionMismatch;
2332 }
2333 break;
2334 }
2335
Ben Langmuir487ea142014-10-23 18:05:36 +00002336 case SIGNATURE:
2337 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2338 F.Signature = Record[0];
2339 break;
2340
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 case IMPORTS: {
2342 // Load each of the imported PCH files.
2343 unsigned Idx = 0, N = Record.size();
2344 while (Idx < N) {
2345 // Read information about the AST file.
2346 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2347 // The import location will be the local one for now; we will adjust
2348 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002349 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002351 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002352 off_t StoredSize = (off_t)Record[Idx++];
2353 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002354 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002355 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002356
Richard Smith0f99d6a2015-08-09 08:48:41 +00002357 // If our client can't cope with us being out of date, we can't cope with
2358 // our dependency being missing.
2359 unsigned Capabilities = ClientLoadCapabilities;
2360 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2361 Capabilities &= ~ARR_Missing;
2362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002364 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2365 Loaded, StoredSize, StoredModTime,
2366 StoredSignature, Capabilities);
2367
2368 // If we diagnosed a problem, produce a backtrace.
2369 if (isDiagnosedResult(Result, Capabilities))
2370 Diag(diag::note_module_file_imported_by)
2371 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2372
2373 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 case Failure: return Failure;
2375 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002376 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 case OutOfDate: return OutOfDate;
2378 case VersionMismatch: return VersionMismatch;
2379 case ConfigurationMismatch: return ConfigurationMismatch;
2380 case HadErrors: return HadErrors;
2381 case Success: break;
2382 }
2383 }
2384 break;
2385 }
2386
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 case ORIGINAL_FILE:
2388 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002389 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002391 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 break;
2393
2394 case ORIGINAL_FILE_ID:
2395 F.OriginalSourceFileID = FileID::get(Record[0]);
2396 break;
2397
2398 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002399 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 break;
2401
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002402 case MODULE_NAME:
2403 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002404 if (Listener)
2405 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002406 break;
2407
Richard Smith223d3f22014-12-06 03:21:08 +00002408 case MODULE_DIRECTORY: {
2409 assert(!F.ModuleName.empty() &&
2410 "MODULE_DIRECTORY found before MODULE_NAME");
2411 // If we've already loaded a module map file covering this module, we may
2412 // have a better path for it (relative to the current build).
2413 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2414 if (M && M->Directory) {
2415 // If we're implicitly loading a module, the base directory can't
2416 // change between the build and use.
2417 if (F.Kind != MK_ExplicitModule) {
2418 const DirectoryEntry *BuildDir =
2419 PP.getFileManager().getDirectory(Blob);
2420 if (!BuildDir || BuildDir != M->Directory) {
2421 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2422 Diag(diag::err_imported_module_relocated)
2423 << F.ModuleName << Blob << M->Directory->getName();
2424 return OutOfDate;
2425 }
2426 }
2427 F.BaseDirectory = M->Directory->getName();
2428 } else {
2429 F.BaseDirectory = Blob;
2430 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002431 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002432 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002433
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002434 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002435 if (ASTReadResult Result =
2436 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2437 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002438 break;
2439
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002440 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002441 NumInputs = Record[0];
2442 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002443 F.InputFileOffsets =
2444 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002445 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 break;
2447 }
2448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002449}
2450
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451ASTReader::ASTReadResult
2452ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002453 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454
2455 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2456 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002457 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 }
2459
2460 // Read all of the records and blocks for the AST file.
2461 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002462 while (1) {
2463 llvm::BitstreamEntry Entry = Stream.advance();
2464
2465 switch (Entry.Kind) {
2466 case llvm::BitstreamEntry::Error:
2467 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002468 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002469 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002470 // Outside of C++, we do not store a lookup map for the translation unit.
2471 // Instead, mark it as needing a lookup map to be built if this module
2472 // contains any declarations lexically within it (which it always does!).
2473 // This usually has no cost, since we very rarely need the lookup map for
2474 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002476 if (DC->hasExternalLexicalStorage() &&
2477 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002479
Ben Langmuir2c9af442014-04-10 17:57:43 +00002480 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002482 case llvm::BitstreamEntry::SubBlock:
2483 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 case DECLTYPES_BLOCK_ID:
2485 // We lazily load the decls block, but we want to set up the
2486 // DeclsCursor cursor to point into it. Clone our current bitcode
2487 // cursor to it, enter the block and read the abbrevs in that block.
2488 // With the main cursor, we just skip over it.
2489 F.DeclsCursor = Stream;
2490 if (Stream.SkipBlock() || // Skip with the main cursor.
2491 // Read the abbrevs.
2492 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2493 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 }
2496 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002497
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 case PREPROCESSOR_BLOCK_ID:
2499 F.MacroCursor = Stream;
2500 if (!PP.getExternalSource())
2501 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002502
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 if (Stream.SkipBlock() ||
2504 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2505 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002506 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 }
2508 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2509 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002510
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 case PREPROCESSOR_DETAIL_BLOCK_ID:
2512 F.PreprocessorDetailCursor = Stream;
2513 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002516 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002517 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002518 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002520 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2521
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 if (!PP.getPreprocessingRecord())
2523 PP.createPreprocessingRecord();
2524 if (!PP.getPreprocessingRecord()->getExternalSource())
2525 PP.getPreprocessingRecord()->SetExternalSource(*this);
2526 break;
2527
2528 case SOURCE_MANAGER_BLOCK_ID:
2529 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002530 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002532
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002534 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2535 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002537
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002539 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 if (Stream.SkipBlock() ||
2541 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2542 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002543 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 }
2545 CommentsCursors.push_back(std::make_pair(C, &F));
2546 break;
2547 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002548
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002550 if (Stream.SkipBlock()) {
2551 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002552 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 }
2554 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 }
2556 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002557
2558 case llvm::BitstreamEntry::Record:
2559 // The interesting case.
2560 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
2562
2563 // Read and process a record.
2564 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002565 StringRef Blob;
2566 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 default: // Default behavior: ignore.
2568 break;
2569
2570 case TYPE_OFFSET: {
2571 if (F.LocalNumTypes != 0) {
2572 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002575 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 F.LocalNumTypes = Record[0];
2577 unsigned LocalBaseTypeIndex = Record[1];
2578 F.BaseTypeIndex = getTotalNumTypes();
2579
2580 if (F.LocalNumTypes > 0) {
2581 // Introduce the global -> local mapping for types within this module.
2582 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2583
2584 // Introduce the local -> global mapping for types within this module.
2585 F.TypeRemap.insertOrReplace(
2586 std::make_pair(LocalBaseTypeIndex,
2587 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002588
2589 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 }
2591 break;
2592 }
2593
2594 case DECL_OFFSET: {
2595 if (F.LocalNumDecls != 0) {
2596 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002599 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 F.LocalNumDecls = Record[0];
2601 unsigned LocalBaseDeclID = Record[1];
2602 F.BaseDeclID = getTotalNumDecls();
2603
2604 if (F.LocalNumDecls > 0) {
2605 // Introduce the global -> local mapping for declarations within this
2606 // module.
2607 GlobalDeclMap.insert(
2608 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2609
2610 // Introduce the local -> global mapping for declarations within this
2611 // module.
2612 F.DeclRemap.insertOrReplace(
2613 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2614
2615 // Introduce the global -> local mapping for declarations within this
2616 // module.
2617 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002618
Ben Langmuir52ca6782014-10-20 16:27:32 +00002619 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
2622 }
2623
2624 case TU_UPDATE_LEXICAL: {
2625 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002626 LexicalContents Contents(
2627 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2628 Blob.data()),
2629 static_cast<unsigned int>(Blob.size() / 4));
2630 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 TU->setHasExternalLexicalStorage(true);
2632 break;
2633 }
2634
2635 case UPDATE_VISIBLE: {
2636 unsigned Idx = 0;
2637 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002638 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002639 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002640 // If we've already loaded the decl, perform the updates when we finish
2641 // loading this block.
2642 if (Decl *D = GetExistingDecl(ID))
2643 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 break;
2645 }
2646
2647 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002648 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002650 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2651 (const unsigned char *)F.IdentifierTableData + Record[0],
2652 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2653 (const unsigned char *)F.IdentifierTableData,
2654 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002655
2656 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2657 }
2658 break;
2659
2660 case IDENTIFIER_OFFSET: {
2661 if (F.LocalNumIdentifiers != 0) {
2662 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002665 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 F.LocalNumIdentifiers = Record[0];
2667 unsigned LocalBaseIdentifierID = Record[1];
2668 F.BaseIdentifierID = getTotalNumIdentifiers();
2669
2670 if (F.LocalNumIdentifiers > 0) {
2671 // Introduce the global -> local mapping for identifiers within this
2672 // module.
2673 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2674 &F));
2675
2676 // Introduce the local -> global mapping for identifiers within this
2677 // module.
2678 F.IdentifierRemap.insertOrReplace(
2679 std::make_pair(LocalBaseIdentifierID,
2680 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002681
Ben Langmuir52ca6782014-10-20 16:27:32 +00002682 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2683 + F.LocalNumIdentifiers);
2684 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 break;
2686 }
2687
Richard Smith33e0f7e2015-07-22 02:08:40 +00002688 case INTERESTING_IDENTIFIERS:
2689 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2690 break;
2691
Ben Langmuir332aafe2014-01-31 01:06:56 +00002692 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002693 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2694 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002696 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 break;
2698
2699 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002700 if (SpecialTypes.empty()) {
2701 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2702 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2703 break;
2704 }
2705
2706 if (SpecialTypes.size() != Record.size()) {
2707 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002708 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002709 }
2710
2711 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2712 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2713 if (!SpecialTypes[I])
2714 SpecialTypes[I] = ID;
2715 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2716 // merge step?
2717 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 break;
2719
2720 case STATISTICS:
2721 TotalNumStatements += Record[0];
2722 TotalNumMacros += Record[1];
2723 TotalLexicalDeclContexts += Record[2];
2724 TotalVisibleDeclContexts += Record[3];
2725 break;
2726
2727 case UNUSED_FILESCOPED_DECLS:
2728 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2729 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2730 break;
2731
2732 case DELEGATING_CTORS:
2733 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2734 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2735 break;
2736
2737 case WEAK_UNDECLARED_IDENTIFIERS:
2738 if (Record.size() % 4 != 0) {
2739 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002740 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 }
2742
2743 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2744 // files. This isn't the way to do it :)
2745 WeakUndeclaredIdentifiers.clear();
2746
2747 // Translate the weak, undeclared identifiers into global IDs.
2748 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2749 WeakUndeclaredIdentifiers.push_back(
2750 getGlobalIdentifierID(F, Record[I++]));
2751 WeakUndeclaredIdentifiers.push_back(
2752 getGlobalIdentifierID(F, Record[I++]));
2753 WeakUndeclaredIdentifiers.push_back(
2754 ReadSourceLocation(F, Record, I).getRawEncoding());
2755 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2756 }
2757 break;
2758
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002760 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 F.LocalNumSelectors = Record[0];
2762 unsigned LocalBaseSelectorID = Record[1];
2763 F.BaseSelectorID = getTotalNumSelectors();
2764
2765 if (F.LocalNumSelectors > 0) {
2766 // Introduce the global -> local mapping for selectors within this
2767 // module.
2768 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2769
2770 // Introduce the local -> global mapping for selectors within this
2771 // module.
2772 F.SelectorRemap.insertOrReplace(
2773 std::make_pair(LocalBaseSelectorID,
2774 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002775
2776 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 }
2778 break;
2779 }
2780
2781 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002782 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 if (Record[0])
2784 F.SelectorLookupTable
2785 = ASTSelectorLookupTable::Create(
2786 F.SelectorLookupTableData + Record[0],
2787 F.SelectorLookupTableData,
2788 ASTSelectorLookupTrait(*this, F));
2789 TotalNumMethodPoolEntries += Record[1];
2790 break;
2791
2792 case REFERENCED_SELECTOR_POOL:
2793 if (!Record.empty()) {
2794 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2795 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2796 Record[Idx++]));
2797 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2798 getRawEncoding());
2799 }
2800 }
2801 break;
2802
2803 case PP_COUNTER_VALUE:
2804 if (!Record.empty() && Listener)
2805 Listener->ReadCounter(F, Record[0]);
2806 break;
2807
2808 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002809 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 F.NumFileSortedDecls = Record[0];
2811 break;
2812
2813 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002814 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 F.LocalNumSLocEntries = Record[0];
2816 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002817 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002818 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002820 if (!F.SLocEntryBaseID) {
2821 Error("ran out of source locations");
2822 break;
2823 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 // Make our entry in the range map. BaseID is negative and growing, so
2825 // we invert it. Because we invert it, though, we need the other end of
2826 // the range.
2827 unsigned RangeStart =
2828 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2829 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2830 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2831
2832 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2833 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2834 GlobalSLocOffsetMap.insert(
2835 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2836 - SLocSpaceSize,&F));
2837
2838 // Initialize the remapping table.
2839 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002840 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002842 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2844
2845 TotalNumSLocEntries += F.LocalNumSLocEntries;
2846 break;
2847 }
2848
2849 case MODULE_OFFSET_MAP: {
2850 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002851 const unsigned char *Data = (const unsigned char*)Blob.data();
2852 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002853
2854 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2855 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2856 F.SLocRemap.insert(std::make_pair(0U, 0));
2857 F.SLocRemap.insert(std::make_pair(2U, 1));
2858 }
2859
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002861 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2862 RemapBuilder;
2863 RemapBuilder SLocRemap(F.SLocRemap);
2864 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2865 RemapBuilder MacroRemap(F.MacroRemap);
2866 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2867 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2868 RemapBuilder SelectorRemap(F.SelectorRemap);
2869 RemapBuilder DeclRemap(F.DeclRemap);
2870 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871
Richard Smithd8879c82015-08-24 21:59:32 +00002872 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002873 using namespace llvm::support;
2874 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 StringRef Name = StringRef((const char*)Data, Len);
2876 Data += Len;
2877 ModuleFile *OM = ModuleMgr.lookup(Name);
2878 if (!OM) {
2879 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002880 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 }
2882
Justin Bogner57ba0b22014-03-28 22:03:24 +00002883 uint32_t SLocOffset =
2884 endian::readNext<uint32_t, little, unaligned>(Data);
2885 uint32_t IdentifierIDOffset =
2886 endian::readNext<uint32_t, little, unaligned>(Data);
2887 uint32_t MacroIDOffset =
2888 endian::readNext<uint32_t, little, unaligned>(Data);
2889 uint32_t PreprocessedEntityIDOffset =
2890 endian::readNext<uint32_t, little, unaligned>(Data);
2891 uint32_t SubmoduleIDOffset =
2892 endian::readNext<uint32_t, little, unaligned>(Data);
2893 uint32_t SelectorIDOffset =
2894 endian::readNext<uint32_t, little, unaligned>(Data);
2895 uint32_t DeclIDOffset =
2896 endian::readNext<uint32_t, little, unaligned>(Data);
2897 uint32_t TypeIndexOffset =
2898 endian::readNext<uint32_t, little, unaligned>(Data);
2899
Ben Langmuir785180e2014-10-20 16:27:30 +00002900 uint32_t None = std::numeric_limits<uint32_t>::max();
2901
2902 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2903 RemapBuilder &Remap) {
2904 if (Offset != None)
2905 Remap.insert(std::make_pair(Offset,
2906 static_cast<int>(BaseOffset - Offset)));
2907 };
2908 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2909 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2910 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2911 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2912 PreprocessedEntityRemap);
2913 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2914 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2915 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2916 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917
2918 // Global -> local mappings.
2919 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2920 }
2921 break;
2922 }
2923
2924 case SOURCE_MANAGER_LINE_TABLE:
2925 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002926 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 break;
2928
2929 case SOURCE_LOCATION_PRELOADS: {
2930 // Need to transform from the local view (1-based IDs) to the global view,
2931 // which is based off F.SLocEntryBaseID.
2932 if (!F.PreloadSLocEntries.empty()) {
2933 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002934 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 }
2936
2937 F.PreloadSLocEntries.swap(Record);
2938 break;
2939 }
2940
2941 case EXT_VECTOR_DECLS:
2942 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2943 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2944 break;
2945
2946 case VTABLE_USES:
2947 if (Record.size() % 3 != 0) {
2948 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002949 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 }
2951
2952 // Later tables overwrite earlier ones.
2953 // FIXME: Modules will have some trouble with this. This is clearly not
2954 // the right way to do this.
2955 VTableUses.clear();
2956
2957 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2958 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2959 VTableUses.push_back(
2960 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2961 VTableUses.push_back(Record[Idx++]);
2962 }
2963 break;
2964
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 case PENDING_IMPLICIT_INSTANTIATIONS:
2966 if (PendingInstantiations.size() % 2 != 0) {
2967 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002968 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 }
2970
2971 if (Record.size() % 2 != 0) {
2972 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002973 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 }
2975
2976 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2977 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2978 PendingInstantiations.push_back(
2979 ReadSourceLocation(F, Record, I).getRawEncoding());
2980 }
2981 break;
2982
2983 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002984 if (Record.size() != 2) {
2985 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2989 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2990 break;
2991
2992 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002993 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2994 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2995 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002996
2997 unsigned LocalBasePreprocessedEntityID = Record[0];
2998
2999 unsigned StartingID;
3000 if (!PP.getPreprocessingRecord())
3001 PP.createPreprocessingRecord();
3002 if (!PP.getPreprocessingRecord()->getExternalSource())
3003 PP.getPreprocessingRecord()->SetExternalSource(*this);
3004 StartingID
3005 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003006 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 F.BasePreprocessedEntityID = StartingID;
3008
3009 if (F.NumPreprocessedEntities > 0) {
3010 // Introduce the global -> local mapping for preprocessed entities in
3011 // this module.
3012 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3013
3014 // Introduce the local -> global mapping for preprocessed entities in
3015 // this module.
3016 F.PreprocessedEntityRemap.insertOrReplace(
3017 std::make_pair(LocalBasePreprocessedEntityID,
3018 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3019 }
3020
3021 break;
3022 }
3023
3024 case DECL_UPDATE_OFFSETS: {
3025 if (Record.size() % 2 != 0) {
3026 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003029 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3030 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3031 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3032
3033 // If we've already loaded the decl, perform the updates when we finish
3034 // loading this block.
3035 if (Decl *D = GetExistingDecl(ID))
3036 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 break;
3039 }
3040
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 case OBJC_CATEGORIES_MAP: {
3042 if (F.LocalNumObjCCategoriesInMap != 0) {
3043 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003044 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 }
3046
3047 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003048 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 break;
3050 }
3051
3052 case OBJC_CATEGORIES:
3053 F.ObjCCategories.swap(Record);
3054 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003055
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 case CXX_BASE_SPECIFIER_OFFSETS: {
3057 if (F.LocalNumCXXBaseSpecifiers != 0) {
3058 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003059 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003061
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003063 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003064 break;
3065 }
3066
3067 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3068 if (F.LocalNumCXXCtorInitializers != 0) {
3069 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3070 return Failure;
3071 }
3072
3073 F.LocalNumCXXCtorInitializers = Record[0];
3074 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 break;
3076 }
3077
3078 case DIAG_PRAGMA_MAPPINGS:
3079 if (F.PragmaDiagMappings.empty())
3080 F.PragmaDiagMappings.swap(Record);
3081 else
3082 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3083 Record.begin(), Record.end());
3084 break;
3085
3086 case CUDA_SPECIAL_DECL_REFS:
3087 // Later tables overwrite earlier ones.
3088 // FIXME: Modules will have trouble with this.
3089 CUDASpecialDeclRefs.clear();
3090 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3091 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3092 break;
3093
3094 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003095 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 if (Record[0]) {
3098 F.HeaderFileInfoTable
3099 = HeaderFileInfoLookupTable::Create(
3100 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3101 (const unsigned char *)F.HeaderFileInfoTableData,
3102 HeaderFileInfoTrait(*this, F,
3103 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003104 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003105
3106 PP.getHeaderSearchInfo().SetExternalSource(this);
3107 if (!PP.getHeaderSearchInfo().getExternalLookup())
3108 PP.getHeaderSearchInfo().SetExternalLookup(this);
3109 }
3110 break;
3111 }
3112
3113 case FP_PRAGMA_OPTIONS:
3114 // Later tables overwrite earlier ones.
3115 FPPragmaOptions.swap(Record);
3116 break;
3117
3118 case OPENCL_EXTENSIONS:
3119 // Later tables overwrite earlier ones.
3120 OpenCLExtensions.swap(Record);
3121 break;
3122
3123 case TENTATIVE_DEFINITIONS:
3124 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3125 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3126 break;
3127
3128 case KNOWN_NAMESPACES:
3129 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3130 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3131 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003132
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003133 case UNDEFINED_BUT_USED:
3134 if (UndefinedButUsed.size() % 2 != 0) {
3135 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003136 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003137 }
3138
3139 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003140 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003141 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003142 }
3143 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003144 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3145 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003146 ReadSourceLocation(F, Record, I).getRawEncoding());
3147 }
3148 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003149 case DELETE_EXPRS_TO_ANALYZE:
3150 for (unsigned I = 0, N = Record.size(); I != N;) {
3151 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3152 const uint64_t Count = Record[I++];
3153 DelayedDeleteExprs.push_back(Count);
3154 for (uint64_t C = 0; C < Count; ++C) {
3155 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3156 bool IsArrayForm = Record[I++] == 1;
3157 DelayedDeleteExprs.push_back(IsArrayForm);
3158 }
3159 }
3160 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003163 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 // If we aren't loading a module (which has its own exports), make
3165 // all of the imported modules visible.
3166 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003167 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3168 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3169 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3170 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003171 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 }
3173 }
3174 break;
3175 }
3176
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 case MACRO_OFFSET: {
3178 if (F.LocalNumMacros != 0) {
3179 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003180 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003182 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 F.LocalNumMacros = Record[0];
3184 unsigned LocalBaseMacroID = Record[1];
3185 F.BaseMacroID = getTotalNumMacros();
3186
3187 if (F.LocalNumMacros > 0) {
3188 // Introduce the global -> local mapping for macros within this module.
3189 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3190
3191 // Introduce the local -> global mapping for macros within this module.
3192 F.MacroRemap.insertOrReplace(
3193 std::make_pair(LocalBaseMacroID,
3194 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003195
3196 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 }
3198 break;
3199 }
3200
Richard Smithe40f2ba2013-08-07 21:41:30 +00003201 case LATE_PARSED_TEMPLATE: {
3202 LateParsedTemplates.append(Record.begin(), Record.end());
3203 break;
3204 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003205
3206 case OPTIMIZE_PRAGMA_OPTIONS:
3207 if (Record.size() != 1) {
3208 Error("invalid pragma optimize record");
3209 return Failure;
3210 }
3211 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3212 break;
Nico Weber72889432014-09-06 01:25:55 +00003213
Nico Weber779355f2016-03-02 23:22:00 +00003214 case MSSTRUCT_PRAGMA_OPTIONS:
3215 if (Record.size() != 1) {
3216 Error("invalid pragma ms_struct record");
3217 return Failure;
3218 }
3219 PragmaMSStructState = Record[0];
3220 break;
3221
Nico Weber42932312016-03-03 00:17:35 +00003222 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3223 if (Record.size() != 2) {
3224 Error("invalid pragma ms_struct record");
3225 return Failure;
3226 }
3227 PragmaMSPointersToMembersState = Record[0];
3228 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3229 break;
3230
Nico Weber72889432014-09-06 01:25:55 +00003231 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3232 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3233 UnusedLocalTypedefNameCandidates.push_back(
3234 getGlobalDeclID(F, Record[I]));
3235 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 }
3237 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003238}
3239
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003240ASTReader::ASTReadResult
3241ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3242 const ModuleFile *ImportedBy,
3243 unsigned ClientLoadCapabilities) {
3244 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003245 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003246
Richard Smithe842a472014-10-22 02:05:46 +00003247 if (F.Kind == MK_ExplicitModule) {
3248 // For an explicitly-loaded module, we don't care whether the original
3249 // module map file exists or matches.
3250 return Success;
3251 }
3252
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003253 // Try to resolve ModuleName in the current header search context and
3254 // verify that it is found in the same module map file as we saved. If the
3255 // top-level AST file is a main file, skip this check because there is no
3256 // usable header search context.
3257 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003258 "MODULE_NAME should come before MODULE_MAP_FILE");
3259 if (F.Kind == MK_ImplicitModule &&
3260 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3261 // An implicitly-loaded module file should have its module listed in some
3262 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003263 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003264 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3265 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3266 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003267 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003268 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3269 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3270 // This module was defined by an imported (explicit) module.
3271 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3272 << ASTFE->getName();
3273 else
3274 // This module was built with a different module map.
3275 Diag(diag::err_imported_module_not_found)
3276 << F.ModuleName << F.FileName << ImportedBy->FileName
3277 << F.ModuleMapPath;
3278 }
3279 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003280 }
3281
Richard Smithe842a472014-10-22 02:05:46 +00003282 assert(M->Name == F.ModuleName && "found module with different name");
3283
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003284 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003285 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003286 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3287 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003288 assert(ImportedBy && "top-level import should be verified");
3289 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3290 Diag(diag::err_imported_module_modmap_changed)
3291 << F.ModuleName << ImportedBy->FileName
3292 << ModMap->getName() << F.ModuleMapPath;
3293 return OutOfDate;
3294 }
3295
3296 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3297 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3298 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003299 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003300 const FileEntry *F =
3301 FileMgr.getFile(Filename, false, false);
3302 if (F == nullptr) {
3303 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3304 Error("could not find file '" + Filename +"' referenced by AST file");
3305 return OutOfDate;
3306 }
3307 AdditionalStoredMaps.insert(F);
3308 }
3309
3310 // Check any additional module map files (e.g. module.private.modulemap)
3311 // that are not in the pcm.
3312 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3313 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3314 // Remove files that match
3315 // Note: SmallPtrSet::erase is really remove
3316 if (!AdditionalStoredMaps.erase(ModMap)) {
3317 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3318 Diag(diag::err_module_different_modmap)
3319 << F.ModuleName << /*new*/0 << ModMap->getName();
3320 return OutOfDate;
3321 }
3322 }
3323 }
3324
3325 // Check any additional module map files that are in the pcm, but not
3326 // found in header search. Cases that match are already removed.
3327 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3328 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3329 Diag(diag::err_module_different_modmap)
3330 << F.ModuleName << /*not new*/1 << ModMap->getName();
3331 return OutOfDate;
3332 }
3333 }
3334
3335 if (Listener)
3336 Listener->ReadModuleMapFile(F.ModuleMapPath);
3337 return Success;
3338}
3339
3340
Douglas Gregorc1489562013-02-12 23:36:21 +00003341/// \brief Move the given method to the back of the global list of methods.
3342static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3343 // Find the entry for this selector in the method pool.
3344 Sema::GlobalMethodPool::iterator Known
3345 = S.MethodPool.find(Method->getSelector());
3346 if (Known == S.MethodPool.end())
3347 return;
3348
3349 // Retrieve the appropriate method list.
3350 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3351 : Known->second.second;
3352 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003353 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003354 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003355 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003356 Found = true;
3357 } else {
3358 // Keep searching.
3359 continue;
3360 }
3361 }
3362
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003363 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003364 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003365 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003366 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003367 }
3368}
3369
Richard Smithde711422015-04-23 21:20:19 +00003370void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003371 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003372 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003373 bool wasHidden = D->Hidden;
3374 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003375
Richard Smith49f906a2014-03-01 00:08:04 +00003376 if (wasHidden && SemaObj) {
3377 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3378 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003379 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 }
3381 }
3382}
3383
Richard Smith49f906a2014-03-01 00:08:04 +00003384void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003385 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003386 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003388 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003389 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003391 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003392
3393 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003394 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 // there is nothing more to do.
3396 continue;
3397 }
Richard Smith49f906a2014-03-01 00:08:04 +00003398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 if (!Mod->isAvailable()) {
3400 // Modules that aren't available cannot be made visible.
3401 continue;
3402 }
3403
3404 // Update the module's name visibility.
3405 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003406
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 // If we've already deserialized any names from this module,
3408 // mark them as visible.
3409 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3410 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003411 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003412 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003413 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003414 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3415 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003416 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003417
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003419 SmallVector<Module *, 16> Exports;
3420 Mod->getExportedModules(Exports);
3421 for (SmallVectorImpl<Module *>::iterator
3422 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3423 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003424 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003425 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 }
3427 }
3428}
3429
Douglas Gregore060e572013-01-25 01:03:03 +00003430bool ASTReader::loadGlobalIndex() {
3431 if (GlobalIndex)
3432 return false;
3433
3434 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3435 !Context.getLangOpts().Modules)
3436 return true;
3437
3438 // Try to load the global index.
3439 TriedLoadingGlobalIndex = true;
3440 StringRef ModuleCachePath
3441 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3442 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003443 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003444 if (!Result.first)
3445 return true;
3446
3447 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003448 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003449 return false;
3450}
3451
3452bool ASTReader::isGlobalIndexUnavailable() const {
3453 return Context.getLangOpts().Modules && UseGlobalIndex &&
3454 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3455}
3456
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003457static void updateModuleTimestamp(ModuleFile &MF) {
3458 // Overwrite the timestamp file contents so that file's mtime changes.
3459 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003460 std::error_code EC;
3461 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3462 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003463 return;
3464 OS << "Timestamp file\n";
3465}
3466
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003467/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3468/// cursor into the start of the given block ID, returning false on success and
3469/// true on failure.
3470static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3471 while (1) {
3472 llvm::BitstreamEntry Entry = Cursor.advance();
3473 switch (Entry.Kind) {
3474 case llvm::BitstreamEntry::Error:
3475 case llvm::BitstreamEntry::EndBlock:
3476 return true;
3477
3478 case llvm::BitstreamEntry::Record:
3479 // Ignore top-level records.
3480 Cursor.skipRecord(Entry.ID);
3481 break;
3482
3483 case llvm::BitstreamEntry::SubBlock:
3484 if (Entry.ID == BlockID) {
3485 if (Cursor.EnterSubBlock(BlockID))
3486 return true;
3487 // Found it!
3488 return false;
3489 }
3490
3491 if (Cursor.SkipBlock())
3492 return true;
3493 }
3494 }
3495}
3496
Benjamin Kramer0772c422016-02-13 13:42:54 +00003497ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 ModuleKind Type,
3499 SourceLocation ImportLoc,
3500 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003501 llvm::SaveAndRestore<SourceLocation>
3502 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3503
Richard Smithd1c46742014-04-30 02:24:17 +00003504 // Defer any pending actions until we get to the end of reading the AST file.
3505 Deserializing AnASTFile(this);
3506
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003508 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003509
3510 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003511 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003513 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003514 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 ClientLoadCapabilities)) {
3516 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003517 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 case OutOfDate:
3519 case VersionMismatch:
3520 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003521 case HadErrors: {
3522 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3523 for (const ImportedModule &IM : Loaded)
3524 LoadedSet.insert(IM.Mod);
3525
Douglas Gregor7029ce12013-03-19 00:28:20 +00003526 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003527 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003528 Context.getLangOpts().Modules
3529 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003530 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003531
3532 // If we find that any modules are unusable, the global index is going
3533 // to be out-of-date. Just remove it.
3534 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003535 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003537 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 case Success:
3539 break;
3540 }
3541
3542 // Here comes stuff that we only do once the entire chain is loaded.
3543
3544 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003545 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3546 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 M != MEnd; ++M) {
3548 ModuleFile &F = *M->Mod;
3549
3550 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003551 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3552 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003553
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003554 // Read the extension blocks.
3555 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3556 if (ASTReadResult Result = ReadExtensionBlock(F))
3557 return Result;
3558 }
3559
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 // Once read, set the ModuleFile bit base offset and update the size in
3561 // bits of all files we've seen.
3562 F.GlobalBitOffset = TotalModulesSizeInBits;
3563 TotalModulesSizeInBits += F.SizeInBits;
3564 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3565
3566 // Preload SLocEntries.
3567 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3568 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3569 // Load it through the SourceManager and don't call ReadSLocEntry()
3570 // directly because the entry may have already been loaded in which case
3571 // calling ReadSLocEntry() directly would trigger an assertion in
3572 // SourceManager.
3573 SourceMgr.getLoadedSLocEntryByID(Index);
3574 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003575
3576 // Preload all the pending interesting identifiers by marking them out of
3577 // date.
3578 for (auto Offset : F.PreloadIdentifierOffsets) {
3579 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3580 F.IdentifierTableData + Offset);
3581
3582 ASTIdentifierLookupTrait Trait(*this, F);
3583 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3584 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003585 auto &II = PP.getIdentifierTable().getOwn(Key);
3586 II.setOutOfDate(true);
3587
3588 // Mark this identifier as being from an AST file so that we can track
3589 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003590 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003591
3592 // Associate the ID with the identifier so that the writer can reuse it.
3593 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3594 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003595 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 }
3597
Douglas Gregor603cd862013-03-22 18:50:14 +00003598 // Setup the import locations and notify the module manager that we've
3599 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003600 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3601 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 M != MEnd; ++M) {
3603 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003604
3605 ModuleMgr.moduleFileAccepted(&F);
3606
3607 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003608 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003609 // FIXME: We assume that locations from PCH / preamble do not need
3610 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 if (!M->ImportedBy)
3612 F.ImportLoc = M->ImportLoc;
3613 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003614 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 }
3616
Richard Smith33e0f7e2015-07-22 02:08:40 +00003617 if (!Context.getLangOpts().CPlusPlus ||
3618 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3619 // Mark all of the identifiers in the identifier table as being out of date,
3620 // so that various accessors know to check the loaded modules when the
3621 // identifier is used.
3622 //
3623 // For C++ modules, we don't need information on many identifiers (just
3624 // those that provide macros or are poisoned), so we mark all of
3625 // the interesting ones via PreloadIdentifierOffsets.
3626 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3627 IdEnd = PP.getIdentifierTable().end();
3628 Id != IdEnd; ++Id)
3629 Id->second->setOutOfDate(true);
3630 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003631
3632 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003633 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3634 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3636 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003637
3638 switch (Unresolved.Kind) {
3639 case UnresolvedModuleRef::Conflict:
3640 if (ResolvedMod) {
3641 Module::Conflict Conflict;
3642 Conflict.Other = ResolvedMod;
3643 Conflict.Message = Unresolved.String.str();
3644 Unresolved.Mod->Conflicts.push_back(Conflict);
3645 }
3646 continue;
3647
3648 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003650 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003652
Douglas Gregorfb912652013-03-20 21:10:35 +00003653 case UnresolvedModuleRef::Export:
3654 if (ResolvedMod || Unresolved.IsWildcard)
3655 Unresolved.Mod->Exports.push_back(
3656 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3657 continue;
3658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003660 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003661
3662 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3663 // Might be unnecessary as use declarations are only used to build the
3664 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003665
3666 InitializeContext();
3667
Richard Smith3d8e97e2013-10-18 06:54:39 +00003668 if (SemaObj)
3669 UpdateSema();
3670
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 if (DeserializationListener)
3672 DeserializationListener->ReaderInitialized(this);
3673
3674 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003675 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 PrimaryModule.OriginalSourceFileID
3677 = FileID::get(PrimaryModule.SLocEntryBaseID
3678 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3679
3680 // If this AST file is a precompiled preamble, then set the
3681 // preamble file ID of the source manager to the file source file
3682 // from which the preamble was built.
3683 if (Type == MK_Preamble) {
3684 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3685 } else if (Type == MK_MainFile) {
3686 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3687 }
3688 }
3689
3690 // For any Objective-C class definitions we have already loaded, make sure
3691 // that we load any additional categories.
3692 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3693 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3694 ObjCClassesLoaded[I],
3695 PreviousGeneration);
3696 }
Douglas Gregore060e572013-01-25 01:03:03 +00003697
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003698 if (PP.getHeaderSearchInfo()
3699 .getHeaderSearchOpts()
3700 .ModulesValidateOncePerBuildSession) {
3701 // Now we are certain that the module and all modules it depends on are
3702 // up to date. Create or update timestamp files for modules that are
3703 // located in the module cache (not for PCH files that could be anywhere
3704 // in the filesystem).
3705 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3706 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003707 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003708 updateModuleTimestamp(*M.Mod);
3709 }
3710 }
3711 }
3712
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 return Success;
3714}
3715
Ben Langmuir487ea142014-10-23 18:05:36 +00003716static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3717
Ben Langmuir70a1b812015-03-24 04:43:52 +00003718/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3719static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3720 return Stream.Read(8) == 'C' &&
3721 Stream.Read(8) == 'P' &&
3722 Stream.Read(8) == 'C' &&
3723 Stream.Read(8) == 'H';
3724}
3725
Richard Smith0f99d6a2015-08-09 08:48:41 +00003726static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3727 switch (Kind) {
3728 case MK_PCH:
3729 return 0; // PCH
3730 case MK_ImplicitModule:
3731 case MK_ExplicitModule:
3732 return 1; // module
3733 case MK_MainFile:
3734 case MK_Preamble:
3735 return 2; // main source file
3736 }
3737 llvm_unreachable("unknown module kind");
3738}
3739
Guy Benyei11169dd2012-12-18 14:30:41 +00003740ASTReader::ASTReadResult
3741ASTReader::ReadASTCore(StringRef FileName,
3742 ModuleKind Type,
3743 SourceLocation ImportLoc,
3744 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003745 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003746 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003747 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 unsigned ClientLoadCapabilities) {
3749 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003750 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003751 ModuleManager::AddModuleResult AddResult
3752 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003753 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003754 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003755 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003756
Douglas Gregor7029ce12013-03-19 00:28:20 +00003757 switch (AddResult) {
3758 case ModuleManager::AlreadyLoaded:
3759 return Success;
3760
3761 case ModuleManager::NewlyLoaded:
3762 // Load module file below.
3763 break;
3764
3765 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003766 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003767 // it.
3768 if (ClientLoadCapabilities & ARR_Missing)
3769 return Missing;
3770
3771 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003772 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3773 << FileName << ErrorStr.empty()
3774 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003775 return Failure;
3776
3777 case ModuleManager::OutOfDate:
3778 // We couldn't load the module file because it is out-of-date. If the
3779 // client can handle out-of-date, return it.
3780 if (ClientLoadCapabilities & ARR_OutOfDate)
3781 return OutOfDate;
3782
3783 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003784 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3785 << FileName << ErrorStr.empty()
3786 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 return Failure;
3788 }
3789
Douglas Gregor7029ce12013-03-19 00:28:20 +00003790 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
3792 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3793 // module?
3794 if (FileName != "-") {
3795 CurrentDir = llvm::sys::path::parent_path(FileName);
3796 if (CurrentDir.empty()) CurrentDir = ".";
3797 }
3798
3799 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003800 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003801 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003802 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003803 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3804
Guy Benyei11169dd2012-12-18 14:30:41 +00003805 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003806 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003807 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3808 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 return Failure;
3810 }
3811
3812 // This is used for compatibility with older PCH formats.
3813 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003814 while (1) {
3815 llvm::BitstreamEntry Entry = Stream.advance();
3816
3817 switch (Entry.Kind) {
3818 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003819 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003820 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 Error("invalid record at top-level of AST file");
3822 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003823
3824 case llvm::BitstreamEntry::SubBlock:
3825 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 }
3827
Chris Lattnerefa77172013-01-20 00:00:22 +00003828 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 case CONTROL_BLOCK_ID:
3830 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003831 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003833 // Check that we didn't try to load a non-module AST file as a module.
3834 //
3835 // FIXME: Should we also perform the converse check? Loading a module as
3836 // a PCH file sort of works, but it's a bit wonky.
3837 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3838 F.ModuleName.empty()) {
3839 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3840 if (Result != OutOfDate ||
3841 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3842 Diag(diag::err_module_file_not_module) << FileName;
3843 return Result;
3844 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003845 break;
3846
3847 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003848 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 case OutOfDate: return OutOfDate;
3850 case VersionMismatch: return VersionMismatch;
3851 case ConfigurationMismatch: return ConfigurationMismatch;
3852 case HadErrors: return HadErrors;
3853 }
3854 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003855
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 case AST_BLOCK_ID:
3857 if (!HaveReadControlBlock) {
3858 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003859 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003860 return VersionMismatch;
3861 }
3862
3863 // Record that we've loaded this module.
3864 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3865 return Success;
3866
3867 default:
3868 if (Stream.SkipBlock()) {
3869 Error("malformed block record in AST file");
3870 return Failure;
3871 }
3872 break;
3873 }
3874 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003875
3876 return Success;
3877}
3878
3879/// Parse a record and blob containing module file extension metadata.
3880static bool parseModuleFileExtensionMetadata(
3881 const SmallVectorImpl<uint64_t> &Record,
3882 StringRef Blob,
3883 ModuleFileExtensionMetadata &Metadata) {
3884 if (Record.size() < 4) return true;
3885
3886 Metadata.MajorVersion = Record[0];
3887 Metadata.MinorVersion = Record[1];
3888
3889 unsigned BlockNameLen = Record[2];
3890 unsigned UserInfoLen = Record[3];
3891
3892 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3893
3894 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3895 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3896 Blob.data() + BlockNameLen + UserInfoLen);
3897 return false;
3898}
3899
3900ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3901 BitstreamCursor &Stream = F.Stream;
3902
3903 RecordData Record;
3904 while (true) {
3905 llvm::BitstreamEntry Entry = Stream.advance();
3906 switch (Entry.Kind) {
3907 case llvm::BitstreamEntry::SubBlock:
3908 if (Stream.SkipBlock())
3909 return Failure;
3910
3911 continue;
3912
3913 case llvm::BitstreamEntry::EndBlock:
3914 return Success;
3915
3916 case llvm::BitstreamEntry::Error:
3917 return HadErrors;
3918
3919 case llvm::BitstreamEntry::Record:
3920 break;
3921 }
3922
3923 Record.clear();
3924 StringRef Blob;
3925 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3926 switch (RecCode) {
3927 case EXTENSION_METADATA: {
3928 ModuleFileExtensionMetadata Metadata;
3929 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3930 return Failure;
3931
3932 // Find a module file extension with this block name.
3933 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3934 if (Known == ModuleFileExtensions.end()) break;
3935
3936 // Form a reader.
3937 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3938 F, Stream)) {
3939 F.ExtensionReaders.push_back(std::move(Reader));
3940 }
3941
3942 break;
3943 }
3944 }
3945 }
3946
3947 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003948}
3949
Richard Smitha7e2cc62015-05-01 01:53:09 +00003950void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 // If there's a listener, notify them that we "read" the translation unit.
3952 if (DeserializationListener)
3953 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3954 Context.getTranslationUnitDecl());
3955
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 // FIXME: Find a better way to deal with collisions between these
3957 // built-in types. Right now, we just ignore the problem.
3958
3959 // Load the special types.
3960 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3961 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3962 if (!Context.CFConstantStringTypeDecl)
3963 Context.setCFConstantStringType(GetType(String));
3964 }
3965
3966 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3967 QualType FileType = GetType(File);
3968 if (FileType.isNull()) {
3969 Error("FILE type is NULL");
3970 return;
3971 }
3972
3973 if (!Context.FILEDecl) {
3974 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3975 Context.setFILEDecl(Typedef->getDecl());
3976 else {
3977 const TagType *Tag = FileType->getAs<TagType>();
3978 if (!Tag) {
3979 Error("Invalid FILE type in AST file");
3980 return;
3981 }
3982 Context.setFILEDecl(Tag->getDecl());
3983 }
3984 }
3985 }
3986
3987 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3988 QualType Jmp_bufType = GetType(Jmp_buf);
3989 if (Jmp_bufType.isNull()) {
3990 Error("jmp_buf type is NULL");
3991 return;
3992 }
3993
3994 if (!Context.jmp_bufDecl) {
3995 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3996 Context.setjmp_bufDecl(Typedef->getDecl());
3997 else {
3998 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3999 if (!Tag) {
4000 Error("Invalid jmp_buf type in AST file");
4001 return;
4002 }
4003 Context.setjmp_bufDecl(Tag->getDecl());
4004 }
4005 }
4006 }
4007
4008 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4009 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4010 if (Sigjmp_bufType.isNull()) {
4011 Error("sigjmp_buf type is NULL");
4012 return;
4013 }
4014
4015 if (!Context.sigjmp_bufDecl) {
4016 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4017 Context.setsigjmp_bufDecl(Typedef->getDecl());
4018 else {
4019 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4020 assert(Tag && "Invalid sigjmp_buf type in AST file");
4021 Context.setsigjmp_bufDecl(Tag->getDecl());
4022 }
4023 }
4024 }
4025
4026 if (unsigned ObjCIdRedef
4027 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4028 if (Context.ObjCIdRedefinitionType.isNull())
4029 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4030 }
4031
4032 if (unsigned ObjCClassRedef
4033 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4034 if (Context.ObjCClassRedefinitionType.isNull())
4035 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4036 }
4037
4038 if (unsigned ObjCSelRedef
4039 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4040 if (Context.ObjCSelRedefinitionType.isNull())
4041 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4042 }
4043
4044 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4045 QualType Ucontext_tType = GetType(Ucontext_t);
4046 if (Ucontext_tType.isNull()) {
4047 Error("ucontext_t type is NULL");
4048 return;
4049 }
4050
4051 if (!Context.ucontext_tDecl) {
4052 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4053 Context.setucontext_tDecl(Typedef->getDecl());
4054 else {
4055 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4056 assert(Tag && "Invalid ucontext_t type in AST file");
4057 Context.setucontext_tDecl(Tag->getDecl());
4058 }
4059 }
4060 }
4061 }
4062
4063 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4064
4065 // If there were any CUDA special declarations, deserialize them.
4066 if (!CUDASpecialDeclRefs.empty()) {
4067 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4068 Context.setcudaConfigureCallDecl(
4069 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4070 }
Richard Smith56be7542014-03-21 00:33:59 +00004071
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004073 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004074 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004075 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004076 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004077 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004078 if (Import.ImportLoc.isValid())
4079 PP.makeModuleVisible(Imported, Import.ImportLoc);
4080 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004081 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 }
4083 ImportedModules.clear();
4084}
4085
4086void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004087 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004088}
4089
Ben Langmuir70a1b812015-03-24 04:43:52 +00004090/// \brief Reads and return the signature record from \p StreamFile's control
4091/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004092static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4093 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004094 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004095 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004096
4097 // Scan for the CONTROL_BLOCK_ID block.
4098 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4099 return 0;
4100
4101 // Scan for SIGNATURE inside the control block.
4102 ASTReader::RecordData Record;
4103 while (1) {
4104 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4105 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4106 Entry.Kind != llvm::BitstreamEntry::Record)
4107 return 0;
4108
4109 Record.clear();
4110 StringRef Blob;
4111 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4112 return Record[0];
4113 }
4114}
4115
Guy Benyei11169dd2012-12-18 14:30:41 +00004116/// \brief Retrieve the name of the original source file name
4117/// directly from the AST file, without actually loading the AST
4118/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004119std::string ASTReader::getOriginalSourceFile(
4120 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004121 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004123 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004125 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4126 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 return std::string();
4128 }
4129
4130 // Initialize the stream
4131 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004132 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004133 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004134
4135 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004136 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4138 return std::string();
4139 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004140
Chris Lattnere7b154b2013-01-19 21:39:22 +00004141 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004142 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004143 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4144 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004145 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004146
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004147 // Scan for ORIGINAL_FILE inside the control block.
4148 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004149 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004150 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004151 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4152 return std::string();
4153
4154 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4155 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4156 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004158
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004160 StringRef Blob;
4161 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4162 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004164}
4165
4166namespace {
4167 class SimplePCHValidator : public ASTReaderListener {
4168 const LangOptions &ExistingLangOpts;
4169 const TargetOptions &ExistingTargetOpts;
4170 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004171 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004173
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 public:
4175 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4176 const TargetOptions &ExistingTargetOpts,
4177 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004178 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 FileManager &FileMgr)
4180 : ExistingLangOpts(ExistingLangOpts),
4181 ExistingTargetOpts(ExistingTargetOpts),
4182 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004183 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 FileMgr(FileMgr)
4185 {
4186 }
4187
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004188 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4189 bool AllowCompatibleDifferences) override {
4190 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4191 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004193 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4194 bool AllowCompatibleDifferences) override {
4195 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4196 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004198 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4199 StringRef SpecificModuleCachePath,
4200 bool Complain) override {
4201 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4202 ExistingModuleCachePath,
4203 nullptr, ExistingLangOpts);
4204 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004205 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4206 bool Complain,
4207 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004208 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004209 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 }
4211 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004212}
Guy Benyei11169dd2012-12-18 14:30:41 +00004213
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004214bool ASTReader::readASTFileControlBlock(
4215 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004216 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004217 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004218 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004220 // FIXME: This allows use of the VFS; we do not allow use of the
4221 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004222 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 if (!Buffer) {
4224 return true;
4225 }
4226
4227 // Initialize the stream
4228 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004229 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004230 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
4232 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004233 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004235
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004236 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004237 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004238 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004239
4240 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004241 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004242 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004243 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004244
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004246 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004247 bool DoneWithControlBlock = false;
4248 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004249 llvm::BitstreamEntry Entry = Stream.advance();
4250
4251 switch (Entry.Kind) {
4252 case llvm::BitstreamEntry::SubBlock: {
4253 switch (Entry.ID) {
4254 case OPTIONS_BLOCK_ID: {
4255 std::string IgnoredSuggestedPredefines;
4256 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4257 /*AllowCompatibleConfigurationMismatch*/ false,
4258 Listener, IgnoredSuggestedPredefines) != Success)
4259 return true;
4260 break;
4261 }
4262
4263 case INPUT_FILES_BLOCK_ID:
4264 InputFilesCursor = Stream;
4265 if (Stream.SkipBlock() ||
4266 (NeedsInputFiles &&
4267 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4268 return true;
4269 break;
4270
4271 default:
4272 if (Stream.SkipBlock())
4273 return true;
4274 break;
4275 }
4276
4277 continue;
4278 }
4279
4280 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004281 DoneWithControlBlock = true;
4282 break;
Richard Smith0516b182015-09-08 19:40:14 +00004283
4284 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004285 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004286
4287 case llvm::BitstreamEntry::Record:
4288 break;
4289 }
4290
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004291 if (DoneWithControlBlock) break;
4292
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004294 StringRef Blob;
4295 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004296 switch ((ControlRecordTypes)RecCode) {
4297 case METADATA: {
4298 if (Record[0] != VERSION_MAJOR)
4299 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004300
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004301 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004302 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004303
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004304 break;
4305 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004306 case MODULE_NAME:
4307 Listener.ReadModuleName(Blob);
4308 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004309 case MODULE_DIRECTORY:
4310 ModuleDir = Blob;
4311 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004312 case MODULE_MAP_FILE: {
4313 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004314 auto Path = ReadString(Record, Idx);
4315 ResolveImportedPath(Path, ModuleDir);
4316 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004317 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004318 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004319 case INPUT_FILE_OFFSETS: {
4320 if (!NeedsInputFiles)
4321 break;
4322
4323 unsigned NumInputFiles = Record[0];
4324 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004325 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004326 for (unsigned I = 0; I != NumInputFiles; ++I) {
4327 // Go find this input file.
4328 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004329
4330 if (isSystemFile && !NeedsSystemInputFiles)
4331 break; // the rest are system input files
4332
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004333 BitstreamCursor &Cursor = InputFilesCursor;
4334 SavedStreamPosition SavedPosition(Cursor);
4335 Cursor.JumpToBit(InputFileOffs[I]);
4336
4337 unsigned Code = Cursor.ReadCode();
4338 RecordData Record;
4339 StringRef Blob;
4340 bool shouldContinue = false;
4341 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4342 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004343 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004344 std::string Filename = Blob;
4345 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004346 shouldContinue = Listener.visitInputFile(
4347 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004348 break;
4349 }
4350 if (!shouldContinue)
4351 break;
4352 }
4353 break;
4354 }
4355
Richard Smithd4b230b2014-10-27 23:01:16 +00004356 case IMPORTS: {
4357 if (!NeedsImports)
4358 break;
4359
4360 unsigned Idx = 0, N = Record.size();
4361 while (Idx < N) {
4362 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004363 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004364 std::string Filename = ReadString(Record, Idx);
4365 ResolveImportedPath(Filename, ModuleDir);
4366 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004367 }
4368 break;
4369 }
4370
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004371 default:
4372 // No other validation to perform.
4373 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 }
4375 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004376
4377 // Look for module file extension blocks, if requested.
4378 if (FindModuleFileExtensions) {
4379 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4380 bool DoneWithExtensionBlock = false;
4381 while (!DoneWithExtensionBlock) {
4382 llvm::BitstreamEntry Entry = Stream.advance();
4383
4384 switch (Entry.Kind) {
4385 case llvm::BitstreamEntry::SubBlock:
4386 if (Stream.SkipBlock())
4387 return true;
4388
4389 continue;
4390
4391 case llvm::BitstreamEntry::EndBlock:
4392 DoneWithExtensionBlock = true;
4393 continue;
4394
4395 case llvm::BitstreamEntry::Error:
4396 return true;
4397
4398 case llvm::BitstreamEntry::Record:
4399 break;
4400 }
4401
4402 Record.clear();
4403 StringRef Blob;
4404 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4405 switch (RecCode) {
4406 case EXTENSION_METADATA: {
4407 ModuleFileExtensionMetadata Metadata;
4408 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4409 return true;
4410
4411 Listener.readModuleFileExtension(Metadata);
4412 break;
4413 }
4414 }
4415 }
4416 }
4417 }
4418
4419 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420}
4421
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004422bool ASTReader::isAcceptableASTFile(
4423 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004424 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004425 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4426 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004427 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4428 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004429 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004430 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004431 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004432}
4433
Ben Langmuir2c9af442014-04-10 17:57:43 +00004434ASTReader::ASTReadResult
4435ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 // Enter the submodule block.
4437 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4438 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004439 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 }
4441
4442 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4443 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004444 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 RecordData Record;
4446 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004447 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4448
4449 switch (Entry.Kind) {
4450 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4451 case llvm::BitstreamEntry::Error:
4452 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004453 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004454 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004455 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004456 case llvm::BitstreamEntry::Record:
4457 // The interesting case.
4458 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004460
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004462 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004464 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4465
4466 if ((Kind == SUBMODULE_METADATA) != First) {
4467 Error("submodule metadata record should be at beginning of block");
4468 return Failure;
4469 }
4470 First = false;
4471
4472 // Submodule information is only valid if we have a current module.
4473 // FIXME: Should we error on these cases?
4474 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4475 Kind != SUBMODULE_DEFINITION)
4476 continue;
4477
4478 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 default: // Default behavior: ignore.
4480 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004481
Richard Smith03478d92014-10-23 22:12:14 +00004482 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004483 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004485 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 }
Richard Smith03478d92014-10-23 22:12:14 +00004487
Chris Lattner0e6c9402013-01-20 02:38:54 +00004488 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004489 unsigned Idx = 0;
4490 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4491 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4492 bool IsFramework = Record[Idx++];
4493 bool IsExplicit = Record[Idx++];
4494 bool IsSystem = Record[Idx++];
4495 bool IsExternC = Record[Idx++];
4496 bool InferSubmodules = Record[Idx++];
4497 bool InferExplicitSubmodules = Record[Idx++];
4498 bool InferExportWildcard = Record[Idx++];
4499 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004500
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004501 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004502 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004504
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 // Retrieve this (sub)module from the module map, creating it if
4506 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004507 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004509
4510 // FIXME: set the definition loc for CurrentModule, or call
4511 // ModMap.setInferredModuleAllowedBy()
4512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4514 if (GlobalIndex >= SubmodulesLoaded.size() ||
4515 SubmodulesLoaded[GlobalIndex]) {
4516 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004517 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004519
Douglas Gregor7029ce12013-03-19 00:28:20 +00004520 if (!ParentModule) {
4521 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4522 if (CurFile != F.File) {
4523 if (!Diags.isDiagnosticInFlight()) {
4524 Diag(diag::err_module_file_conflict)
4525 << CurrentModule->getTopLevelModuleName()
4526 << CurFile->getName()
4527 << F.File->getName();
4528 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004529 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004530 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004531 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004532
4533 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004534 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004535
Adrian Prantl15bcf702015-06-30 17:39:43 +00004536 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 CurrentModule->IsFromModuleFile = true;
4538 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004539 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 CurrentModule->InferSubmodules = InferSubmodules;
4541 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4542 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004543 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 if (DeserializationListener)
4545 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4546
4547 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004548
Richard Smith8a3e39a2016-03-28 21:31:09 +00004549 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004550 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004551 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004552 CurrentModule->UnresolvedConflicts.clear();
4553 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004554
4555 // The module is available unless it's missing a requirement; relevant
4556 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4557 // Missing headers that were present when the module was built do not
4558 // make it unavailable -- if we got this far, this must be an explicitly
4559 // imported module file.
4560 CurrentModule->Requirements.clear();
4561 CurrentModule->MissingHeaders.clear();
4562 CurrentModule->IsMissingRequirement =
4563 ParentModule && ParentModule->IsMissingRequirement;
4564 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 break;
4566 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004567
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004569 std::string Filename = Blob;
4570 ResolveImportedPath(F, Filename);
4571 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004573 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4574 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004575 // This can be a spurious difference caused by changing the VFS to
4576 // point to a different copy of the file, and it is too late to
4577 // to rebuild safely.
4578 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4579 // after input file validation only real problems would remain and we
4580 // could just error. For now, assume it's okay.
4581 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 }
4583 }
4584 break;
4585 }
4586
Richard Smith202210b2014-10-24 20:23:01 +00004587 case SUBMODULE_HEADER:
4588 case SUBMODULE_EXCLUDED_HEADER:
4589 case SUBMODULE_PRIVATE_HEADER:
4590 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004591 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4592 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004593 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
Richard Smith202210b2014-10-24 20:23:01 +00004595 case SUBMODULE_TEXTUAL_HEADER:
4596 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4597 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4598 // them here.
4599 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004600
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004602 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 break;
4604 }
4605
4606 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004607 std::string Dirname = Blob;
4608 ResolveImportedPath(F, Dirname);
4609 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004611 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4612 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004613 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4614 Error("mismatched umbrella directories in submodule");
4615 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 }
4617 }
4618 break;
4619 }
4620
4621 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 F.BaseSubmoduleID = getTotalNumSubmodules();
4623 F.LocalNumSubmodules = Record[0];
4624 unsigned LocalBaseSubmoduleID = Record[1];
4625 if (F.LocalNumSubmodules > 0) {
4626 // Introduce the global -> local mapping for submodules within this
4627 // module.
4628 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4629
4630 // Introduce the local -> global mapping for submodules within this
4631 // module.
4632 F.SubmoduleRemap.insertOrReplace(
4633 std::make_pair(LocalBaseSubmoduleID,
4634 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004635
Ben Langmuir52ca6782014-10-20 16:27:32 +00004636 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4637 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 break;
4639 }
4640
4641 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004643 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 Unresolved.File = &F;
4645 Unresolved.Mod = CurrentModule;
4646 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004647 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004649 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 }
4651 break;
4652 }
4653
4654 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004655 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004656 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 Unresolved.File = &F;
4658 Unresolved.Mod = CurrentModule;
4659 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004660 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004662 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 }
4664
4665 // Once we've loaded the set of exports, there's no reason to keep
4666 // the parsed, unresolved exports around.
4667 CurrentModule->UnresolvedExports.clear();
4668 break;
4669 }
4670 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004671 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 Context.getTargetInfo());
4673 break;
4674 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004675
4676 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004677 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004678 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004679 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004680
4681 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004682 CurrentModule->ConfigMacros.push_back(Blob.str());
4683 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004684
4685 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004686 UnresolvedModuleRef Unresolved;
4687 Unresolved.File = &F;
4688 Unresolved.Mod = CurrentModule;
4689 Unresolved.ID = Record[0];
4690 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4691 Unresolved.IsWildcard = false;
4692 Unresolved.String = Blob;
4693 UnresolvedModuleRefs.push_back(Unresolved);
4694 break;
4695 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 }
4697 }
4698}
4699
4700/// \brief Parse the record that corresponds to a LangOptions data
4701/// structure.
4702///
4703/// This routine parses the language options from the AST file and then gives
4704/// them to the AST listener if one is set.
4705///
4706/// \returns true if the listener deems the file unacceptable, false otherwise.
4707bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4708 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004709 ASTReaderListener &Listener,
4710 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 LangOptions LangOpts;
4712 unsigned Idx = 0;
4713#define LANGOPT(Name, Bits, Default, Description) \
4714 LangOpts.Name = Record[Idx++];
4715#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4716 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4717#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004718#define SANITIZER(NAME, ID) \
4719 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004720#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004721
Ben Langmuircd98cb72015-06-23 18:20:18 +00004722 for (unsigned N = Record[Idx++]; N; --N)
4723 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4724
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4726 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4727 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004728
Ben Langmuird4a667a2015-06-23 18:20:23 +00004729 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004730
4731 // Comment options.
4732 for (unsigned N = Record[Idx++]; N; --N) {
4733 LangOpts.CommentOpts.BlockCommandNames.push_back(
4734 ReadString(Record, Idx));
4735 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004736 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004737
Samuel Antaoee8fb302016-01-06 13:42:12 +00004738 // OpenMP offloading options.
4739 for (unsigned N = Record[Idx++]; N; --N) {
4740 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4741 }
4742
4743 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4744
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004745 return Listener.ReadLanguageOptions(LangOpts, Complain,
4746 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004747}
4748
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004749bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4750 ASTReaderListener &Listener,
4751 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 unsigned Idx = 0;
4753 TargetOptions TargetOpts;
4754 TargetOpts.Triple = ReadString(Record, Idx);
4755 TargetOpts.CPU = ReadString(Record, Idx);
4756 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 for (unsigned N = Record[Idx++]; N; --N) {
4758 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4759 }
4760 for (unsigned N = Record[Idx++]; N; --N) {
4761 TargetOpts.Features.push_back(ReadString(Record, Idx));
4762 }
4763
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004764 return Listener.ReadTargetOptions(TargetOpts, Complain,
4765 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004766}
4767
4768bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4769 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004770 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004772#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004773#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004774 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004775#include "clang/Basic/DiagnosticOptions.def"
4776
Richard Smith3be1cb22014-08-07 00:24:21 +00004777 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004778 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004779 for (unsigned N = Record[Idx++]; N; --N)
4780 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004781
4782 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4783}
4784
4785bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4786 ASTReaderListener &Listener) {
4787 FileSystemOptions FSOpts;
4788 unsigned Idx = 0;
4789 FSOpts.WorkingDir = ReadString(Record, Idx);
4790 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4791}
4792
4793bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4794 bool Complain,
4795 ASTReaderListener &Listener) {
4796 HeaderSearchOptions HSOpts;
4797 unsigned Idx = 0;
4798 HSOpts.Sysroot = ReadString(Record, Idx);
4799
4800 // Include entries.
4801 for (unsigned N = Record[Idx++]; N; --N) {
4802 std::string Path = ReadString(Record, Idx);
4803 frontend::IncludeDirGroup Group
4804 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 bool IsFramework = Record[Idx++];
4806 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004807 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4808 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 }
4810
4811 // System header prefixes.
4812 for (unsigned N = Record[Idx++]; N; --N) {
4813 std::string Prefix = ReadString(Record, Idx);
4814 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004815 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 }
4817
4818 HSOpts.ResourceDir = ReadString(Record, Idx);
4819 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004820 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 HSOpts.DisableModuleHash = Record[Idx++];
4822 HSOpts.UseBuiltinIncludes = Record[Idx++];
4823 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4824 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4825 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004826 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004827
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004828 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4829 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004830}
4831
4832bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4833 bool Complain,
4834 ASTReaderListener &Listener,
4835 std::string &SuggestedPredefines) {
4836 PreprocessorOptions PPOpts;
4837 unsigned Idx = 0;
4838
4839 // Macro definitions/undefs
4840 for (unsigned N = Record[Idx++]; N; --N) {
4841 std::string Macro = ReadString(Record, Idx);
4842 bool IsUndef = Record[Idx++];
4843 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4844 }
4845
4846 // Includes
4847 for (unsigned N = Record[Idx++]; N; --N) {
4848 PPOpts.Includes.push_back(ReadString(Record, Idx));
4849 }
4850
4851 // Macro Includes
4852 for (unsigned N = Record[Idx++]; N; --N) {
4853 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4854 }
4855
4856 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004857 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4859 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4860 PPOpts.ObjCXXARCStandardLibrary =
4861 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4862 SuggestedPredefines.clear();
4863 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4864 SuggestedPredefines);
4865}
4866
4867std::pair<ModuleFile *, unsigned>
4868ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4869 GlobalPreprocessedEntityMapType::iterator
4870 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4871 assert(I != GlobalPreprocessedEntityMap.end() &&
4872 "Corrupted global preprocessed entity map");
4873 ModuleFile *M = I->second;
4874 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4875 return std::make_pair(M, LocalIndex);
4876}
4877
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004878llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004879ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4880 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4881 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4882 Mod.NumPreprocessedEntities);
4883
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004884 return llvm::make_range(PreprocessingRecord::iterator(),
4885 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004886}
4887
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004888llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004889ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004890 return llvm::make_range(
4891 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4892 ModuleDeclIterator(this, &Mod,
4893 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004894}
4895
4896PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4897 PreprocessedEntityID PPID = Index+1;
4898 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4899 ModuleFile &M = *PPInfo.first;
4900 unsigned LocalIndex = PPInfo.second;
4901 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4902
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 if (!PP.getPreprocessingRecord()) {
4904 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004905 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 }
4907
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004908 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4909 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4910
4911 llvm::BitstreamEntry Entry =
4912 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4913 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004914 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004915
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00004917 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
4918 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004920 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 RecordData Record;
4922 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004923 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4924 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 switch (RecType) {
4926 case PPD_MACRO_EXPANSION: {
4927 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004928 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004929 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 if (isBuiltin)
4931 Name = getLocalIdentifier(M, Record[1]);
4932 else {
Richard Smith66a81862015-05-04 02:25:31 +00004933 PreprocessedEntityID GlobalID =
4934 getGlobalPreprocessedEntityID(M, Record[1]);
4935 Def = cast<MacroDefinitionRecord>(
4936 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 }
4938
4939 MacroExpansion *ME;
4940 if (isBuiltin)
4941 ME = new (PPRec) MacroExpansion(Name, Range);
4942 else
4943 ME = new (PPRec) MacroExpansion(Def, Range);
4944
4945 return ME;
4946 }
4947
4948 case PPD_MACRO_DEFINITION: {
4949 // Decode the identifier info and then check again; if the macro is
4950 // still defined and associated with the identifier,
4951 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004952 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004953
4954 if (DeserializationListener)
4955 DeserializationListener->MacroDefinitionRead(PPID, MD);
4956
4957 return MD;
4958 }
4959
4960 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004961 const char *FullFileNameStart = Blob.data() + Record[0];
4962 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004963 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 if (!FullFileName.empty())
4965 File = PP.getFileManager().getFile(FullFileName);
4966
4967 // FIXME: Stable encoding
4968 InclusionDirective::InclusionKind Kind
4969 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4970 InclusionDirective *ID
4971 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004972 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 Record[1], Record[3],
4974 File,
4975 Range);
4976 return ID;
4977 }
4978 }
4979
4980 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4981}
4982
4983/// \brief \arg SLocMapI points at a chunk of a module that contains no
4984/// preprocessed entities or the entities it contains are not the ones we are
4985/// looking for. Find the next module that contains entities and return the ID
4986/// of the first entry.
4987PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4988 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4989 ++SLocMapI;
4990 for (GlobalSLocOffsetMapType::const_iterator
4991 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4992 ModuleFile &M = *SLocMapI->second;
4993 if (M.NumPreprocessedEntities)
4994 return M.BasePreprocessedEntityID;
4995 }
4996
4997 return getTotalNumPreprocessedEntities();
4998}
4999
5000namespace {
5001
Guy Benyei11169dd2012-12-18 14:30:41 +00005002struct PPEntityComp {
5003 const ASTReader &Reader;
5004 ModuleFile &M;
5005
5006 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5007
5008 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5009 SourceLocation LHS = getLoc(L);
5010 SourceLocation RHS = getLoc(R);
5011 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5012 }
5013
5014 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5015 SourceLocation LHS = getLoc(L);
5016 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5017 }
5018
5019 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5020 SourceLocation RHS = getLoc(R);
5021 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5022 }
5023
5024 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005025 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 }
5027};
5028
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005029}
Guy Benyei11169dd2012-12-18 14:30:41 +00005030
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005031PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5032 bool EndsAfter) const {
5033 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 return getTotalNumPreprocessedEntities();
5035
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005036 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5037 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5039 "Corrupted global sloc offset map");
5040
5041 if (SLocMapI->second->NumPreprocessedEntities == 0)
5042 return findNextPreprocessedEntity(SLocMapI);
5043
5044 ModuleFile &M = *SLocMapI->second;
5045 typedef const PPEntityOffset *pp_iterator;
5046 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5047 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5048
5049 size_t Count = M.NumPreprocessedEntities;
5050 size_t Half;
5051 pp_iterator First = pp_begin;
5052 pp_iterator PPI;
5053
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005054 if (EndsAfter) {
5055 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005056 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005057 } else {
5058 // Do a binary search manually instead of using std::lower_bound because
5059 // The end locations of entities may be unordered (when a macro expansion
5060 // is inside another macro argument), but for this case it is not important
5061 // whether we get the first macro expansion or its containing macro.
5062 while (Count > 0) {
5063 Half = Count / 2;
5064 PPI = First;
5065 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005066 if (SourceMgr.isBeforeInTranslationUnit(
5067 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005068 First = PPI;
5069 ++First;
5070 Count = Count - Half - 1;
5071 } else
5072 Count = Half;
5073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 }
5075
5076 if (PPI == pp_end)
5077 return findNextPreprocessedEntity(SLocMapI);
5078
5079 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5080}
5081
Guy Benyei11169dd2012-12-18 14:30:41 +00005082/// \brief Returns a pair of [Begin, End) indices of preallocated
5083/// preprocessed entities that \arg Range encompasses.
5084std::pair<unsigned, unsigned>
5085 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5086 if (Range.isInvalid())
5087 return std::make_pair(0,0);
5088 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5089
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005090 PreprocessedEntityID BeginID =
5091 findPreprocessedEntity(Range.getBegin(), false);
5092 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 return std::make_pair(BeginID, EndID);
5094}
5095
5096/// \brief Optionally returns true or false if the preallocated preprocessed
5097/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005098Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 FileID FID) {
5100 if (FID.isInvalid())
5101 return false;
5102
5103 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5104 ModuleFile &M = *PPInfo.first;
5105 unsigned LocalIndex = PPInfo.second;
5106 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5107
Richard Smithcb34bd32016-03-27 07:28:06 +00005108 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 if (Loc.isInvalid())
5110 return false;
5111
5112 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5113 return true;
5114 else
5115 return false;
5116}
5117
5118namespace {
5119 /// \brief Visitor used to search for information about a header file.
5120 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 const FileEntry *FE;
5122
David Blaikie05785d12013-02-20 22:23:23 +00005123 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005124
5125 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005126 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5127 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005128
5129 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 HeaderFileInfoLookupTable *Table
5131 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5132 if (!Table)
5133 return false;
5134
5135 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005136 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 if (Pos == Table->end())
5138 return false;
5139
Richard Smithbdf2d932015-07-30 03:37:16 +00005140 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 return true;
5142 }
5143
David Blaikie05785d12013-02-20 22:23:23 +00005144 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005146}
Guy Benyei11169dd2012-12-18 14:30:41 +00005147
5148HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005149 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005150 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005151 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005153
5154 return HeaderFileInfo();
5155}
5156
5157void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5158 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005159 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5161 ModuleFile &F = *(*I);
5162 unsigned Idx = 0;
5163 DiagStates.clear();
5164 assert(!Diag.DiagStates.empty());
5165 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5166 while (Idx < F.PragmaDiagMappings.size()) {
5167 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5168 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5169 if (DiagStateID != 0) {
5170 Diag.DiagStatePoints.push_back(
5171 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5172 FullSourceLoc(Loc, SourceMgr)));
5173 continue;
5174 }
5175
5176 assert(DiagStateID == 0);
5177 // A new DiagState was created here.
5178 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5179 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5180 DiagStates.push_back(NewState);
5181 Diag.DiagStatePoints.push_back(
5182 DiagnosticsEngine::DiagStatePoint(NewState,
5183 FullSourceLoc(Loc, SourceMgr)));
5184 while (1) {
5185 assert(Idx < F.PragmaDiagMappings.size() &&
5186 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5187 if (Idx >= F.PragmaDiagMappings.size()) {
5188 break; // Something is messed up but at least avoid infinite loop in
5189 // release build.
5190 }
5191 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5192 if (DiagID == (unsigned)-1) {
5193 break; // no more diag/map pairs for this location.
5194 }
Alp Tokerc726c362014-06-10 09:31:37 +00005195 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5196 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5197 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 }
5199 }
5200 }
5201}
5202
5203/// \brief Get the correct cursor and offset for loading a type.
5204ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5205 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5206 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5207 ModuleFile *M = I->second;
5208 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5209}
5210
5211/// \brief Read and return the type with the given index..
5212///
5213/// The index is the type ID, shifted and minus the number of predefs. This
5214/// routine actually reads the record corresponding to the type at the given
5215/// location. It is a helper routine for GetType, which deals with reading type
5216/// IDs.
5217QualType ASTReader::readTypeRecord(unsigned Index) {
5218 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005219 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005220
5221 // Keep track of where we are in the stream, then jump back there
5222 // after reading this type.
5223 SavedStreamPosition SavedPosition(DeclsCursor);
5224
5225 ReadingKindTracker ReadingKind(Read_Type, *this);
5226
5227 // Note that we are loading a type record.
5228 Deserializing AType(this);
5229
5230 unsigned Idx = 0;
5231 DeclsCursor.JumpToBit(Loc.Offset);
5232 RecordData Record;
5233 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005234 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 case TYPE_EXT_QUAL: {
5236 if (Record.size() != 2) {
5237 Error("Incorrect encoding of extended qualifier type");
5238 return QualType();
5239 }
5240 QualType Base = readType(*Loc.F, Record, Idx);
5241 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5242 return Context.getQualifiedType(Base, Quals);
5243 }
5244
5245 case TYPE_COMPLEX: {
5246 if (Record.size() != 1) {
5247 Error("Incorrect encoding of complex type");
5248 return QualType();
5249 }
5250 QualType ElemType = readType(*Loc.F, Record, Idx);
5251 return Context.getComplexType(ElemType);
5252 }
5253
5254 case TYPE_POINTER: {
5255 if (Record.size() != 1) {
5256 Error("Incorrect encoding of pointer type");
5257 return QualType();
5258 }
5259 QualType PointeeType = readType(*Loc.F, Record, Idx);
5260 return Context.getPointerType(PointeeType);
5261 }
5262
Reid Kleckner8a365022013-06-24 17:51:48 +00005263 case TYPE_DECAYED: {
5264 if (Record.size() != 1) {
5265 Error("Incorrect encoding of decayed type");
5266 return QualType();
5267 }
5268 QualType OriginalType = readType(*Loc.F, Record, Idx);
5269 QualType DT = Context.getAdjustedParameterType(OriginalType);
5270 if (!isa<DecayedType>(DT))
5271 Error("Decayed type does not decay");
5272 return DT;
5273 }
5274
Reid Kleckner0503a872013-12-05 01:23:43 +00005275 case TYPE_ADJUSTED: {
5276 if (Record.size() != 2) {
5277 Error("Incorrect encoding of adjusted type");
5278 return QualType();
5279 }
5280 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5281 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5282 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5283 }
5284
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 case TYPE_BLOCK_POINTER: {
5286 if (Record.size() != 1) {
5287 Error("Incorrect encoding of block pointer type");
5288 return QualType();
5289 }
5290 QualType PointeeType = readType(*Loc.F, Record, Idx);
5291 return Context.getBlockPointerType(PointeeType);
5292 }
5293
5294 case TYPE_LVALUE_REFERENCE: {
5295 if (Record.size() != 2) {
5296 Error("Incorrect encoding of lvalue reference type");
5297 return QualType();
5298 }
5299 QualType PointeeType = readType(*Loc.F, Record, Idx);
5300 return Context.getLValueReferenceType(PointeeType, Record[1]);
5301 }
5302
5303 case TYPE_RVALUE_REFERENCE: {
5304 if (Record.size() != 1) {
5305 Error("Incorrect encoding of rvalue reference type");
5306 return QualType();
5307 }
5308 QualType PointeeType = readType(*Loc.F, Record, Idx);
5309 return Context.getRValueReferenceType(PointeeType);
5310 }
5311
5312 case TYPE_MEMBER_POINTER: {
5313 if (Record.size() != 2) {
5314 Error("Incorrect encoding of member pointer type");
5315 return QualType();
5316 }
5317 QualType PointeeType = readType(*Loc.F, Record, Idx);
5318 QualType ClassType = readType(*Loc.F, Record, Idx);
5319 if (PointeeType.isNull() || ClassType.isNull())
5320 return QualType();
5321
5322 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5323 }
5324
5325 case TYPE_CONSTANT_ARRAY: {
5326 QualType ElementType = readType(*Loc.F, Record, Idx);
5327 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5328 unsigned IndexTypeQuals = Record[2];
5329 unsigned Idx = 3;
5330 llvm::APInt Size = ReadAPInt(Record, Idx);
5331 return Context.getConstantArrayType(ElementType, Size,
5332 ASM, IndexTypeQuals);
5333 }
5334
5335 case TYPE_INCOMPLETE_ARRAY: {
5336 QualType ElementType = readType(*Loc.F, Record, Idx);
5337 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5338 unsigned IndexTypeQuals = Record[2];
5339 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5340 }
5341
5342 case TYPE_VARIABLE_ARRAY: {
5343 QualType ElementType = readType(*Loc.F, Record, Idx);
5344 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5345 unsigned IndexTypeQuals = Record[2];
5346 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5347 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5348 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5349 ASM, IndexTypeQuals,
5350 SourceRange(LBLoc, RBLoc));
5351 }
5352
5353 case TYPE_VECTOR: {
5354 if (Record.size() != 3) {
5355 Error("incorrect encoding of vector type in AST file");
5356 return QualType();
5357 }
5358
5359 QualType ElementType = readType(*Loc.F, Record, Idx);
5360 unsigned NumElements = Record[1];
5361 unsigned VecKind = Record[2];
5362 return Context.getVectorType(ElementType, NumElements,
5363 (VectorType::VectorKind)VecKind);
5364 }
5365
5366 case TYPE_EXT_VECTOR: {
5367 if (Record.size() != 3) {
5368 Error("incorrect encoding of extended vector type in AST file");
5369 return QualType();
5370 }
5371
5372 QualType ElementType = readType(*Loc.F, Record, Idx);
5373 unsigned NumElements = Record[1];
5374 return Context.getExtVectorType(ElementType, NumElements);
5375 }
5376
5377 case TYPE_FUNCTION_NO_PROTO: {
5378 if (Record.size() != 6) {
5379 Error("incorrect encoding of no-proto function type");
5380 return QualType();
5381 }
5382 QualType ResultType = readType(*Loc.F, Record, Idx);
5383 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5384 (CallingConv)Record[4], Record[5]);
5385 return Context.getFunctionNoProtoType(ResultType, Info);
5386 }
5387
5388 case TYPE_FUNCTION_PROTO: {
5389 QualType ResultType = readType(*Loc.F, Record, Idx);
5390
5391 FunctionProtoType::ExtProtoInfo EPI;
5392 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5393 /*hasregparm*/ Record[2],
5394 /*regparm*/ Record[3],
5395 static_cast<CallingConv>(Record[4]),
5396 /*produces*/ Record[5]);
5397
5398 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005399
5400 EPI.Variadic = Record[Idx++];
5401 EPI.HasTrailingReturn = Record[Idx++];
5402 EPI.TypeQuals = Record[Idx++];
5403 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005404 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005405 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005406
5407 unsigned NumParams = Record[Idx++];
5408 SmallVector<QualType, 16> ParamTypes;
5409 for (unsigned I = 0; I != NumParams; ++I)
5410 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5411
John McCall18afab72016-03-01 00:49:02 +00005412 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5413 if (Idx != Record.size()) {
5414 for (unsigned I = 0; I != NumParams; ++I)
5415 ExtParameterInfos.push_back(
5416 FunctionProtoType::ExtParameterInfo
5417 ::getFromOpaqueValue(Record[Idx++]));
5418 EPI.ExtParameterInfos = ExtParameterInfos.data();
5419 }
5420
5421 assert(Idx == Record.size());
5422
Jordan Rose5c382722013-03-08 21:51:21 +00005423 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 }
5425
5426 case TYPE_UNRESOLVED_USING: {
5427 unsigned Idx = 0;
5428 return Context.getTypeDeclType(
5429 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5430 }
5431
5432 case TYPE_TYPEDEF: {
5433 if (Record.size() != 2) {
5434 Error("incorrect encoding of typedef type");
5435 return QualType();
5436 }
5437 unsigned Idx = 0;
5438 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5439 QualType Canonical = readType(*Loc.F, Record, Idx);
5440 if (!Canonical.isNull())
5441 Canonical = Context.getCanonicalType(Canonical);
5442 return Context.getTypedefType(Decl, Canonical);
5443 }
5444
5445 case TYPE_TYPEOF_EXPR:
5446 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5447
5448 case TYPE_TYPEOF: {
5449 if (Record.size() != 1) {
5450 Error("incorrect encoding of typeof(type) in AST file");
5451 return QualType();
5452 }
5453 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5454 return Context.getTypeOfType(UnderlyingType);
5455 }
5456
5457 case TYPE_DECLTYPE: {
5458 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5459 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5460 }
5461
5462 case TYPE_UNARY_TRANSFORM: {
5463 QualType BaseType = readType(*Loc.F, Record, Idx);
5464 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5465 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5466 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5467 }
5468
Richard Smith74aeef52013-04-26 16:15:35 +00005469 case TYPE_AUTO: {
5470 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005471 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005472 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005473 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005474 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005475
5476 case TYPE_RECORD: {
5477 if (Record.size() != 2) {
5478 Error("incorrect encoding of record type");
5479 return QualType();
5480 }
5481 unsigned Idx = 0;
5482 bool IsDependent = Record[Idx++];
5483 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5484 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5485 QualType T = Context.getRecordType(RD);
5486 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5487 return T;
5488 }
5489
5490 case TYPE_ENUM: {
5491 if (Record.size() != 2) {
5492 Error("incorrect encoding of enum type");
5493 return QualType();
5494 }
5495 unsigned Idx = 0;
5496 bool IsDependent = Record[Idx++];
5497 QualType T
5498 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5499 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5500 return T;
5501 }
5502
5503 case TYPE_ATTRIBUTED: {
5504 if (Record.size() != 3) {
5505 Error("incorrect encoding of attributed type");
5506 return QualType();
5507 }
5508 QualType modifiedType = readType(*Loc.F, Record, Idx);
5509 QualType equivalentType = readType(*Loc.F, Record, Idx);
5510 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5511 return Context.getAttributedType(kind, modifiedType, equivalentType);
5512 }
5513
5514 case TYPE_PAREN: {
5515 if (Record.size() != 1) {
5516 Error("incorrect encoding of paren type");
5517 return QualType();
5518 }
5519 QualType InnerType = readType(*Loc.F, Record, Idx);
5520 return Context.getParenType(InnerType);
5521 }
5522
5523 case TYPE_PACK_EXPANSION: {
5524 if (Record.size() != 2) {
5525 Error("incorrect encoding of pack expansion type");
5526 return QualType();
5527 }
5528 QualType Pattern = readType(*Loc.F, Record, Idx);
5529 if (Pattern.isNull())
5530 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005531 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005532 if (Record[1])
5533 NumExpansions = Record[1] - 1;
5534 return Context.getPackExpansionType(Pattern, NumExpansions);
5535 }
5536
5537 case TYPE_ELABORATED: {
5538 unsigned Idx = 0;
5539 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5540 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5541 QualType NamedType = readType(*Loc.F, Record, Idx);
5542 return Context.getElaboratedType(Keyword, NNS, NamedType);
5543 }
5544
5545 case TYPE_OBJC_INTERFACE: {
5546 unsigned Idx = 0;
5547 ObjCInterfaceDecl *ItfD
5548 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5549 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5550 }
5551
5552 case TYPE_OBJC_OBJECT: {
5553 unsigned Idx = 0;
5554 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005555 unsigned NumTypeArgs = Record[Idx++];
5556 SmallVector<QualType, 4> TypeArgs;
5557 for (unsigned I = 0; I != NumTypeArgs; ++I)
5558 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005559 unsigned NumProtos = Record[Idx++];
5560 SmallVector<ObjCProtocolDecl*, 4> Protos;
5561 for (unsigned I = 0; I != NumProtos; ++I)
5562 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005563 bool IsKindOf = Record[Idx++];
5564 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 }
5566
5567 case TYPE_OBJC_OBJECT_POINTER: {
5568 unsigned Idx = 0;
5569 QualType Pointee = readType(*Loc.F, Record, Idx);
5570 return Context.getObjCObjectPointerType(Pointee);
5571 }
5572
5573 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5574 unsigned Idx = 0;
5575 QualType Parm = readType(*Loc.F, Record, Idx);
5576 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005577 return Context.getSubstTemplateTypeParmType(
5578 cast<TemplateTypeParmType>(Parm),
5579 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005580 }
5581
5582 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5583 unsigned Idx = 0;
5584 QualType Parm = readType(*Loc.F, Record, Idx);
5585 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5586 return Context.getSubstTemplateTypeParmPackType(
5587 cast<TemplateTypeParmType>(Parm),
5588 ArgPack);
5589 }
5590
5591 case TYPE_INJECTED_CLASS_NAME: {
5592 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5593 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5594 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5595 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005596 const Type *T = nullptr;
5597 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5598 if (const Type *Existing = DI->getTypeForDecl()) {
5599 T = Existing;
5600 break;
5601 }
5602 }
5603 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005604 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005605 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5606 DI->setTypeForDecl(T);
5607 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005608 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005609 }
5610
5611 case TYPE_TEMPLATE_TYPE_PARM: {
5612 unsigned Idx = 0;
5613 unsigned Depth = Record[Idx++];
5614 unsigned Index = Record[Idx++];
5615 bool Pack = Record[Idx++];
5616 TemplateTypeParmDecl *D
5617 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5618 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5619 }
5620
5621 case TYPE_DEPENDENT_NAME: {
5622 unsigned Idx = 0;
5623 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5624 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005625 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 QualType Canon = readType(*Loc.F, Record, Idx);
5627 if (!Canon.isNull())
5628 Canon = Context.getCanonicalType(Canon);
5629 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5630 }
5631
5632 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5633 unsigned Idx = 0;
5634 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5635 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005636 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005637 unsigned NumArgs = Record[Idx++];
5638 SmallVector<TemplateArgument, 8> Args;
5639 Args.reserve(NumArgs);
5640 while (NumArgs--)
5641 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5642 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5643 Args.size(), Args.data());
5644 }
5645
5646 case TYPE_DEPENDENT_SIZED_ARRAY: {
5647 unsigned Idx = 0;
5648
5649 // ArrayType
5650 QualType ElementType = readType(*Loc.F, Record, Idx);
5651 ArrayType::ArraySizeModifier ASM
5652 = (ArrayType::ArraySizeModifier)Record[Idx++];
5653 unsigned IndexTypeQuals = Record[Idx++];
5654
5655 // DependentSizedArrayType
5656 Expr *NumElts = ReadExpr(*Loc.F);
5657 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5658
5659 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5660 IndexTypeQuals, Brackets);
5661 }
5662
5663 case TYPE_TEMPLATE_SPECIALIZATION: {
5664 unsigned Idx = 0;
5665 bool IsDependent = Record[Idx++];
5666 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5667 SmallVector<TemplateArgument, 8> Args;
5668 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5669 QualType Underlying = readType(*Loc.F, Record, Idx);
5670 QualType T;
5671 if (Underlying.isNull())
5672 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5673 Args.size());
5674 else
5675 T = Context.getTemplateSpecializationType(Name, Args.data(),
5676 Args.size(), Underlying);
5677 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5678 return T;
5679 }
5680
5681 case TYPE_ATOMIC: {
5682 if (Record.size() != 1) {
5683 Error("Incorrect encoding of atomic type");
5684 return QualType();
5685 }
5686 QualType ValueType = readType(*Loc.F, Record, Idx);
5687 return Context.getAtomicType(ValueType);
5688 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005689
5690 case TYPE_PIPE: {
5691 if (Record.size() != 1) {
5692 Error("Incorrect encoding of pipe type");
5693 return QualType();
5694 }
5695
5696 // Reading the pipe element type.
5697 QualType ElementType = readType(*Loc.F, Record, Idx);
5698 return Context.getPipeType(ElementType);
5699 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005700 }
5701 llvm_unreachable("Invalid TypeCode!");
5702}
5703
Richard Smith564417a2014-03-20 21:47:22 +00005704void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5705 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005706 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005707 const RecordData &Record, unsigned &Idx) {
5708 ExceptionSpecificationType EST =
5709 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005710 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005711 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005712 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005713 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005714 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005715 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005716 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005717 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005718 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5719 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005720 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005721 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005722 }
5723}
5724
Guy Benyei11169dd2012-12-18 14:30:41 +00005725class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5726 ASTReader &Reader;
5727 ModuleFile &F;
5728 const ASTReader::RecordData &Record;
5729 unsigned &Idx;
5730
5731 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5732 unsigned &I) {
5733 return Reader.ReadSourceLocation(F, R, I);
5734 }
5735
5736 template<typename T>
5737 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5738 return Reader.ReadDeclAs<T>(F, Record, Idx);
5739 }
5740
5741public:
5742 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5743 const ASTReader::RecordData &Record, unsigned &Idx)
5744 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5745 { }
5746
5747 // We want compile-time assurance that we've enumerated all of
5748 // these, so unfortunately we have to declare them first, then
5749 // define them out-of-line.
5750#define ABSTRACT_TYPELOC(CLASS, PARENT)
5751#define TYPELOC(CLASS, PARENT) \
5752 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5753#include "clang/AST/TypeLocNodes.def"
5754
5755 void VisitFunctionTypeLoc(FunctionTypeLoc);
5756 void VisitArrayTypeLoc(ArrayTypeLoc);
5757};
5758
5759void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5760 // nothing to do
5761}
5762void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5763 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5764 if (TL.needsExtraLocalData()) {
5765 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5766 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5767 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5768 TL.setModeAttr(Record[Idx++]);
5769 }
5770}
5771void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5772 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5773}
5774void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5775 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5776}
Reid Kleckner8a365022013-06-24 17:51:48 +00005777void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5778 // nothing to do
5779}
Reid Kleckner0503a872013-12-05 01:23:43 +00005780void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5781 // nothing to do
5782}
Guy Benyei11169dd2012-12-18 14:30:41 +00005783void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5784 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5787 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5788}
5789void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5790 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5791}
5792void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5793 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5794 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5795}
5796void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5797 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5798 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5799 if (Record[Idx++])
5800 TL.setSizeExpr(Reader.ReadExpr(F));
5801 else
Craig Toppera13603a2014-05-22 05:54:18 +00005802 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005803}
5804void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5805 VisitArrayTypeLoc(TL);
5806}
5807void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5808 VisitArrayTypeLoc(TL);
5809}
5810void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5811 VisitArrayTypeLoc(TL);
5812}
5813void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5814 DependentSizedArrayTypeLoc TL) {
5815 VisitArrayTypeLoc(TL);
5816}
5817void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5818 DependentSizedExtVectorTypeLoc TL) {
5819 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5820}
5821void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5822 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5823}
5824void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5825 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5826}
5827void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5828 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5829 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5830 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5831 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005832 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5833 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 }
5835}
5836void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5837 VisitFunctionTypeLoc(TL);
5838}
5839void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5840 VisitFunctionTypeLoc(TL);
5841}
5842void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5843 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5844}
5845void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5846 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5847}
5848void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5849 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5850 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5851 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5852}
5853void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5854 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5855 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5856 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5857 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5858}
5859void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5860 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5861}
5862void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5863 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5864 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5865 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5866 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5867}
5868void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5869 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5870}
5871void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5872 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5873}
5874void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5875 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5876}
5877void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5878 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5879 if (TL.hasAttrOperand()) {
5880 SourceRange range;
5881 range.setBegin(ReadSourceLocation(Record, Idx));
5882 range.setEnd(ReadSourceLocation(Record, Idx));
5883 TL.setAttrOperandParensRange(range);
5884 }
5885 if (TL.hasAttrExprOperand()) {
5886 if (Record[Idx++])
5887 TL.setAttrExprOperand(Reader.ReadExpr(F));
5888 else
Craig Toppera13603a2014-05-22 05:54:18 +00005889 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005890 } else if (TL.hasAttrEnumOperand())
5891 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5892}
5893void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5894 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5895}
5896void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5897 SubstTemplateTypeParmTypeLoc TL) {
5898 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5899}
5900void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5901 SubstTemplateTypeParmPackTypeLoc TL) {
5902 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5903}
5904void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5905 TemplateSpecializationTypeLoc TL) {
5906 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5907 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5908 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5909 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5910 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5911 TL.setArgLocInfo(i,
5912 Reader.GetTemplateArgumentLocInfo(F,
5913 TL.getTypePtr()->getArg(i).getKind(),
5914 Record, Idx));
5915}
5916void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5917 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5918 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5919}
5920void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5921 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5922 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5923}
5924void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5925 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5926}
5927void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5928 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5929 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5930 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5931}
5932void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5933 DependentTemplateSpecializationTypeLoc TL) {
5934 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5935 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5936 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5937 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5938 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5939 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5940 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5941 TL.setArgLocInfo(I,
5942 Reader.GetTemplateArgumentLocInfo(F,
5943 TL.getTypePtr()->getArg(I).getKind(),
5944 Record, Idx));
5945}
5946void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5947 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5948}
5949void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5950 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5951}
5952void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5953 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005954 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5955 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5956 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5957 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5958 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5959 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5961 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5962}
5963void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5964 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5965}
5966void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5967 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5968 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5969 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5970}
Xiuli Pan9c14e282016-01-09 12:53:17 +00005971void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5972 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5973}
Guy Benyei11169dd2012-12-18 14:30:41 +00005974
5975TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5976 const RecordData &Record,
5977 unsigned &Idx) {
5978 QualType InfoTy = readType(F, Record, Idx);
5979 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005980 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005981
5982 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5983 TypeLocReader TLR(*this, F, Record, Idx);
5984 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5985 TLR.Visit(TL);
5986 return TInfo;
5987}
5988
5989QualType ASTReader::GetType(TypeID ID) {
5990 unsigned FastQuals = ID & Qualifiers::FastMask;
5991 unsigned Index = ID >> Qualifiers::FastWidth;
5992
5993 if (Index < NUM_PREDEF_TYPE_IDS) {
5994 QualType T;
5995 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005996 case PREDEF_TYPE_NULL_ID:
5997 return QualType();
5998 case PREDEF_TYPE_VOID_ID:
5999 T = Context.VoidTy;
6000 break;
6001 case PREDEF_TYPE_BOOL_ID:
6002 T = Context.BoolTy;
6003 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006004
6005 case PREDEF_TYPE_CHAR_U_ID:
6006 case PREDEF_TYPE_CHAR_S_ID:
6007 // FIXME: Check that the signedness of CharTy is correct!
6008 T = Context.CharTy;
6009 break;
6010
Alexey Baderbdf7c842015-09-15 12:18:29 +00006011 case PREDEF_TYPE_UCHAR_ID:
6012 T = Context.UnsignedCharTy;
6013 break;
6014 case PREDEF_TYPE_USHORT_ID:
6015 T = Context.UnsignedShortTy;
6016 break;
6017 case PREDEF_TYPE_UINT_ID:
6018 T = Context.UnsignedIntTy;
6019 break;
6020 case PREDEF_TYPE_ULONG_ID:
6021 T = Context.UnsignedLongTy;
6022 break;
6023 case PREDEF_TYPE_ULONGLONG_ID:
6024 T = Context.UnsignedLongLongTy;
6025 break;
6026 case PREDEF_TYPE_UINT128_ID:
6027 T = Context.UnsignedInt128Ty;
6028 break;
6029 case PREDEF_TYPE_SCHAR_ID:
6030 T = Context.SignedCharTy;
6031 break;
6032 case PREDEF_TYPE_WCHAR_ID:
6033 T = Context.WCharTy;
6034 break;
6035 case PREDEF_TYPE_SHORT_ID:
6036 T = Context.ShortTy;
6037 break;
6038 case PREDEF_TYPE_INT_ID:
6039 T = Context.IntTy;
6040 break;
6041 case PREDEF_TYPE_LONG_ID:
6042 T = Context.LongTy;
6043 break;
6044 case PREDEF_TYPE_LONGLONG_ID:
6045 T = Context.LongLongTy;
6046 break;
6047 case PREDEF_TYPE_INT128_ID:
6048 T = Context.Int128Ty;
6049 break;
6050 case PREDEF_TYPE_HALF_ID:
6051 T = Context.HalfTy;
6052 break;
6053 case PREDEF_TYPE_FLOAT_ID:
6054 T = Context.FloatTy;
6055 break;
6056 case PREDEF_TYPE_DOUBLE_ID:
6057 T = Context.DoubleTy;
6058 break;
6059 case PREDEF_TYPE_LONGDOUBLE_ID:
6060 T = Context.LongDoubleTy;
6061 break;
6062 case PREDEF_TYPE_OVERLOAD_ID:
6063 T = Context.OverloadTy;
6064 break;
6065 case PREDEF_TYPE_BOUND_MEMBER:
6066 T = Context.BoundMemberTy;
6067 break;
6068 case PREDEF_TYPE_PSEUDO_OBJECT:
6069 T = Context.PseudoObjectTy;
6070 break;
6071 case PREDEF_TYPE_DEPENDENT_ID:
6072 T = Context.DependentTy;
6073 break;
6074 case PREDEF_TYPE_UNKNOWN_ANY:
6075 T = Context.UnknownAnyTy;
6076 break;
6077 case PREDEF_TYPE_NULLPTR_ID:
6078 T = Context.NullPtrTy;
6079 break;
6080 case PREDEF_TYPE_CHAR16_ID:
6081 T = Context.Char16Ty;
6082 break;
6083 case PREDEF_TYPE_CHAR32_ID:
6084 T = Context.Char32Ty;
6085 break;
6086 case PREDEF_TYPE_OBJC_ID:
6087 T = Context.ObjCBuiltinIdTy;
6088 break;
6089 case PREDEF_TYPE_OBJC_CLASS:
6090 T = Context.ObjCBuiltinClassTy;
6091 break;
6092 case PREDEF_TYPE_OBJC_SEL:
6093 T = Context.ObjCBuiltinSelTy;
6094 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006095#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6096 case PREDEF_TYPE_##Id##_ID: \
6097 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006098 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006099#include "clang/AST/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006100 case PREDEF_TYPE_SAMPLER_ID:
6101 T = Context.OCLSamplerTy;
6102 break;
6103 case PREDEF_TYPE_EVENT_ID:
6104 T = Context.OCLEventTy;
6105 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006106 case PREDEF_TYPE_CLK_EVENT_ID:
6107 T = Context.OCLClkEventTy;
6108 break;
6109 case PREDEF_TYPE_QUEUE_ID:
6110 T = Context.OCLQueueTy;
6111 break;
6112 case PREDEF_TYPE_NDRANGE_ID:
6113 T = Context.OCLNDRangeTy;
6114 break;
6115 case PREDEF_TYPE_RESERVE_ID_ID:
6116 T = Context.OCLReserveIDTy;
6117 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006118 case PREDEF_TYPE_AUTO_DEDUCT:
6119 T = Context.getAutoDeductType();
6120 break;
6121
6122 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6123 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 break;
6125
6126 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6127 T = Context.ARCUnbridgedCastTy;
6128 break;
6129
Guy Benyei11169dd2012-12-18 14:30:41 +00006130 case PREDEF_TYPE_BUILTIN_FN:
6131 T = Context.BuiltinFnTy;
6132 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006133
6134 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6135 T = Context.OMPArraySectionTy;
6136 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 }
6138
6139 assert(!T.isNull() && "Unknown predefined type");
6140 return T.withFastQualifiers(FastQuals);
6141 }
6142
6143 Index -= NUM_PREDEF_TYPE_IDS;
6144 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6145 if (TypesLoaded[Index].isNull()) {
6146 TypesLoaded[Index] = readTypeRecord(Index);
6147 if (TypesLoaded[Index].isNull())
6148 return QualType();
6149
6150 TypesLoaded[Index]->setFromAST();
6151 if (DeserializationListener)
6152 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6153 TypesLoaded[Index]);
6154 }
6155
6156 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6157}
6158
6159QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6160 return GetType(getGlobalTypeID(F, LocalID));
6161}
6162
6163serialization::TypeID
6164ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6165 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6166 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6167
6168 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6169 return LocalID;
6170
6171 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6172 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6173 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6174
6175 unsigned GlobalIndex = LocalIndex + I->second;
6176 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6177}
6178
6179TemplateArgumentLocInfo
6180ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6181 TemplateArgument::ArgKind Kind,
6182 const RecordData &Record,
6183 unsigned &Index) {
6184 switch (Kind) {
6185 case TemplateArgument::Expression:
6186 return ReadExpr(F);
6187 case TemplateArgument::Type:
6188 return GetTypeSourceInfo(F, Record, Index);
6189 case TemplateArgument::Template: {
6190 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6191 Index);
6192 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6193 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6194 SourceLocation());
6195 }
6196 case TemplateArgument::TemplateExpansion: {
6197 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6198 Index);
6199 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6200 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6201 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6202 EllipsisLoc);
6203 }
6204 case TemplateArgument::Null:
6205 case TemplateArgument::Integral:
6206 case TemplateArgument::Declaration:
6207 case TemplateArgument::NullPtr:
6208 case TemplateArgument::Pack:
6209 // FIXME: Is this right?
6210 return TemplateArgumentLocInfo();
6211 }
6212 llvm_unreachable("unexpected template argument loc");
6213}
6214
6215TemplateArgumentLoc
6216ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6217 const RecordData &Record, unsigned &Index) {
6218 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6219
6220 if (Arg.getKind() == TemplateArgument::Expression) {
6221 if (Record[Index++]) // bool InfoHasSameExpr.
6222 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6223 }
6224 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6225 Record, Index));
6226}
6227
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006228const ASTTemplateArgumentListInfo*
6229ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6230 const RecordData &Record,
6231 unsigned &Index) {
6232 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6233 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6234 unsigned NumArgsAsWritten = Record[Index++];
6235 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6236 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6237 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6238 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6239}
6240
Guy Benyei11169dd2012-12-18 14:30:41 +00006241Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6242 return GetDecl(ID);
6243}
6244
Richard Smith50895422015-01-31 03:04:55 +00006245template<typename TemplateSpecializationDecl>
6246static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6247 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6248 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6249}
6250
Richard Smith053f6c62014-05-16 23:01:30 +00006251void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006252 if (NumCurrentElementsDeserializing) {
6253 // We arrange to not care about the complete redeclaration chain while we're
6254 // deserializing. Just remember that the AST has marked this one as complete
6255 // but that it's not actually complete yet, so we know we still need to
6256 // complete it later.
6257 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6258 return;
6259 }
6260
Richard Smith053f6c62014-05-16 23:01:30 +00006261 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6262
Richard Smith053f6c62014-05-16 23:01:30 +00006263 // If this is a named declaration, complete it by looking it up
6264 // within its context.
6265 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006266 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006267 // all mergeable entities within it.
6268 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6269 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6270 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006271 if (!getContext().getLangOpts().CPlusPlus &&
6272 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006273 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006274 // the identifier instead. (For C++ modules, we don't store decls
6275 // in the serialized identifier table, so we do the lookup in the TU.)
6276 auto *II = Name.getAsIdentifierInfo();
6277 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006278 if (II->isOutOfDate())
6279 updateOutOfDateIdentifier(*II);
6280 } else
6281 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006282 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006283 // Find all declarations of this kind from the relevant context.
6284 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6285 auto *DC = cast<DeclContext>(DCDecl);
6286 SmallVector<Decl*, 8> Decls;
6287 FindExternalLexicalDecls(
6288 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6289 }
Richard Smith053f6c62014-05-16 23:01:30 +00006290 }
6291 }
Richard Smith50895422015-01-31 03:04:55 +00006292
6293 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6294 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6295 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6296 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6297 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6298 if (auto *Template = FD->getPrimaryTemplate())
6299 Template->LoadLazySpecializations();
6300 }
Richard Smith053f6c62014-05-16 23:01:30 +00006301}
6302
Richard Smithc2bb8182015-03-24 06:36:48 +00006303uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6304 const RecordData &Record,
6305 unsigned &Idx) {
6306 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6307 Error("malformed AST file: missing C++ ctor initializers");
6308 return 0;
6309 }
6310
6311 unsigned LocalID = Record[Idx++];
6312 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6313}
6314
6315CXXCtorInitializer **
6316ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6317 RecordLocation Loc = getLocalBitOffset(Offset);
6318 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6319 SavedStreamPosition SavedPosition(Cursor);
6320 Cursor.JumpToBit(Loc.Offset);
6321 ReadingKindTracker ReadingKind(Read_Decl, *this);
6322
6323 RecordData Record;
6324 unsigned Code = Cursor.ReadCode();
6325 unsigned RecCode = Cursor.readRecord(Code, Record);
6326 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6327 Error("malformed AST file: missing C++ ctor initializers");
6328 return nullptr;
6329 }
6330
6331 unsigned Idx = 0;
6332 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6333}
6334
Richard Smithcd45dbc2014-04-19 03:48:30 +00006335uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6336 const RecordData &Record,
6337 unsigned &Idx) {
6338 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6339 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006341 }
6342
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 unsigned LocalID = Record[Idx++];
6344 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6345}
6346
6347CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6348 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006349 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006350 SavedStreamPosition SavedPosition(Cursor);
6351 Cursor.JumpToBit(Loc.Offset);
6352 ReadingKindTracker ReadingKind(Read_Decl, *this);
6353 RecordData Record;
6354 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006355 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006357 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006358 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006359 }
6360
6361 unsigned Idx = 0;
6362 unsigned NumBases = Record[Idx++];
6363 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6364 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6365 for (unsigned I = 0; I != NumBases; ++I)
6366 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6367 return Bases;
6368}
6369
6370serialization::DeclID
6371ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6372 if (LocalID < NUM_PREDEF_DECL_IDS)
6373 return LocalID;
6374
6375 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6376 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6377 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6378
6379 return LocalID + I->second;
6380}
6381
6382bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6383 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006384 // Predefined decls aren't from any module.
6385 if (ID < NUM_PREDEF_DECL_IDS)
6386 return false;
6387
Richard Smithbcda1a92015-07-12 23:51:20 +00006388 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6389 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006390}
6391
Douglas Gregor9f782892013-01-21 15:25:38 +00006392ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006394 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6396 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6397 return I->second;
6398}
6399
6400SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6401 if (ID < NUM_PREDEF_DECL_IDS)
6402 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006403
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6405
6406 if (Index > DeclsLoaded.size()) {
6407 Error("declaration ID out-of-range for AST file");
6408 return SourceLocation();
6409 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006410
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 if (Decl *D = DeclsLoaded[Index])
6412 return D->getLocation();
6413
Richard Smithcb34bd32016-03-27 07:28:06 +00006414 SourceLocation Loc;
6415 DeclCursorForID(ID, Loc);
6416 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006417}
6418
Richard Smithfe620d22015-03-05 23:24:12 +00006419static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6420 switch (ID) {
6421 case PREDEF_DECL_NULL_ID:
6422 return nullptr;
6423
6424 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6425 return Context.getTranslationUnitDecl();
6426
6427 case PREDEF_DECL_OBJC_ID_ID:
6428 return Context.getObjCIdDecl();
6429
6430 case PREDEF_DECL_OBJC_SEL_ID:
6431 return Context.getObjCSelDecl();
6432
6433 case PREDEF_DECL_OBJC_CLASS_ID:
6434 return Context.getObjCClassDecl();
6435
6436 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6437 return Context.getObjCProtocolDecl();
6438
6439 case PREDEF_DECL_INT_128_ID:
6440 return Context.getInt128Decl();
6441
6442 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6443 return Context.getUInt128Decl();
6444
6445 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6446 return Context.getObjCInstanceTypeDecl();
6447
6448 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6449 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006450
Richard Smith9b88a4c2015-07-27 05:40:23 +00006451 case PREDEF_DECL_VA_LIST_TAG:
6452 return Context.getVaListTagDecl();
6453
Charles Davisc7d5c942015-09-17 20:55:33 +00006454 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6455 return Context.getBuiltinMSVaListDecl();
6456
Richard Smithf19e1272015-03-07 00:04:49 +00006457 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6458 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006459
6460 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6461 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006462
6463 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6464 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006465
6466 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6467 return Context.getCFConstantStringTagDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006468 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006469 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006470}
6471
Richard Smithcd45dbc2014-04-19 03:48:30 +00006472Decl *ASTReader::GetExistingDecl(DeclID ID) {
6473 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006474 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6475 if (D) {
6476 // Track that we have merged the declaration with ID \p ID into the
6477 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006478 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006479 if (Merged.empty())
6480 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 }
Richard Smithfe620d22015-03-05 23:24:12 +00006482 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006483 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006484
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6486
6487 if (Index >= DeclsLoaded.size()) {
6488 assert(0 && "declaration ID out-of-range for AST file");
6489 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006490 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006492
6493 return DeclsLoaded[Index];
6494}
6495
6496Decl *ASTReader::GetDecl(DeclID ID) {
6497 if (ID < NUM_PREDEF_DECL_IDS)
6498 return GetExistingDecl(ID);
6499
6500 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6501
6502 if (Index >= DeclsLoaded.size()) {
6503 assert(0 && "declaration ID out-of-range for AST file");
6504 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006505 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006506 }
6507
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 if (!DeclsLoaded[Index]) {
6509 ReadDeclRecord(ID);
6510 if (DeserializationListener)
6511 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6512 }
6513
6514 return DeclsLoaded[Index];
6515}
6516
6517DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6518 DeclID GlobalID) {
6519 if (GlobalID < NUM_PREDEF_DECL_IDS)
6520 return GlobalID;
6521
6522 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6523 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6524 ModuleFile *Owner = I->second;
6525
6526 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6527 = M.GlobalToLocalDeclIDs.find(Owner);
6528 if (Pos == M.GlobalToLocalDeclIDs.end())
6529 return 0;
6530
6531 return GlobalID - Owner->BaseDeclID + Pos->second;
6532}
6533
6534serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6535 const RecordData &Record,
6536 unsigned &Idx) {
6537 if (Idx >= Record.size()) {
6538 Error("Corrupted AST file");
6539 return 0;
6540 }
6541
6542 return getGlobalDeclID(F, Record[Idx++]);
6543}
6544
6545/// \brief Resolve the offset of a statement into a statement.
6546///
6547/// This operation will read a new statement from the external
6548/// source each time it is called, and is meant to be used via a
6549/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6550Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6551 // Switch case IDs are per Decl.
6552 ClearSwitchCaseIDs();
6553
6554 // Offset here is a global offset across the entire chain.
6555 RecordLocation Loc = getLocalBitOffset(Offset);
6556 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6557 return ReadStmtFromStream(*Loc.F);
6558}
6559
Richard Smith3cb15722015-08-05 22:41:45 +00006560void ASTReader::FindExternalLexicalDecls(
6561 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6562 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006563 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6564
Richard Smith9ccdd932015-08-06 22:14:12 +00006565 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006566 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6567 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6568 auto K = (Decl::Kind)+LexicalDecls[I];
6569 if (!IsKindWeWant(K))
6570 continue;
6571
6572 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6573
6574 // Don't add predefined declarations to the lexical context more
6575 // than once.
6576 if (ID < NUM_PREDEF_DECL_IDS) {
6577 if (PredefsVisited[ID])
6578 continue;
6579
6580 PredefsVisited[ID] = true;
6581 }
6582
6583 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006584 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006585 if (!DC->isDeclInLexicalTraversal(D))
6586 Decls.push_back(D);
6587 }
6588 }
6589 };
6590
6591 if (isa<TranslationUnitDecl>(DC)) {
6592 for (auto Lexical : TULexicalDecls)
6593 Visit(Lexical.first, Lexical.second);
6594 } else {
6595 auto I = LexicalDecls.find(DC);
6596 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006597 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006598 }
6599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006601}
6602
6603namespace {
6604
6605class DeclIDComp {
6606 ASTReader &Reader;
6607 ModuleFile &Mod;
6608
6609public:
6610 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6611
6612 bool operator()(LocalDeclID L, LocalDeclID R) const {
6613 SourceLocation LHS = getLocation(L);
6614 SourceLocation RHS = getLocation(R);
6615 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6616 }
6617
6618 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6619 SourceLocation RHS = getLocation(R);
6620 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6621 }
6622
6623 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6624 SourceLocation LHS = getLocation(L);
6625 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6626 }
6627
6628 SourceLocation getLocation(LocalDeclID ID) const {
6629 return Reader.getSourceManager().getFileLoc(
6630 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6631 }
6632};
6633
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006634}
Guy Benyei11169dd2012-12-18 14:30:41 +00006635
6636void ASTReader::FindFileRegionDecls(FileID File,
6637 unsigned Offset, unsigned Length,
6638 SmallVectorImpl<Decl *> &Decls) {
6639 SourceManager &SM = getSourceManager();
6640
6641 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6642 if (I == FileDeclIDs.end())
6643 return;
6644
6645 FileDeclsInfo &DInfo = I->second;
6646 if (DInfo.Decls.empty())
6647 return;
6648
6649 SourceLocation
6650 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6651 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6652
6653 DeclIDComp DIDComp(*this, *DInfo.Mod);
6654 ArrayRef<serialization::LocalDeclID>::iterator
6655 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6656 BeginLoc, DIDComp);
6657 if (BeginIt != DInfo.Decls.begin())
6658 --BeginIt;
6659
6660 // If we are pointing at a top-level decl inside an objc container, we need
6661 // to backtrack until we find it otherwise we will fail to report that the
6662 // region overlaps with an objc container.
6663 while (BeginIt != DInfo.Decls.begin() &&
6664 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6665 ->isTopLevelDeclInObjCContainer())
6666 --BeginIt;
6667
6668 ArrayRef<serialization::LocalDeclID>::iterator
6669 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6670 EndLoc, DIDComp);
6671 if (EndIt != DInfo.Decls.end())
6672 ++EndIt;
6673
6674 for (ArrayRef<serialization::LocalDeclID>::iterator
6675 DIt = BeginIt; DIt != EndIt; ++DIt)
6676 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6677}
6678
Richard Smith9ce12e32013-02-07 03:30:24 +00006679bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006680ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6681 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006682 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 "DeclContext has no visible decls in storage");
6684 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006685 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006686
Richard Smithd88a7f12015-09-01 20:35:42 +00006687 auto It = Lookups.find(DC);
6688 if (It == Lookups.end())
6689 return false;
6690
Richard Smith8c913ec2014-08-14 02:21:01 +00006691 Deserializing LookupResults(this);
6692
Richard Smithd88a7f12015-09-01 20:35:42 +00006693 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006695 for (DeclID ID : It->second.Table.find(Name)) {
6696 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6697 if (ND->getDeclName() == Name)
6698 Decls.push_back(ND);
6699 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006700
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 ++NumVisibleDeclContextsRead;
6702 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006703 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006704}
6705
Guy Benyei11169dd2012-12-18 14:30:41 +00006706void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6707 if (!DC->hasExternalVisibleStorage())
6708 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006709
6710 auto It = Lookups.find(DC);
6711 assert(It != Lookups.end() &&
6712 "have external visible storage but no lookup tables");
6713
Craig Topper79be4cd2013-07-05 04:33:53 +00006714 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006715
Richard Smithd88a7f12015-09-01 20:35:42 +00006716 for (DeclID ID : It->second.Table.findAll()) {
6717 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6718 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006719 }
6720
Guy Benyei11169dd2012-12-18 14:30:41 +00006721 ++NumVisibleDeclContextsRead;
6722
Craig Topper79be4cd2013-07-05 04:33:53 +00006723 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6725 }
6726 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6727}
6728
Richard Smithd88a7f12015-09-01 20:35:42 +00006729const serialization::reader::DeclContextLookupTable *
6730ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6731 auto I = Lookups.find(Primary);
6732 return I == Lookups.end() ? nullptr : &I->second;
6733}
6734
Guy Benyei11169dd2012-12-18 14:30:41 +00006735/// \brief Under non-PCH compilation the consumer receives the objc methods
6736/// before receiving the implementation, and codegen depends on this.
6737/// We simulate this by deserializing and passing to consumer the methods of the
6738/// implementation before passing the deserialized implementation decl.
6739static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6740 ASTConsumer *Consumer) {
6741 assert(ImplD && Consumer);
6742
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006743 for (auto *I : ImplD->methods())
6744 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006745
6746 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6747}
6748
6749void ASTReader::PassInterestingDeclsToConsumer() {
6750 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006751
6752 if (PassingDeclsToConsumer)
6753 return;
6754
6755 // Guard variable to avoid recursively redoing the process of passing
6756 // decls to consumer.
6757 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6758 true);
6759
Richard Smith9e2341d2015-03-23 03:25:59 +00006760 // Ensure that we've loaded all potentially-interesting declarations
6761 // that need to be eagerly loaded.
6762 for (auto ID : EagerlyDeserializedDecls)
6763 GetDecl(ID);
6764 EagerlyDeserializedDecls.clear();
6765
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 while (!InterestingDecls.empty()) {
6767 Decl *D = InterestingDecls.front();
6768 InterestingDecls.pop_front();
6769
6770 PassInterestingDeclToConsumer(D);
6771 }
6772}
6773
6774void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6775 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6776 PassObjCImplDeclToConsumer(ImplD, Consumer);
6777 else
6778 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6779}
6780
6781void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6782 this->Consumer = Consumer;
6783
Richard Smith9e2341d2015-03-23 03:25:59 +00006784 if (Consumer)
6785 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006786
6787 if (DeserializationListener)
6788 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006789}
6790
6791void ASTReader::PrintStats() {
6792 std::fprintf(stderr, "*** AST File Statistics:\n");
6793
6794 unsigned NumTypesLoaded
6795 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6796 QualType());
6797 unsigned NumDeclsLoaded
6798 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006799 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006800 unsigned NumIdentifiersLoaded
6801 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6802 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006803 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 unsigned NumMacrosLoaded
6805 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6806 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006807 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 unsigned NumSelectorsLoaded
6809 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6810 SelectorsLoaded.end(),
6811 Selector());
6812
6813 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6814 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6815 NumSLocEntriesRead, TotalNumSLocEntries,
6816 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6817 if (!TypesLoaded.empty())
6818 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6819 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6820 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6821 if (!DeclsLoaded.empty())
6822 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6823 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6824 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6825 if (!IdentifiersLoaded.empty())
6826 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6827 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6828 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6829 if (!MacrosLoaded.empty())
6830 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6831 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6832 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6833 if (!SelectorsLoaded.empty())
6834 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6835 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6836 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6837 if (TotalNumStatements)
6838 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6839 NumStatementsRead, TotalNumStatements,
6840 ((float)NumStatementsRead/TotalNumStatements * 100));
6841 if (TotalNumMacros)
6842 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6843 NumMacrosRead, TotalNumMacros,
6844 ((float)NumMacrosRead/TotalNumMacros * 100));
6845 if (TotalLexicalDeclContexts)
6846 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6847 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6848 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6849 * 100));
6850 if (TotalVisibleDeclContexts)
6851 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6852 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6853 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6854 * 100));
6855 if (TotalNumMethodPoolEntries) {
6856 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6857 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6858 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6859 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006861 if (NumMethodPoolLookups) {
6862 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6863 NumMethodPoolHits, NumMethodPoolLookups,
6864 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6865 }
6866 if (NumMethodPoolTableLookups) {
6867 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6868 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6869 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6870 * 100.0));
6871 }
6872
Douglas Gregor00a50f72013-01-25 00:38:33 +00006873 if (NumIdentifierLookupHits) {
6874 std::fprintf(stderr,
6875 " %u / %u identifier table lookups succeeded (%f%%)\n",
6876 NumIdentifierLookupHits, NumIdentifierLookups,
6877 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6878 }
6879
Douglas Gregore060e572013-01-25 01:03:03 +00006880 if (GlobalIndex) {
6881 std::fprintf(stderr, "\n");
6882 GlobalIndex->printStats();
6883 }
6884
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 std::fprintf(stderr, "\n");
6886 dump();
6887 std::fprintf(stderr, "\n");
6888}
6889
6890template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6891static void
6892dumpModuleIDMap(StringRef Name,
6893 const ContinuousRangeMap<Key, ModuleFile *,
6894 InitialCapacity> &Map) {
6895 if (Map.begin() == Map.end())
6896 return;
6897
6898 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6899 llvm::errs() << Name << ":\n";
6900 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6901 I != IEnd; ++I) {
6902 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6903 << "\n";
6904 }
6905}
6906
Yaron Kerencdae9412016-01-29 19:38:18 +00006907LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6909 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6910 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6911 dumpModuleIDMap("Global type map", GlobalTypeMap);
6912 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6913 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6914 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6915 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6916 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6917 dumpModuleIDMap("Global preprocessed entity map",
6918 GlobalPreprocessedEntityMap);
6919
6920 llvm::errs() << "\n*** PCH/Modules Loaded:";
6921 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6922 MEnd = ModuleMgr.end();
6923 M != MEnd; ++M)
6924 (*M)->dump();
6925}
6926
6927/// Return the amount of memory used by memory buffers, breaking down
6928/// by heap-backed versus mmap'ed memory.
6929void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6930 for (ModuleConstIterator I = ModuleMgr.begin(),
6931 E = ModuleMgr.end(); I != E; ++I) {
6932 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6933 size_t bytes = buf->getBufferSize();
6934 switch (buf->getBufferKind()) {
6935 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6936 sizes.malloc_bytes += bytes;
6937 break;
6938 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6939 sizes.mmap_bytes += bytes;
6940 break;
6941 }
6942 }
6943 }
6944}
6945
6946void ASTReader::InitializeSema(Sema &S) {
6947 SemaObj = &S;
6948 S.addExternalSource(this);
6949
6950 // Makes sure any declarations that were deserialized "too early"
6951 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006952 for (uint64_t ID : PreloadedDeclIDs) {
6953 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6954 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006956 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006957
Richard Smith3d8e97e2013-10-18 06:54:39 +00006958 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 if (!FPPragmaOptions.empty()) {
6960 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6961 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6962 }
6963
Richard Smith3d8e97e2013-10-18 06:54:39 +00006964 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 if (!OpenCLExtensions.empty()) {
6966 unsigned I = 0;
6967#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6968#include "clang/Basic/OpenCLExtensions.def"
6969
6970 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6971 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006972
6973 UpdateSema();
6974}
6975
6976void ASTReader::UpdateSema() {
6977 assert(SemaObj && "no Sema to update");
6978
6979 // Load the offsets of the declarations that Sema references.
6980 // They will be lazily deserialized when needed.
6981 if (!SemaDeclRefs.empty()) {
6982 assert(SemaDeclRefs.size() % 2 == 0);
6983 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6984 if (!SemaObj->StdNamespace)
6985 SemaObj->StdNamespace = SemaDeclRefs[I];
6986 if (!SemaObj->StdBadAlloc)
6987 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6988 }
6989 SemaDeclRefs.clear();
6990 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006991
Nico Weber779355f2016-03-02 23:22:00 +00006992 // Update the state of pragmas. Use the same API as if we had encountered the
6993 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00006994 if(OptimizeOffPragmaLocation.isValid())
6995 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00006996 if (PragmaMSStructState != -1)
6997 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00006998 if (PointersToMembersPragmaLocation.isValid()) {
6999 SemaObj->ActOnPragmaMSPointersToMembers(
7000 (LangOptions::PragmaMSPointersToMembersKind)
7001 PragmaMSPointersToMembersState,
7002 PointersToMembersPragmaLocation);
7003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007004}
7005
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007006IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 // Note that we are loading an identifier.
7008 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007009
Douglas Gregor7211ac12013-01-25 23:32:03 +00007010 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007011 NumIdentifierLookups,
7012 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007013
7014 // We don't need to do identifier table lookups in C++ modules (we preload
7015 // all interesting declarations, and don't need to use the scope for name
7016 // lookups). Perform the lookup in PCH files, though, since we don't build
7017 // a complete initial identifier table if we're carrying on from a PCH.
7018 if (Context.getLangOpts().CPlusPlus) {
7019 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007020 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007021 break;
7022 } else {
7023 // If there is a global index, look there first to determine which modules
7024 // provably do not have any results for this identifier.
7025 GlobalModuleIndex::HitSet Hits;
7026 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7027 if (!loadGlobalIndex()) {
7028 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7029 HitsPtr = &Hits;
7030 }
7031 }
7032
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007033 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007034 }
7035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 IdentifierInfo *II = Visitor.getIdentifierInfo();
7037 markIdentifierUpToDate(II);
7038 return II;
7039}
7040
7041namespace clang {
7042 /// \brief An identifier-lookup iterator that enumerates all of the
7043 /// identifiers stored within a set of AST files.
7044 class ASTIdentifierIterator : public IdentifierIterator {
7045 /// \brief The AST reader whose identifiers are being enumerated.
7046 const ASTReader &Reader;
7047
7048 /// \brief The current index into the chain of AST files stored in
7049 /// the AST reader.
7050 unsigned Index;
7051
7052 /// \brief The current position within the identifier lookup table
7053 /// of the current AST file.
7054 ASTIdentifierLookupTable::key_iterator Current;
7055
7056 /// \brief The end position within the identifier lookup table of
7057 /// the current AST file.
7058 ASTIdentifierLookupTable::key_iterator End;
7059
7060 public:
7061 explicit ASTIdentifierIterator(const ASTReader &Reader);
7062
Craig Topper3e89dfe2014-03-13 02:13:41 +00007063 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007065}
Guy Benyei11169dd2012-12-18 14:30:41 +00007066
7067ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7068 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7069 ASTIdentifierLookupTable *IdTable
7070 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7071 Current = IdTable->key_begin();
7072 End = IdTable->key_end();
7073}
7074
7075StringRef ASTIdentifierIterator::Next() {
7076 while (Current == End) {
7077 // If we have exhausted all of our AST files, we're done.
7078 if (Index == 0)
7079 return StringRef();
7080
7081 --Index;
7082 ASTIdentifierLookupTable *IdTable
7083 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7084 IdentifierLookupTable;
7085 Current = IdTable->key_begin();
7086 End = IdTable->key_end();
7087 }
7088
7089 // We have any identifiers remaining in the current AST file; return
7090 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007091 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007093 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007094}
7095
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007096IdentifierIterator *ASTReader::getIdentifiers() {
7097 if (!loadGlobalIndex())
7098 return GlobalIndex->createIdentifierIterator();
7099
Guy Benyei11169dd2012-12-18 14:30:41 +00007100 return new ASTIdentifierIterator(*this);
7101}
7102
7103namespace clang { namespace serialization {
7104 class ReadMethodPoolVisitor {
7105 ASTReader &Reader;
7106 Selector Sel;
7107 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007108 unsigned InstanceBits;
7109 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007110 bool InstanceHasMoreThanOneDecl;
7111 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007112 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7113 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007114
7115 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007116 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007118 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007119 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7120 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007121
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007122 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 if (!M.SelectorLookupTable)
7124 return false;
7125
7126 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007127 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 return true;
7129
Richard Smithbdf2d932015-07-30 03:37:16 +00007130 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 ASTSelectorLookupTable *PoolTable
7132 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007133 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 if (Pos == PoolTable->end())
7135 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007136
Richard Smithbdf2d932015-07-30 03:37:16 +00007137 ++Reader.NumMethodPoolTableHits;
7138 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 // FIXME: Not quite happy with the statistics here. We probably should
7140 // disable this tracking when called via LoadSelector.
7141 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007142 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007144 if (Reader.DeserializationListener)
7145 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007146
Richard Smithbdf2d932015-07-30 03:37:16 +00007147 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7148 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7149 InstanceBits = Data.InstanceBits;
7150 FactoryBits = Data.FactoryBits;
7151 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7152 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 return true;
7154 }
7155
7156 /// \brief Retrieve the instance methods found by this visitor.
7157 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7158 return InstanceMethods;
7159 }
7160
7161 /// \brief Retrieve the instance methods found by this visitor.
7162 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7163 return FactoryMethods;
7164 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007165
7166 unsigned getInstanceBits() const { return InstanceBits; }
7167 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007168 bool instanceHasMoreThanOneDecl() const {
7169 return InstanceHasMoreThanOneDecl;
7170 }
7171 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007173} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007174
7175/// \brief Add the given set of methods to the method list.
7176static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7177 ObjCMethodList &List) {
7178 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7179 S.addMethodToGlobalList(&List, Methods[I]);
7180 }
7181}
7182
7183void ASTReader::ReadMethodPool(Selector Sel) {
7184 // Get the selector generation and update it to the current generation.
7185 unsigned &Generation = SelectorGeneration[Sel];
7186 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007187 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007188
7189 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007190 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007192 ModuleMgr.visit(Visitor);
7193
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007195 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007197
7198 ++NumMethodPoolHits;
7199
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 if (!getSema())
7201 return;
7202
7203 Sema &S = *getSema();
7204 Sema::GlobalMethodPool::iterator Pos
7205 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007206
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007207 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007208 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007209 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007210 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007211
7212 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7213 // when building a module we keep every method individually and may need to
7214 // update hasMoreThanOneDecl as we add the methods.
7215 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7216 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007217}
7218
7219void ASTReader::ReadKnownNamespaces(
7220 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7221 Namespaces.clear();
7222
7223 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7224 if (NamespaceDecl *Namespace
7225 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7226 Namespaces.push_back(Namespace);
7227 }
7228}
7229
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007230void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007231 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007232 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7233 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007234 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007235 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007236 Undefined.insert(std::make_pair(D, Loc));
7237 }
7238}
Nick Lewycky8334af82013-01-26 00:35:08 +00007239
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007240void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7241 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7242 Exprs) {
7243 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7244 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7245 uint64_t Count = DelayedDeleteExprs[Idx++];
7246 for (uint64_t C = 0; C < Count; ++C) {
7247 SourceLocation DeleteLoc =
7248 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7249 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7250 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7251 }
7252 }
7253}
7254
Guy Benyei11169dd2012-12-18 14:30:41 +00007255void ASTReader::ReadTentativeDefinitions(
7256 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7257 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7258 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7259 if (Var)
7260 TentativeDefs.push_back(Var);
7261 }
7262 TentativeDefinitions.clear();
7263}
7264
7265void ASTReader::ReadUnusedFileScopedDecls(
7266 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7267 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7268 DeclaratorDecl *D
7269 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7270 if (D)
7271 Decls.push_back(D);
7272 }
7273 UnusedFileScopedDecls.clear();
7274}
7275
7276void ASTReader::ReadDelegatingConstructors(
7277 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7278 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7279 CXXConstructorDecl *D
7280 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7281 if (D)
7282 Decls.push_back(D);
7283 }
7284 DelegatingCtorDecls.clear();
7285}
7286
7287void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7288 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7289 TypedefNameDecl *D
7290 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7291 if (D)
7292 Decls.push_back(D);
7293 }
7294 ExtVectorDecls.clear();
7295}
7296
Nico Weber72889432014-09-06 01:25:55 +00007297void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7298 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7299 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7300 ++I) {
7301 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7302 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7303 if (D)
7304 Decls.insert(D);
7305 }
7306 UnusedLocalTypedefNameCandidates.clear();
7307}
7308
Guy Benyei11169dd2012-12-18 14:30:41 +00007309void ASTReader::ReadReferencedSelectors(
7310 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7311 if (ReferencedSelectorsData.empty())
7312 return;
7313
7314 // If there are @selector references added them to its pool. This is for
7315 // implementation of -Wselector.
7316 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7317 unsigned I = 0;
7318 while (I < DataSize) {
7319 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7320 SourceLocation SelLoc
7321 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7322 Sels.push_back(std::make_pair(Sel, SelLoc));
7323 }
7324 ReferencedSelectorsData.clear();
7325}
7326
7327void ASTReader::ReadWeakUndeclaredIdentifiers(
7328 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7329 if (WeakUndeclaredIdentifiers.empty())
7330 return;
7331
7332 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7333 IdentifierInfo *WeakId
7334 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7335 IdentifierInfo *AliasId
7336 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7337 SourceLocation Loc
7338 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7339 bool Used = WeakUndeclaredIdentifiers[I++];
7340 WeakInfo WI(AliasId, Loc);
7341 WI.setUsed(Used);
7342 WeakIDs.push_back(std::make_pair(WeakId, WI));
7343 }
7344 WeakUndeclaredIdentifiers.clear();
7345}
7346
7347void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7348 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7349 ExternalVTableUse VT;
7350 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7351 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7352 VT.DefinitionRequired = VTableUses[Idx++];
7353 VTables.push_back(VT);
7354 }
7355
7356 VTableUses.clear();
7357}
7358
7359void ASTReader::ReadPendingInstantiations(
7360 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7361 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7362 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7363 SourceLocation Loc
7364 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7365
7366 Pending.push_back(std::make_pair(D, Loc));
7367 }
7368 PendingInstantiations.clear();
7369}
7370
Richard Smithe40f2ba2013-08-07 21:41:30 +00007371void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007372 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007373 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7374 /* In loop */) {
7375 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7376
7377 LateParsedTemplate *LT = new LateParsedTemplate;
7378 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7379
7380 ModuleFile *F = getOwningModuleFile(LT->D);
7381 assert(F && "No module");
7382
7383 unsigned TokN = LateParsedTemplates[Idx++];
7384 LT->Toks.reserve(TokN);
7385 for (unsigned T = 0; T < TokN; ++T)
7386 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7387
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007388 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007389 }
7390
7391 LateParsedTemplates.clear();
7392}
7393
Guy Benyei11169dd2012-12-18 14:30:41 +00007394void ASTReader::LoadSelector(Selector Sel) {
7395 // It would be complicated to avoid reading the methods anyway. So don't.
7396 ReadMethodPool(Sel);
7397}
7398
7399void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7400 assert(ID && "Non-zero identifier ID required");
7401 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7402 IdentifiersLoaded[ID - 1] = II;
7403 if (DeserializationListener)
7404 DeserializationListener->IdentifierRead(ID, II);
7405}
7406
7407/// \brief Set the globally-visible declarations associated with the given
7408/// identifier.
7409///
7410/// If the AST reader is currently in a state where the given declaration IDs
7411/// cannot safely be resolved, they are queued until it is safe to resolve
7412/// them.
7413///
7414/// \param II an IdentifierInfo that refers to one or more globally-visible
7415/// declarations.
7416///
7417/// \param DeclIDs the set of declaration IDs with the name @p II that are
7418/// visible at global scope.
7419///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007420/// \param Decls if non-null, this vector will be populated with the set of
7421/// deserialized declarations. These declarations will not be pushed into
7422/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007423void
7424ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7425 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007426 SmallVectorImpl<Decl *> *Decls) {
7427 if (NumCurrentElementsDeserializing && !Decls) {
7428 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007429 return;
7430 }
7431
7432 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007433 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 // Queue this declaration so that it will be added to the
7435 // translation unit scope and identifier's declaration chain
7436 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007437 PreloadedDeclIDs.push_back(DeclIDs[I]);
7438 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007440
7441 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7442
7443 // If we're simply supposed to record the declarations, do so now.
7444 if (Decls) {
7445 Decls->push_back(D);
7446 continue;
7447 }
7448
7449 // Introduce this declaration into the translation-unit scope
7450 // and add it to the declaration chain for this identifier, so
7451 // that (unqualified) name lookup will find it.
7452 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 }
7454}
7455
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007456IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007458 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007459
7460 if (IdentifiersLoaded.empty()) {
7461 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007462 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007463 }
7464
7465 ID -= 1;
7466 if (!IdentifiersLoaded[ID]) {
7467 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7468 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7469 ModuleFile *M = I->second;
7470 unsigned Index = ID - M->BaseIdentifierID;
7471 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7472
7473 // All of the strings in the AST file are preceded by a 16-bit length.
7474 // Extract that 16-bit length to avoid having to execute strlen().
7475 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7476 // unsigned integers. This is important to avoid integer overflow when
7477 // we cast them to 'unsigned'.
7478 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7479 unsigned StrLen = (((unsigned) StrLenPtr[0])
7480 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007481 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7482 IdentifiersLoaded[ID] = &II;
7483 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007484 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007485 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 }
7487
7488 return IdentifiersLoaded[ID];
7489}
7490
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007491IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7492 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007493}
7494
7495IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7496 if (LocalID < NUM_PREDEF_IDENT_IDS)
7497 return LocalID;
7498
7499 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7500 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7501 assert(I != M.IdentifierRemap.end()
7502 && "Invalid index into identifier index remap");
7503
7504 return LocalID + I->second;
7505}
7506
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007507MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007509 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007510
7511 if (MacrosLoaded.empty()) {
7512 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007513 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 }
7515
7516 ID -= NUM_PREDEF_MACRO_IDS;
7517 if (!MacrosLoaded[ID]) {
7518 GlobalMacroMapType::iterator I
7519 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7520 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7521 ModuleFile *M = I->second;
7522 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007523 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7524
7525 if (DeserializationListener)
7526 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7527 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 }
7529
7530 return MacrosLoaded[ID];
7531}
7532
7533MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7534 if (LocalID < NUM_PREDEF_MACRO_IDS)
7535 return LocalID;
7536
7537 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7538 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7539 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7540
7541 return LocalID + I->second;
7542}
7543
7544serialization::SubmoduleID
7545ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7546 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7547 return LocalID;
7548
7549 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7550 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7551 assert(I != M.SubmoduleRemap.end()
7552 && "Invalid index into submodule index remap");
7553
7554 return LocalID + I->second;
7555}
7556
7557Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7558 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7559 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007560 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007561 }
7562
7563 if (GlobalID > SubmodulesLoaded.size()) {
7564 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007565 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007566 }
7567
7568 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7569}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007570
7571Module *ASTReader::getModule(unsigned ID) {
7572 return getSubmodule(ID);
7573}
7574
Richard Smithd88a7f12015-09-01 20:35:42 +00007575ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7576 if (ID & 1) {
7577 // It's a module, look it up by submodule ID.
7578 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7579 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7580 } else {
7581 // It's a prefix (preamble, PCH, ...). Look it up by index.
7582 unsigned IndexFromEnd = ID >> 1;
7583 assert(IndexFromEnd && "got reference to unknown module file");
7584 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7585 }
7586}
7587
7588unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7589 if (!F)
7590 return 1;
7591
7592 // For a file representing a module, use the submodule ID of the top-level
7593 // module as the file ID. For any other kind of file, the number of such
7594 // files loaded beforehand will be the same on reload.
7595 // FIXME: Is this true even if we have an explicit module file and a PCH?
7596 if (F->isModule())
7597 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7598
7599 auto PCHModules = getModuleManager().pch_modules();
7600 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7601 assert(I != PCHModules.end() && "emitting reference to unknown file");
7602 return (I - PCHModules.end()) << 1;
7603}
7604
Adrian Prantl15bcf702015-06-30 17:39:43 +00007605llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7606ASTReader::getSourceDescriptor(unsigned ID) {
7607 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007608 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007609
7610 // If there is only a single PCH, return it instead.
7611 // Chained PCH are not suported.
7612 if (ModuleMgr.size() == 1) {
7613 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007614 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7615 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir,
7616 MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007617 }
7618 return None;
7619}
7620
Guy Benyei11169dd2012-12-18 14:30:41 +00007621Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7622 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7623}
7624
7625Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7626 if (ID == 0)
7627 return Selector();
7628
7629 if (ID > SelectorsLoaded.size()) {
7630 Error("selector ID out of range in AST file");
7631 return Selector();
7632 }
7633
Craig Toppera13603a2014-05-22 05:54:18 +00007634 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 // Load this selector from the selector table.
7636 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7637 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7638 ModuleFile &M = *I->second;
7639 ASTSelectorLookupTrait Trait(*this, M);
7640 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7641 SelectorsLoaded[ID - 1] =
7642 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7643 if (DeserializationListener)
7644 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7645 }
7646
7647 return SelectorsLoaded[ID - 1];
7648}
7649
7650Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7651 return DecodeSelector(ID);
7652}
7653
7654uint32_t ASTReader::GetNumExternalSelectors() {
7655 // ID 0 (the null selector) is considered an external selector.
7656 return getTotalNumSelectors() + 1;
7657}
7658
7659serialization::SelectorID
7660ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7661 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7662 return LocalID;
7663
7664 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7665 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7666 assert(I != M.SelectorRemap.end()
7667 && "Invalid index into selector index remap");
7668
7669 return LocalID + I->second;
7670}
7671
7672DeclarationName
7673ASTReader::ReadDeclarationName(ModuleFile &F,
7674 const RecordData &Record, unsigned &Idx) {
7675 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7676 switch (Kind) {
7677 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007678 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007679
7680 case DeclarationName::ObjCZeroArgSelector:
7681 case DeclarationName::ObjCOneArgSelector:
7682 case DeclarationName::ObjCMultiArgSelector:
7683 return DeclarationName(ReadSelector(F, Record, Idx));
7684
7685 case DeclarationName::CXXConstructorName:
7686 return Context.DeclarationNames.getCXXConstructorName(
7687 Context.getCanonicalType(readType(F, Record, Idx)));
7688
7689 case DeclarationName::CXXDestructorName:
7690 return Context.DeclarationNames.getCXXDestructorName(
7691 Context.getCanonicalType(readType(F, Record, Idx)));
7692
7693 case DeclarationName::CXXConversionFunctionName:
7694 return Context.DeclarationNames.getCXXConversionFunctionName(
7695 Context.getCanonicalType(readType(F, Record, Idx)));
7696
7697 case DeclarationName::CXXOperatorName:
7698 return Context.DeclarationNames.getCXXOperatorName(
7699 (OverloadedOperatorKind)Record[Idx++]);
7700
7701 case DeclarationName::CXXLiteralOperatorName:
7702 return Context.DeclarationNames.getCXXLiteralOperatorName(
7703 GetIdentifierInfo(F, Record, Idx));
7704
7705 case DeclarationName::CXXUsingDirective:
7706 return DeclarationName::getUsingDirectiveName();
7707 }
7708
7709 llvm_unreachable("Invalid NameKind!");
7710}
7711
7712void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7713 DeclarationNameLoc &DNLoc,
7714 DeclarationName Name,
7715 const RecordData &Record, unsigned &Idx) {
7716 switch (Name.getNameKind()) {
7717 case DeclarationName::CXXConstructorName:
7718 case DeclarationName::CXXDestructorName:
7719 case DeclarationName::CXXConversionFunctionName:
7720 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7721 break;
7722
7723 case DeclarationName::CXXOperatorName:
7724 DNLoc.CXXOperatorName.BeginOpNameLoc
7725 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7726 DNLoc.CXXOperatorName.EndOpNameLoc
7727 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7728 break;
7729
7730 case DeclarationName::CXXLiteralOperatorName:
7731 DNLoc.CXXLiteralOperatorName.OpNameLoc
7732 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7733 break;
7734
7735 case DeclarationName::Identifier:
7736 case DeclarationName::ObjCZeroArgSelector:
7737 case DeclarationName::ObjCOneArgSelector:
7738 case DeclarationName::ObjCMultiArgSelector:
7739 case DeclarationName::CXXUsingDirective:
7740 break;
7741 }
7742}
7743
7744void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7745 DeclarationNameInfo &NameInfo,
7746 const RecordData &Record, unsigned &Idx) {
7747 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7748 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7749 DeclarationNameLoc DNLoc;
7750 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7751 NameInfo.setInfo(DNLoc);
7752}
7753
7754void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7755 const RecordData &Record, unsigned &Idx) {
7756 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7757 unsigned NumTPLists = Record[Idx++];
7758 Info.NumTemplParamLists = NumTPLists;
7759 if (NumTPLists) {
7760 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7761 for (unsigned i=0; i != NumTPLists; ++i)
7762 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7763 }
7764}
7765
7766TemplateName
7767ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7768 unsigned &Idx) {
7769 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7770 switch (Kind) {
7771 case TemplateName::Template:
7772 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7773
7774 case TemplateName::OverloadedTemplate: {
7775 unsigned size = Record[Idx++];
7776 UnresolvedSet<8> Decls;
7777 while (size--)
7778 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7779
7780 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7781 }
7782
7783 case TemplateName::QualifiedTemplate: {
7784 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7785 bool hasTemplKeyword = Record[Idx++];
7786 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7787 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7788 }
7789
7790 case TemplateName::DependentTemplate: {
7791 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7792 if (Record[Idx++]) // isIdentifier
7793 return Context.getDependentTemplateName(NNS,
7794 GetIdentifierInfo(F, Record,
7795 Idx));
7796 return Context.getDependentTemplateName(NNS,
7797 (OverloadedOperatorKind)Record[Idx++]);
7798 }
7799
7800 case TemplateName::SubstTemplateTemplateParm: {
7801 TemplateTemplateParmDecl *param
7802 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7803 if (!param) return TemplateName();
7804 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7805 return Context.getSubstTemplateTemplateParm(param, replacement);
7806 }
7807
7808 case TemplateName::SubstTemplateTemplateParmPack: {
7809 TemplateTemplateParmDecl *Param
7810 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7811 if (!Param)
7812 return TemplateName();
7813
7814 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7815 if (ArgPack.getKind() != TemplateArgument::Pack)
7816 return TemplateName();
7817
7818 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7819 }
7820 }
7821
7822 llvm_unreachable("Unhandled template name kind!");
7823}
7824
Richard Smith2bb3c342015-08-09 01:05:31 +00007825TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7826 const RecordData &Record,
7827 unsigned &Idx,
7828 bool Canonicalize) {
7829 if (Canonicalize) {
7830 // The caller wants a canonical template argument. Sometimes the AST only
7831 // wants template arguments in canonical form (particularly as the template
7832 // argument lists of template specializations) so ensure we preserve that
7833 // canonical form across serialization.
7834 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7835 return Context.getCanonicalTemplateArgument(Arg);
7836 }
7837
Guy Benyei11169dd2012-12-18 14:30:41 +00007838 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7839 switch (Kind) {
7840 case TemplateArgument::Null:
7841 return TemplateArgument();
7842 case TemplateArgument::Type:
7843 return TemplateArgument(readType(F, Record, Idx));
7844 case TemplateArgument::Declaration: {
7845 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007846 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 }
7848 case TemplateArgument::NullPtr:
7849 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7850 case TemplateArgument::Integral: {
7851 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7852 QualType T = readType(F, Record, Idx);
7853 return TemplateArgument(Context, Value, T);
7854 }
7855 case TemplateArgument::Template:
7856 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7857 case TemplateArgument::TemplateExpansion: {
7858 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007859 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 if (unsigned NumExpansions = Record[Idx++])
7861 NumTemplateExpansions = NumExpansions - 1;
7862 return TemplateArgument(Name, NumTemplateExpansions);
7863 }
7864 case TemplateArgument::Expression:
7865 return TemplateArgument(ReadExpr(F));
7866 case TemplateArgument::Pack: {
7867 unsigned NumArgs = Record[Idx++];
7868 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7869 for (unsigned I = 0; I != NumArgs; ++I)
7870 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007871 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007872 }
7873 }
7874
7875 llvm_unreachable("Unhandled template argument kind!");
7876}
7877
7878TemplateParameterList *
7879ASTReader::ReadTemplateParameterList(ModuleFile &F,
7880 const RecordData &Record, unsigned &Idx) {
7881 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7882 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7883 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7884
7885 unsigned NumParams = Record[Idx++];
7886 SmallVector<NamedDecl *, 16> Params;
7887 Params.reserve(NumParams);
7888 while (NumParams--)
7889 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7890
7891 TemplateParameterList* TemplateParams =
7892 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
David Majnemer902f8c62015-12-27 07:16:27 +00007893 Params, RAngleLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 return TemplateParams;
7895}
7896
7897void
7898ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007899ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007900 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007901 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 unsigned NumTemplateArgs = Record[Idx++];
7903 TemplArgs.reserve(NumTemplateArgs);
7904 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007905 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007906}
7907
7908/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007909void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 const RecordData &Record, unsigned &Idx) {
7911 unsigned NumDecls = Record[Idx++];
7912 Set.reserve(Context, NumDecls);
7913 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007914 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007916 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 }
7918}
7919
7920CXXBaseSpecifier
7921ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7922 const RecordData &Record, unsigned &Idx) {
7923 bool isVirtual = static_cast<bool>(Record[Idx++]);
7924 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7925 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7926 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7927 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7928 SourceRange Range = ReadSourceRange(F, Record, Idx);
7929 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7930 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7931 EllipsisLoc);
7932 Result.setInheritConstructors(inheritConstructors);
7933 return Result;
7934}
7935
Richard Smithc2bb8182015-03-24 06:36:48 +00007936CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007937ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7938 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007940 assert(NumInitializers && "wrote ctor initializers but have no inits");
7941 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7942 for (unsigned i = 0; i != NumInitializers; ++i) {
7943 TypeSourceInfo *TInfo = nullptr;
7944 bool IsBaseVirtual = false;
7945 FieldDecl *Member = nullptr;
7946 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007947
Richard Smithc2bb8182015-03-24 06:36:48 +00007948 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7949 switch (Type) {
7950 case CTOR_INITIALIZER_BASE:
7951 TInfo = GetTypeSourceInfo(F, Record, Idx);
7952 IsBaseVirtual = Record[Idx++];
7953 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007954
Richard Smithc2bb8182015-03-24 06:36:48 +00007955 case CTOR_INITIALIZER_DELEGATING:
7956 TInfo = GetTypeSourceInfo(F, Record, Idx);
7957 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007958
Richard Smithc2bb8182015-03-24 06:36:48 +00007959 case CTOR_INITIALIZER_MEMBER:
7960 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7961 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007962
Richard Smithc2bb8182015-03-24 06:36:48 +00007963 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7964 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7965 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007967
7968 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7969 Expr *Init = ReadExpr(F);
7970 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7971 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7972 bool IsWritten = Record[Idx++];
7973 unsigned SourceOrderOrNumArrayIndices;
7974 SmallVector<VarDecl *, 8> Indices;
7975 if (IsWritten) {
7976 SourceOrderOrNumArrayIndices = Record[Idx++];
7977 } else {
7978 SourceOrderOrNumArrayIndices = Record[Idx++];
7979 Indices.reserve(SourceOrderOrNumArrayIndices);
7980 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7981 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7982 }
7983
7984 CXXCtorInitializer *BOMInit;
7985 if (Type == CTOR_INITIALIZER_BASE) {
7986 BOMInit = new (Context)
7987 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7988 RParenLoc, MemberOrEllipsisLoc);
7989 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7990 BOMInit = new (Context)
7991 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7992 } else if (IsWritten) {
7993 if (Member)
7994 BOMInit = new (Context) CXXCtorInitializer(
7995 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7996 else
7997 BOMInit = new (Context)
7998 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7999 LParenLoc, Init, RParenLoc);
8000 } else {
8001 if (IndirectMember) {
8002 assert(Indices.empty() && "Indirect field improperly initialized");
8003 BOMInit = new (Context)
8004 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8005 LParenLoc, Init, RParenLoc);
8006 } else {
8007 BOMInit = CXXCtorInitializer::Create(
8008 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
8009 Indices.data(), Indices.size());
8010 }
8011 }
8012
8013 if (IsWritten)
8014 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8015 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 }
8017
Richard Smithc2bb8182015-03-24 06:36:48 +00008018 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008019}
8020
8021NestedNameSpecifier *
8022ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8023 const RecordData &Record, unsigned &Idx) {
8024 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008025 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 for (unsigned I = 0; I != N; ++I) {
8027 NestedNameSpecifier::SpecifierKind Kind
8028 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8029 switch (Kind) {
8030 case NestedNameSpecifier::Identifier: {
8031 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8032 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8033 break;
8034 }
8035
8036 case NestedNameSpecifier::Namespace: {
8037 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8038 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8039 break;
8040 }
8041
8042 case NestedNameSpecifier::NamespaceAlias: {
8043 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8044 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8045 break;
8046 }
8047
8048 case NestedNameSpecifier::TypeSpec:
8049 case NestedNameSpecifier::TypeSpecWithTemplate: {
8050 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8051 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008052 return nullptr;
8053
Guy Benyei11169dd2012-12-18 14:30:41 +00008054 bool Template = Record[Idx++];
8055 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8056 break;
8057 }
8058
8059 case NestedNameSpecifier::Global: {
8060 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8061 // No associated value, and there can't be a prefix.
8062 break;
8063 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008064
8065 case NestedNameSpecifier::Super: {
8066 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8067 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8068 break;
8069 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 }
8071 Prev = NNS;
8072 }
8073 return NNS;
8074}
8075
8076NestedNameSpecifierLoc
8077ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8078 unsigned &Idx) {
8079 unsigned N = Record[Idx++];
8080 NestedNameSpecifierLocBuilder Builder;
8081 for (unsigned I = 0; I != N; ++I) {
8082 NestedNameSpecifier::SpecifierKind Kind
8083 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8084 switch (Kind) {
8085 case NestedNameSpecifier::Identifier: {
8086 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8087 SourceRange Range = ReadSourceRange(F, Record, Idx);
8088 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8089 break;
8090 }
8091
8092 case NestedNameSpecifier::Namespace: {
8093 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8094 SourceRange Range = ReadSourceRange(F, Record, Idx);
8095 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8096 break;
8097 }
8098
8099 case NestedNameSpecifier::NamespaceAlias: {
8100 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8101 SourceRange Range = ReadSourceRange(F, Record, Idx);
8102 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8103 break;
8104 }
8105
8106 case NestedNameSpecifier::TypeSpec:
8107 case NestedNameSpecifier::TypeSpecWithTemplate: {
8108 bool Template = Record[Idx++];
8109 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8110 if (!T)
8111 return NestedNameSpecifierLoc();
8112 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8113
8114 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8115 Builder.Extend(Context,
8116 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8117 T->getTypeLoc(), ColonColonLoc);
8118 break;
8119 }
8120
8121 case NestedNameSpecifier::Global: {
8122 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8123 Builder.MakeGlobal(Context, ColonColonLoc);
8124 break;
8125 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008126
8127 case NestedNameSpecifier::Super: {
8128 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8129 SourceRange Range = ReadSourceRange(F, Record, Idx);
8130 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8131 break;
8132 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 }
8134 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008135
Guy Benyei11169dd2012-12-18 14:30:41 +00008136 return Builder.getWithLocInContext(Context);
8137}
8138
8139SourceRange
8140ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8141 unsigned &Idx) {
8142 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8143 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8144 return SourceRange(beg, end);
8145}
8146
8147/// \brief Read an integral value
8148llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8149 unsigned BitWidth = Record[Idx++];
8150 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8151 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8152 Idx += NumWords;
8153 return Result;
8154}
8155
8156/// \brief Read a signed integral value
8157llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8158 bool isUnsigned = Record[Idx++];
8159 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8160}
8161
8162/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008163llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8164 const llvm::fltSemantics &Sem,
8165 unsigned &Idx) {
8166 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008167}
8168
8169// \brief Read a string
8170std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8171 unsigned Len = Record[Idx++];
8172 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8173 Idx += Len;
8174 return Result;
8175}
8176
Richard Smith7ed1bc92014-12-05 22:42:13 +00008177std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8178 unsigned &Idx) {
8179 std::string Filename = ReadString(Record, Idx);
8180 ResolveImportedPath(F, Filename);
8181 return Filename;
8182}
8183
Guy Benyei11169dd2012-12-18 14:30:41 +00008184VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8185 unsigned &Idx) {
8186 unsigned Major = Record[Idx++];
8187 unsigned Minor = Record[Idx++];
8188 unsigned Subminor = Record[Idx++];
8189 if (Minor == 0)
8190 return VersionTuple(Major);
8191 if (Subminor == 0)
8192 return VersionTuple(Major, Minor - 1);
8193 return VersionTuple(Major, Minor - 1, Subminor - 1);
8194}
8195
8196CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8197 const RecordData &Record,
8198 unsigned &Idx) {
8199 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8200 return CXXTemporary::Create(Context, Decl);
8201}
8202
8203DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008204 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008205}
8206
8207DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8208 return Diags.Report(Loc, DiagID);
8209}
8210
8211/// \brief Retrieve the identifier table associated with the
8212/// preprocessor.
8213IdentifierTable &ASTReader::getIdentifierTable() {
8214 return PP.getIdentifierTable();
8215}
8216
8217/// \brief Record that the given ID maps to the given switch-case
8218/// statement.
8219void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008220 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 "Already have a SwitchCase with this ID");
8222 (*CurrSwitchCaseStmts)[ID] = SC;
8223}
8224
8225/// \brief Retrieve the switch-case statement with the given ID.
8226SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008227 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 return (*CurrSwitchCaseStmts)[ID];
8229}
8230
8231void ASTReader::ClearSwitchCaseIDs() {
8232 CurrSwitchCaseStmts->clear();
8233}
8234
8235void ASTReader::ReadComments() {
8236 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008237 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 serialization::ModuleFile *> >::iterator
8239 I = CommentsCursors.begin(),
8240 E = CommentsCursors.end();
8241 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008242 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008243 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 serialization::ModuleFile &F = *I->second;
8245 SavedStreamPosition SavedPosition(Cursor);
8246
8247 RecordData Record;
8248 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008249 llvm::BitstreamEntry Entry =
8250 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008251
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008252 switch (Entry.Kind) {
8253 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8254 case llvm::BitstreamEntry::Error:
8255 Error("malformed block record in AST file");
8256 return;
8257 case llvm::BitstreamEntry::EndBlock:
8258 goto NextCursor;
8259 case llvm::BitstreamEntry::Record:
8260 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008261 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008262 }
8263
8264 // Read a record.
8265 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008266 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 case COMMENTS_RAW_COMMENT: {
8268 unsigned Idx = 0;
8269 SourceRange SR = ReadSourceRange(F, Record, Idx);
8270 RawComment::CommentKind Kind =
8271 (RawComment::CommentKind) Record[Idx++];
8272 bool IsTrailingComment = Record[Idx++];
8273 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008274 Comments.push_back(new (Context) RawComment(
8275 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8276 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 break;
8278 }
8279 }
8280 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008281 NextCursor:
8282 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008284}
8285
Richard Smithcd45dbc2014-04-19 03:48:30 +00008286std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8287 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008288 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008289 return M->getFullModuleName();
8290
8291 // Otherwise, use the name of the top-level module the decl is within.
8292 if (ModuleFile *M = getOwningModuleFile(D))
8293 return M->ModuleName;
8294
8295 // Not from a module.
8296 return "";
8297}
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008300 while (!PendingIdentifierInfos.empty() ||
8301 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008302 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008303 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008304 // If any identifiers with corresponding top-level declarations have
8305 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008306 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8307 TopLevelDeclsMap;
8308 TopLevelDeclsMap TopLevelDecls;
8309
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008311 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008312 SmallVector<uint32_t, 4> DeclIDs =
8313 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008314 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008315
8316 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008317 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008318
Richard Smith851072e2014-05-19 20:59:20 +00008319 // For each decl chain that we wanted to complete while deserializing, mark
8320 // it as "still needs to be completed".
8321 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8322 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8323 }
8324 PendingIncompleteDeclChains.clear();
8325
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008327 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008328 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 PendingDeclChains.clear();
8330
Douglas Gregor6168bd22013-02-18 15:53:43 +00008331 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008332 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8333 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008334 IdentifierInfo *II = TLD->first;
8335 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008336 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008337 }
8338 }
8339
Guy Benyei11169dd2012-12-18 14:30:41 +00008340 // Load any pending macro definitions.
8341 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008342 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8343 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8344 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8345 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008346 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008347 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008348 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008349 if (Info.M->Kind != MK_ImplicitModule &&
8350 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008351 resolvePendingMacro(II, Info);
8352 }
8353 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008354 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008355 ++IDIdx) {
8356 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008357 if (Info.M->Kind == MK_ImplicitModule ||
8358 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008359 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 }
8361 }
8362 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008363
8364 // Wire up the DeclContexts for Decls that we delayed setting until
8365 // recursive loading is completed.
8366 while (!PendingDeclContextInfos.empty()) {
8367 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8368 PendingDeclContextInfos.pop_front();
8369 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8370 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8371 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8372 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008373
Richard Smithd1c46742014-04-30 02:24:17 +00008374 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008375 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008376 auto Update = PendingUpdateRecords.pop_back_val();
8377 ReadingKindTracker ReadingKind(Read_Decl, *this);
8378 loadDeclUpdateRecords(Update.first, Update.second);
8379 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008380 }
Richard Smith8a639892015-01-24 01:07:20 +00008381
8382 // At this point, all update records for loaded decls are in place, so any
8383 // fake class definitions should have become real.
8384 assert(PendingFakeDefinitionData.empty() &&
8385 "faked up a class definition but never saw the real one");
8386
Guy Benyei11169dd2012-12-18 14:30:41 +00008387 // If we deserialized any C++ or Objective-C class definitions, any
8388 // Objective-C protocol definitions, or any redeclarable templates, make sure
8389 // that all redeclarations point to the definitions. Note that this can only
8390 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008391 for (Decl *D : PendingDefinitions) {
8392 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008393 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 // Make sure that the TagType points at the definition.
8395 const_cast<TagType*>(TagT)->decl = TD;
8396 }
Richard Smith8ce51082015-03-11 01:44:51 +00008397
Craig Topperc6914d02014-08-25 04:15:02 +00008398 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008399 for (auto *R = getMostRecentExistingDecl(RD); R;
8400 R = R->getPreviousDecl()) {
8401 assert((R == D) ==
8402 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008403 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008404 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008405 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008406 }
8407
8408 continue;
8409 }
Richard Smith8ce51082015-03-11 01:44:51 +00008410
Craig Topperc6914d02014-08-25 04:15:02 +00008411 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 // Make sure that the ObjCInterfaceType points at the definition.
8413 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8414 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008415
8416 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8417 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8418
Guy Benyei11169dd2012-12-18 14:30:41 +00008419 continue;
8420 }
Richard Smith8ce51082015-03-11 01:44:51 +00008421
Craig Topperc6914d02014-08-25 04:15:02 +00008422 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008423 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8424 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8425
Guy Benyei11169dd2012-12-18 14:30:41 +00008426 continue;
8427 }
Richard Smith8ce51082015-03-11 01:44:51 +00008428
Craig Topperc6914d02014-08-25 04:15:02 +00008429 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008430 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8431 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 }
8433 PendingDefinitions.clear();
8434
8435 // Load the bodies of any functions or methods we've encountered. We do
8436 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008437 // have been fully wired up (hasBody relies on this).
8438 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008439 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8440 PBEnd = PendingBodies.end();
8441 PB != PBEnd; ++PB) {
8442 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8443 // FIXME: Check for =delete/=default?
8444 // FIXME: Complain about ODR violations here?
8445 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8446 FD->setLazyBody(PB->second);
8447 continue;
8448 }
8449
8450 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8451 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8452 MD->setLazyBody(PB->second);
8453 }
8454 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008455
8456 // Do some cleanup.
8457 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8458 getContext().deduplicateMergedDefinitonsFor(ND);
8459 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008460}
8461
8462void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008463 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8464 return;
8465
Richard Smitha0ce9c42014-07-29 23:23:27 +00008466 // Trigger the import of the full definition of each class that had any
8467 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008468 // These updates may in turn find and diagnose some ODR failures, so take
8469 // ownership of the set first.
8470 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8471 PendingOdrMergeFailures.clear();
8472 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008473 Merge.first->buildLookup();
8474 Merge.first->decls_begin();
8475 Merge.first->bases_begin();
8476 Merge.first->vbases_begin();
8477 for (auto *RD : Merge.second) {
8478 RD->decls_begin();
8479 RD->bases_begin();
8480 RD->vbases_begin();
8481 }
8482 }
8483
8484 // For each declaration from a merged context, check that the canonical
8485 // definition of that context also contains a declaration of the same
8486 // entity.
8487 //
8488 // Caution: this loop does things that might invalidate iterators into
8489 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8490 while (!PendingOdrMergeChecks.empty()) {
8491 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8492
8493 // FIXME: Skip over implicit declarations for now. This matters for things
8494 // like implicitly-declared special member functions. This isn't entirely
8495 // correct; we can end up with multiple unmerged declarations of the same
8496 // implicit entity.
8497 if (D->isImplicit())
8498 continue;
8499
8500 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008501
8502 bool Found = false;
8503 const Decl *DCanon = D->getCanonicalDecl();
8504
Richard Smith01bdb7a2014-08-28 05:44:07 +00008505 for (auto RI : D->redecls()) {
8506 if (RI->getLexicalDeclContext() == CanonDef) {
8507 Found = true;
8508 break;
8509 }
8510 }
8511 if (Found)
8512 continue;
8513
Richard Smith0f4e2c42015-08-06 04:23:48 +00008514 // Quick check failed, time to do the slow thing. Note, we can't just
8515 // look up the name of D in CanonDef here, because the member that is
8516 // in CanonDef might not be found by name lookup (it might have been
8517 // replaced by a more recent declaration in the lookup table), and we
8518 // can't necessarily find it in the redeclaration chain because it might
8519 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008520 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008521 for (auto *CanonMember : CanonDef->decls()) {
8522 if (CanonMember->getCanonicalDecl() == DCanon) {
8523 // This can happen if the declaration is merely mergeable and not
8524 // actually redeclarable (we looked for redeclarations earlier).
8525 //
8526 // FIXME: We should be able to detect this more efficiently, without
8527 // pulling in all of the members of CanonDef.
8528 Found = true;
8529 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008530 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008531 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8532 if (ND->getDeclName() == D->getDeclName())
8533 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008534 }
8535
8536 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008537 // The AST doesn't like TagDecls becoming invalid after they've been
8538 // completed. We only really need to mark FieldDecls as invalid here.
8539 if (!isa<TagDecl>(D))
8540 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008541
8542 // Ensure we don't accidentally recursively enter deserialization while
8543 // we're producing our diagnostic.
8544 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008545
8546 std::string CanonDefModule =
8547 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8548 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8549 << D << getOwningModuleNameForDiagnostic(D)
8550 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8551
8552 if (Candidates.empty())
8553 Diag(cast<Decl>(CanonDef)->getLocation(),
8554 diag::note_module_odr_violation_no_possible_decls) << D;
8555 else {
8556 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8557 Diag(Candidates[I]->getLocation(),
8558 diag::note_module_odr_violation_possible_decl)
8559 << Candidates[I];
8560 }
8561
8562 DiagnosedOdrMergeFailures.insert(CanonDef);
8563 }
8564 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008565
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008566 if (OdrMergeFailures.empty())
8567 return;
8568
8569 // Ensure we don't accidentally recursively enter deserialization while
8570 // we're producing our diagnostics.
8571 Deserializing RecursionGuard(this);
8572
Richard Smithcd45dbc2014-04-19 03:48:30 +00008573 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008574 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008575 // If we've already pointed out a specific problem with this class, don't
8576 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008577 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008578 continue;
8579
8580 bool Diagnosed = false;
8581 for (auto *RD : Merge.second) {
8582 // Multiple different declarations got merged together; tell the user
8583 // where they came from.
8584 if (Merge.first != RD) {
8585 // FIXME: Walk the definition, figure out what's different,
8586 // and diagnose that.
8587 if (!Diagnosed) {
8588 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8589 Diag(Merge.first->getLocation(),
8590 diag::err_module_odr_violation_different_definitions)
8591 << Merge.first << Module.empty() << Module;
8592 Diagnosed = true;
8593 }
8594
8595 Diag(RD->getLocation(),
8596 diag::note_module_odr_violation_different_definitions)
8597 << getOwningModuleNameForDiagnostic(RD);
8598 }
8599 }
8600
8601 if (!Diagnosed) {
8602 // All definitions are updates to the same declaration. This happens if a
8603 // module instantiates the declaration of a class template specialization
8604 // and two or more other modules instantiate its definition.
8605 //
8606 // FIXME: Indicate which modules had instantiations of this definition.
8607 // FIXME: How can this even happen?
8608 Diag(Merge.first->getLocation(),
8609 diag::err_module_odr_violation_different_instantiations)
8610 << Merge.first;
8611 }
8612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008613}
8614
Richard Smithce18a182015-07-14 00:26:00 +00008615void ASTReader::StartedDeserializing() {
8616 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8617 ReadTimer->startTimer();
8618}
8619
Guy Benyei11169dd2012-12-18 14:30:41 +00008620void ASTReader::FinishedDeserializing() {
8621 assert(NumCurrentElementsDeserializing &&
8622 "FinishedDeserializing not paired with StartedDeserializing");
8623 if (NumCurrentElementsDeserializing == 1) {
8624 // We decrease NumCurrentElementsDeserializing only after pending actions
8625 // are finished, to avoid recursively re-calling finishPendingActions().
8626 finishPendingActions();
8627 }
8628 --NumCurrentElementsDeserializing;
8629
Richard Smitha0ce9c42014-07-29 23:23:27 +00008630 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008631 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008632 while (!PendingExceptionSpecUpdates.empty()) {
8633 auto Updates = std::move(PendingExceptionSpecUpdates);
8634 PendingExceptionSpecUpdates.clear();
8635 for (auto Update : Updates) {
8636 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008637 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008638 if (auto *Listener = Context.getASTMutationListener())
8639 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008640 for (auto *Redecl : Update.second->redecls())
8641 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008642 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008643 }
8644
Richard Smithce18a182015-07-14 00:26:00 +00008645 if (ReadTimer)
8646 ReadTimer->stopTimer();
8647
Richard Smith0f4e2c42015-08-06 04:23:48 +00008648 diagnoseOdrViolations();
8649
Richard Smith04d05b52014-03-23 00:27:18 +00008650 // We are not in recursive loading, so it's safe to pass the "interesting"
8651 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008652 if (Consumer)
8653 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008654 }
8655}
8656
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008657void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008658 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8659 // Remove any fake results before adding any real ones.
8660 auto It = PendingFakeLookupResults.find(II);
8661 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008662 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008663 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008664 // FIXME: this works around module+PCH performance issue.
8665 // Rather than erase the result from the map, which is O(n), just clear
8666 // the vector of NamedDecls.
8667 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008668 }
8669 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008670
8671 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8672 SemaObj->TUScope->AddDecl(D);
8673 } else if (SemaObj->TUScope) {
8674 // Adding the decl to IdResolver may have failed because it was already in
8675 // (even though it was not added in scope). If it is already in, make sure
8676 // it gets in the scope as well.
8677 if (std::find(SemaObj->IdResolver.begin(Name),
8678 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8679 SemaObj->TUScope->AddDecl(D);
8680 }
8681}
8682
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008683ASTReader::ASTReader(
8684 Preprocessor &PP, ASTContext &Context,
8685 const PCHContainerReader &PCHContainerRdr,
8686 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8687 StringRef isysroot, bool DisableValidation,
8688 bool AllowASTWithCompilerErrors,
8689 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8690 bool UseGlobalIndex,
8691 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008692 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008693 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008694 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008695 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008696 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008697 ReadTimer(std::move(ReadTimer)),
Nico Weber779355f2016-03-02 23:22:00 +00008698 PragmaMSStructState(-1),
Nico Weber42932312016-03-03 00:17:35 +00008699 PragmaMSPointersToMembersState(-1),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008700 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008701 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8702 AllowConfigurationMismatch(AllowConfigurationMismatch),
8703 ValidateSystemInputs(ValidateSystemInputs),
8704 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008705 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8706 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8707 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8708 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008709 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8710 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8711 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8712 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8713 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8714 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008715 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008716 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008717
8718 for (const auto &Ext : Extensions) {
8719 auto BlockName = Ext->getExtensionMetadata().BlockName;
8720 auto Known = ModuleFileExtensions.find(BlockName);
8721 if (Known != ModuleFileExtensions.end()) {
8722 Diags.Report(diag::warn_duplicate_module_file_extension)
8723 << BlockName;
8724 continue;
8725 }
8726
8727 ModuleFileExtensions.insert({BlockName, Ext});
8728 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008729}
8730
8731ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008732 if (OwnsDeserializationListener)
8733 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008734}