blob: 1fbff107ea5bab240f08dd7483a19c7051c1922a [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000023#include "clang/AST/ASTMutationListener.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000027#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/SourceManagerInternals.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TargetOptions.h"
33#include "clang/Basic/Version.h"
34#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000035#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Lex/HeaderSearch.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/MacroInfo.h"
39#include "clang/Lex/PreprocessingRecord.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Lex/PreprocessorOptions.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000045#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "clang/Serialization/ModuleManager.h"
47#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000048#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049#include "llvm/ADT/StringExtras.h"
50#include "llvm/Bitcode/BitstreamReader.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000094bool ChainedASTReaderListener::ReadTargetOptions(
95 const TargetOptions &TargetOpts, bool Complain,
96 bool AllowCompatibleDifferences) {
97 return First->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences) ||
99 Second->ReadTargetOptions(TargetOpts, Complain,
100 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000101}
102bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000103 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000104 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
105 Second->ReadDiagnosticOptions(DiagOpts, Complain);
106}
107bool
108ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
109 bool Complain) {
110 return First->ReadFileSystemOptions(FSOpts, Complain) ||
111 Second->ReadFileSystemOptions(FSOpts, Complain);
112}
113
114bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000115 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
116 bool Complain) {
117 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain) ||
119 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
120 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000121}
122bool ChainedASTReaderListener::ReadPreprocessorOptions(
123 const PreprocessorOptions &PPOpts, bool Complain,
124 std::string &SuggestedPredefines) {
125 return First->ReadPreprocessorOptions(PPOpts, Complain,
126 SuggestedPredefines) ||
127 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
128}
129void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
130 unsigned Value) {
131 First->ReadCounter(M, Value);
132 Second->ReadCounter(M, Value);
133}
134bool ChainedASTReaderListener::needsInputFileVisitation() {
135 return First->needsInputFileVisitation() ||
136 Second->needsInputFileVisitation();
137}
138bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
139 return First->needsSystemInputFileVisitation() ||
140 Second->needsSystemInputFileVisitation();
141}
Richard Smith216a3bd2015-08-13 17:57:10 +0000142void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
143 ModuleKind Kind) {
144 First->visitModuleFile(Filename, Kind);
145 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000146}
Ben Langmuircb69b572014-03-07 06:40:32 +0000147bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000148 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000149 bool isOverridden,
150 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000151 bool Continue = false;
152 if (First->needsInputFileVisitation() &&
153 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000154 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
155 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000156 if (Second->needsInputFileVisitation() &&
157 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000158 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
159 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000160 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000161}
162
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000163void ChainedASTReaderListener::readModuleFileExtension(
164 const ModuleFileExtensionMetadata &Metadata) {
165 First->readModuleFileExtension(Metadata);
166 Second->readModuleFileExtension(Metadata);
167}
168
Guy Benyei11169dd2012-12-18 14:30:41 +0000169//===----------------------------------------------------------------------===//
170// PCH validator implementation
171//===----------------------------------------------------------------------===//
172
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000173ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000174
175/// \brief Compare the given set of language options against an existing set of
176/// language options.
177///
178/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000179/// \param AllowCompatibleDifferences If true, differences between compatible
180/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000181///
182/// \returns true if the languagae options mis-match, false otherwise.
183static bool checkLanguageOptions(const LangOptions &LangOpts,
184 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000185 DiagnosticsEngine *Diags,
186 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000187#define LANGOPT(Name, Bits, Default, Description) \
188 if (ExistingLangOpts.Name != LangOpts.Name) { \
189 if (Diags) \
190 Diags->Report(diag::err_pch_langopt_mismatch) \
191 << Description << LangOpts.Name << ExistingLangOpts.Name; \
192 return true; \
193 }
194
195#define VALUE_LANGOPT(Name, Bits, Default, Description) \
196 if (ExistingLangOpts.Name != LangOpts.Name) { \
197 if (Diags) \
198 Diags->Report(diag::err_pch_langopt_value_mismatch) \
199 << Description; \
200 return true; \
201 }
202
203#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
204 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
205 if (Diags) \
206 Diags->Report(diag::err_pch_langopt_value_mismatch) \
207 << Description; \
208 return true; \
209 }
210
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000211#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
212 if (!AllowCompatibleDifferences) \
213 LANGOPT(Name, Bits, Default, Description)
214
215#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
216 if (!AllowCompatibleDifferences) \
217 ENUM_LANGOPT(Name, Bits, Default, Description)
218
Guy Benyei11169dd2012-12-18 14:30:41 +0000219#define BENIGN_LANGOPT(Name, Bits, Default, Description)
220#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
221#include "clang/Basic/LangOptions.def"
222
Ben Langmuircd98cb72015-06-23 18:20:18 +0000223 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
224 if (Diags)
225 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
226 return true;
227 }
228
Guy Benyei11169dd2012-12-18 14:30:41 +0000229 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
230 if (Diags)
231 Diags->Report(diag::err_pch_langopt_value_mismatch)
232 << "target Objective-C runtime";
233 return true;
234 }
235
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000236 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
237 LangOpts.CommentOpts.BlockCommandNames) {
238 if (Diags)
239 Diags->Report(diag::err_pch_langopt_value_mismatch)
240 << "block command names";
241 return true;
242 }
243
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 return false;
245}
246
247/// \brief Compare the given set of target options against an existing set of
248/// target options.
249///
250/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
251///
252/// \returns true if the target options mis-match, false otherwise.
253static bool checkTargetOptions(const TargetOptions &TargetOpts,
254 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000255 DiagnosticsEngine *Diags,
256 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#define CHECK_TARGET_OPT(Field, Name) \
258 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
259 if (Diags) \
260 Diags->Report(diag::err_pch_targetopt_mismatch) \
261 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
262 return true; \
263 }
264
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000265 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000266 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000267 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268
269 // We can tolerate different CPUs in many cases, notably when one CPU
270 // supports a strict superset of another. When allowing compatible
271 // differences skip this check.
272 if (!AllowCompatibleDifferences)
273 CHECK_TARGET_OPT(CPU, "target CPU");
274
Guy Benyei11169dd2012-12-18 14:30:41 +0000275#undef CHECK_TARGET_OPT
276
277 // Compare feature sets.
278 SmallVector<StringRef, 4> ExistingFeatures(
279 ExistingTargetOpts.FeaturesAsWritten.begin(),
280 ExistingTargetOpts.FeaturesAsWritten.end());
281 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
282 TargetOpts.FeaturesAsWritten.end());
283 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
284 std::sort(ReadFeatures.begin(), ReadFeatures.end());
285
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 // We compute the set difference in both directions explicitly so that we can
287 // diagnose the differences differently.
288 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
289 std::set_difference(
290 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
291 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
292 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
293 ExistingFeatures.begin(), ExistingFeatures.end(),
294 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000295
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000296 // If we are allowing compatible differences and the read feature set is
297 // a strict subset of the existing feature set, there is nothing to diagnose.
298 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
299 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000300
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000301 if (Diags) {
302 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 << /* is-existing-feature */ false << Feature;
305 for (StringRef Feature : UnmatchedExistingFeatures)
306 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
307 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 }
309
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000311}
312
313bool
314PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000315 bool Complain,
316 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 const LangOptions &ExistingLangOpts = PP.getLangOpts();
318 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000319 Complain ? &Reader.Diags : nullptr,
320 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000321}
322
323bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000324 bool Complain,
325 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000326 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
327 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000328 Complain ? &Reader.Diags : nullptr,
329 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
332namespace {
333 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
334 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000335 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
336 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000337}
338
Ben Langmuirb92de022014-04-29 16:25:26 +0000339static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
340 DiagnosticsEngine &Diags,
341 bool Complain) {
342 typedef DiagnosticsEngine::Level Level;
343
344 // Check current mappings for new -Werror mappings, and the stored mappings
345 // for cases that were explicitly mapped to *not* be errors that are now
346 // errors because of options like -Werror.
347 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
348
349 for (DiagnosticsEngine *MappingSource : MappingSources) {
350 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
351 diag::kind DiagID = DiagIDMappingPair.first;
352 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
353 if (CurLevel < DiagnosticsEngine::Error)
354 continue; // not significant
355 Level StoredLevel =
356 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
357 if (StoredLevel < DiagnosticsEngine::Error) {
358 if (Complain)
359 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
360 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
361 return true;
362 }
363 }
364 }
365
366 return false;
367}
368
Alp Tokerac4e8e52014-06-22 21:58:33 +0000369static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
370 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
371 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
372 return true;
373 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000374}
375
376static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
377 DiagnosticsEngine &Diags,
378 bool IsSystem, bool Complain) {
379 // Top-level options
380 if (IsSystem) {
381 if (Diags.getSuppressSystemWarnings())
382 return false;
383 // If -Wsystem-headers was not enabled before, be conservative
384 if (StoredDiags.getSuppressSystemWarnings()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
387 return true;
388 }
389 }
390
391 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
394 return true;
395 }
396
397 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
398 !StoredDiags.getEnableAllWarnings()) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
401 return true;
402 }
403
404 if (isExtHandlingFromDiagsError(Diags) &&
405 !isExtHandlingFromDiagsError(StoredDiags)) {
406 if (Complain)
407 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
408 return true;
409 }
410
411 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
412}
413
414bool PCHValidator::ReadDiagnosticOptions(
415 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
416 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
417 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
418 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000419 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // This should never fail, because we would have processed these options
421 // before writing them to an ASTFile.
422 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
423
424 ModuleManager &ModuleMgr = Reader.getModuleManager();
425 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
426
427 // If the original import came from a file explicitly generated by the user,
428 // don't check the diagnostic mappings.
429 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000430 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
432 // the transitive closure of its imports, since unrelated modules cannot be
433 // imported until after this module finishes validation.
434 ModuleFile *TopImport = *ModuleMgr.rbegin();
435 while (!TopImport->ImportedBy.empty())
436 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000437 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000438 return false;
439
440 StringRef ModuleName = TopImport->ModuleName;
441 assert(!ModuleName.empty() && "diagnostic options read before module name");
442
443 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
444 assert(M && "missing module");
445
446 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
447 // contains the union of their flags.
448 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
449}
450
Guy Benyei11169dd2012-12-18 14:30:41 +0000451/// \brief Collect the macro definitions provided by the given preprocessor
452/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000453static void
454collectMacroDefinitions(const PreprocessorOptions &PPOpts,
455 MacroDefinitionsMap &Macros,
456 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
458 StringRef Macro = PPOpts.Macros[I].first;
459 bool IsUndef = PPOpts.Macros[I].second;
460
461 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
462 StringRef MacroName = MacroPair.first;
463 StringRef MacroBody = MacroPair.second;
464
465 // For an #undef'd macro, we only care about the name.
466 if (IsUndef) {
467 if (MacroNames && !Macros.count(MacroName))
468 MacroNames->push_back(MacroName);
469
470 Macros[MacroName] = std::make_pair("", true);
471 continue;
472 }
473
474 // For a #define'd macro, figure out the actual definition.
475 if (MacroName.size() == Macro.size())
476 MacroBody = "1";
477 else {
478 // Note: GCC drops anything following an end-of-line character.
479 StringRef::size_type End = MacroBody.find_first_of("\n\r");
480 MacroBody = MacroBody.substr(0, End);
481 }
482
483 if (MacroNames && !Macros.count(MacroName))
484 MacroNames->push_back(MacroName);
485 Macros[MacroName] = std::make_pair(MacroBody, false);
486 }
487}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000488
Guy Benyei11169dd2012-12-18 14:30:41 +0000489/// \brief Check the preprocessor options deserialized from the control block
490/// against the preprocessor options in an existing preprocessor.
491///
492/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
493static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
494 const PreprocessorOptions &ExistingPPOpts,
495 DiagnosticsEngine *Diags,
496 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000497 std::string &SuggestedPredefines,
498 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 // Check macro definitions.
500 MacroDefinitionsMap ASTFileMacros;
501 collectMacroDefinitions(PPOpts, ASTFileMacros);
502 MacroDefinitionsMap ExistingMacros;
503 SmallVector<StringRef, 4> ExistingMacroNames;
504 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
505
506 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
507 // Dig out the macro definition in the existing preprocessor options.
508 StringRef MacroName = ExistingMacroNames[I];
509 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
510
511 // Check whether we know anything about this macro name or not.
512 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
513 = ASTFileMacros.find(MacroName);
514 if (Known == ASTFileMacros.end()) {
515 // FIXME: Check whether this identifier was referenced anywhere in the
516 // AST file. If so, we should reject the AST file. Unfortunately, this
517 // information isn't in the control block. What shall we do about it?
518
519 if (Existing.second) {
520 SuggestedPredefines += "#undef ";
521 SuggestedPredefines += MacroName.str();
522 SuggestedPredefines += '\n';
523 } else {
524 SuggestedPredefines += "#define ";
525 SuggestedPredefines += MacroName.str();
526 SuggestedPredefines += ' ';
527 SuggestedPredefines += Existing.first.str();
528 SuggestedPredefines += '\n';
529 }
530 continue;
531 }
532
533 // If the macro was defined in one but undef'd in the other, we have a
534 // conflict.
535 if (Existing.second != Known->second.second) {
536 if (Diags) {
537 Diags->Report(diag::err_pch_macro_def_undef)
538 << MacroName << Known->second.second;
539 }
540 return true;
541 }
542
543 // If the macro was #undef'd in both, or if the macro bodies are identical,
544 // it's fine.
545 if (Existing.second || Existing.first == Known->second.first)
546 continue;
547
548 // The macro bodies differ; complain.
549 if (Diags) {
550 Diags->Report(diag::err_pch_macro_def_conflict)
551 << MacroName << Known->second.first << Existing.first;
552 }
553 return true;
554 }
555
556 // Check whether we're using predefines.
557 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
558 if (Diags) {
559 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
560 }
561 return true;
562 }
563
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000564 // Detailed record is important since it is used for the module cache hash.
565 if (LangOpts.Modules &&
566 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
567 if (Diags) {
568 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
569 }
570 return true;
571 }
572
Guy Benyei11169dd2012-12-18 14:30:41 +0000573 // Compute the #include and #include_macros lines we need.
574 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
575 StringRef File = ExistingPPOpts.Includes[I];
576 if (File == ExistingPPOpts.ImplicitPCHInclude)
577 continue;
578
579 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
580 != PPOpts.Includes.end())
581 continue;
582
583 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000584 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 SuggestedPredefines += "\"\n";
586 }
587
588 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
589 StringRef File = ExistingPPOpts.MacroIncludes[I];
590 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
591 File)
592 != PPOpts.MacroIncludes.end())
593 continue;
594
595 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000596 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 SuggestedPredefines += "\"\n##\n";
598 }
599
600 return false;
601}
602
603bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
604 bool Complain,
605 std::string &SuggestedPredefines) {
606 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
607
608 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000609 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000611 SuggestedPredefines,
612 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000613}
614
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615/// Check the header search options deserialized from the control block
616/// against the header search options in an existing preprocessor.
617///
618/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
619static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
620 StringRef SpecificModuleCachePath,
621 StringRef ExistingModuleCachePath,
622 DiagnosticsEngine *Diags,
623 const LangOptions &LangOpts) {
624 if (LangOpts.Modules) {
625 if (SpecificModuleCachePath != ExistingModuleCachePath) {
626 if (Diags)
627 Diags->Report(diag::err_pch_modulecache_mismatch)
628 << SpecificModuleCachePath << ExistingModuleCachePath;
629 return true;
630 }
631 }
632
633 return false;
634}
635
636bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
637 StringRef SpecificModuleCachePath,
638 bool Complain) {
639 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
640 PP.getHeaderSearchInfo().getModuleCachePath(),
641 Complain ? &Reader.Diags : nullptr,
642 PP.getLangOpts());
643}
644
Guy Benyei11169dd2012-12-18 14:30:41 +0000645void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
646 PP.setCounterValue(Value);
647}
648
649//===----------------------------------------------------------------------===//
650// AST reader implementation
651//===----------------------------------------------------------------------===//
652
Nico Weber824285e2014-05-08 04:26:47 +0000653void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
654 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000656 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000657}
658
659
660
661unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
662 return serialization::ComputeHash(Sel);
663}
664
665
666std::pair<unsigned, unsigned>
667ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000668 using namespace llvm::support;
669 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 return std::make_pair(KeyLen, DataLen);
672}
673
674ASTSelectorLookupTrait::internal_key_type
675ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000676 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
679 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
680 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000681 if (N == 0)
682 return SelTable.getNullarySelector(FirstII);
683 else if (N == 1)
684 return SelTable.getUnarySelector(FirstII);
685
686 SmallVector<IdentifierInfo *, 16> Args;
687 Args.push_back(FirstII);
688 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000689 Args.push_back(Reader.getLocalIdentifier(
690 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000691
692 return SelTable.getSelector(N, Args.data());
693}
694
695ASTSelectorLookupTrait::data_type
696ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
697 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000698 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000699
700 data_type Result;
701
Justin Bogner57ba0b22014-03-28 22:03:24 +0000702 Result.ID = Reader.getGlobalSelectorID(
703 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000704 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
705 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
706 Result.InstanceBits = FullInstanceBits & 0x3;
707 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
708 Result.FactoryBits = FullFactoryBits & 0x3;
709 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
710 unsigned NumInstanceMethods = FullInstanceBits >> 3;
711 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000712
713 // Load instance methods
714 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 Result.Instance.push_back(Method);
718 }
719
720 // Load factory methods
721 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000722 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
723 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 Result.Factory.push_back(Method);
725 }
726
727 return Result;
728}
729
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000730unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
731 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732}
733
734std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000736 using namespace llvm::support;
737 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 return std::make_pair(KeyLen, DataLen);
740}
741
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000742ASTIdentifierLookupTraitBase::internal_key_type
743ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000745 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000746}
747
Douglas Gregordcf25082013-02-11 18:16:18 +0000748/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000749static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
750 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000751 return II.hadMacroDefinition() ||
752 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000753 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000754 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000755 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
756 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000757}
758
Richard Smith76c2f2c2015-07-17 20:09:43 +0000759static bool readBit(unsigned &Bits) {
760 bool Value = Bits & 0x1;
761 Bits >>= 1;
762 return Value;
763}
764
Richard Smith79bf9202015-08-24 03:33:22 +0000765IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
766 using namespace llvm::support;
767 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
768 return Reader.getGlobalIdentifierID(F, RawID >> 1);
769}
770
Guy Benyei11169dd2012-12-18 14:30:41 +0000771IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
772 const unsigned char* d,
773 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000774 using namespace llvm::support;
775 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000776 bool IsInteresting = RawID & 0x01;
777
778 // Wipe out the "is interesting" bit.
779 RawID = RawID >> 1;
780
Richard Smith76c2f2c2015-07-17 20:09:43 +0000781 // Build the IdentifierInfo and link the identifier ID with it.
782 IdentifierInfo *II = KnownII;
783 if (!II) {
784 II = &Reader.getIdentifierTable().getOwn(k);
785 KnownII = II;
786 }
787 if (!II->isFromAST()) {
788 II->setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +0000789 bool IsModule = Reader.PP.getCurrentModule() != nullptr;
790 if (isInterestingIdentifier(Reader, *II, IsModule))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 II->setChangedSinceDeserialization();
792 }
793 Reader.markIdentifierUpToDate(II);
794
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
796 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000797 // For uninteresting identifiers, there's nothing else to do. Just notify
798 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 return II;
801 }
802
Justin Bogner57ba0b22014-03-28 22:03:24 +0000803 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
804 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000805 bool CPlusPlusOperatorKeyword = readBit(Bits);
806 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000807 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000808 bool Poisoned = readBit(Bits);
809 bool ExtensionToken = readBit(Bits);
810 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000811
812 assert(Bits == 0 && "Extra bits in the identifier?");
813 DataLen -= 8;
814
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 // Set or check the various bits in the IdentifierInfo structure.
816 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000817 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000818 II->revertTokenIDToIdentifier();
819 if (!F.isModule())
820 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
821 else if (HasRevertedBuiltin && II->getBuiltinID()) {
822 II->revertBuiltin();
823 assert((II->hasRevertedBuiltin() ||
824 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
825 "Incorrect ObjC keyword or builtin ID");
826 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 assert(II->isExtensionToken() == ExtensionToken &&
828 "Incorrect extension token flag");
829 (void)ExtensionToken;
830 if (Poisoned)
831 II->setIsPoisoned(true);
832 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
833 "Incorrect C++ operator keyword flag");
834 (void)CPlusPlusOperatorKeyword;
835
836 // If this identifier is a macro, deserialize the macro
837 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000838 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 uint32_t MacroDirectivesOffset =
840 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000841 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000842
Richard Smithd7329392015-04-21 21:46:32 +0000843 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000844 }
845
846 Reader.SetIdentifierInfo(ID, II);
847
848 // Read all of the declarations visible at global scope with this
849 // name.
850 if (DataLen > 0) {
851 SmallVector<uint32_t, 4> DeclIDs;
852 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000853 DeclIDs.push_back(Reader.getGlobalDeclID(
854 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000855 Reader.SetGloballyVisibleDecls(II, DeclIDs);
856 }
857
858 return II;
859}
860
Richard Smitha06c7e62015-08-26 23:55:49 +0000861DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
862 : Kind(Name.getNameKind()) {
863 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000865 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 break;
867 case DeclarationName::ObjCZeroArgSelector:
868 case DeclarationName::ObjCOneArgSelector:
869 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000870 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 break;
872 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000873 Data = Name.getCXXOverloadedOperator();
874 break;
875 case DeclarationName::CXXLiteralOperatorName:
876 Data = (uint64_t)Name.getCXXLiteralIdentifier();
877 break;
878 case DeclarationName::CXXConstructorName:
879 case DeclarationName::CXXDestructorName:
880 case DeclarationName::CXXConversionFunctionName:
881 case DeclarationName::CXXUsingDirective:
882 Data = 0;
883 break;
884 }
885}
886
887unsigned DeclarationNameKey::getHash() const {
888 llvm::FoldingSetNodeID ID;
889 ID.AddInteger(Kind);
890
891 switch (Kind) {
892 case DeclarationName::Identifier:
893 case DeclarationName::CXXLiteralOperatorName:
894 ID.AddString(((IdentifierInfo*)Data)->getName());
895 break;
896 case DeclarationName::ObjCZeroArgSelector:
897 case DeclarationName::ObjCOneArgSelector:
898 case DeclarationName::ObjCMultiArgSelector:
899 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
900 break;
901 case DeclarationName::CXXOperatorName:
902 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 break;
904 case DeclarationName::CXXConstructorName:
905 case DeclarationName::CXXDestructorName:
906 case DeclarationName::CXXConversionFunctionName:
907 case DeclarationName::CXXUsingDirective:
908 break;
909 }
910
911 return ID.ComputeHash();
912}
913
Richard Smithd88a7f12015-09-01 20:35:42 +0000914ModuleFile *
915ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
916 using namespace llvm::support;
917 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
918 return Reader.getLocalModuleFile(F, ModuleFileID);
919}
920
Guy Benyei11169dd2012-12-18 14:30:41 +0000921std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000922ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 using namespace llvm::support;
924 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
925 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 return std::make_pair(KeyLen, DataLen);
927}
928
Richard Smitha06c7e62015-08-26 23:55:49 +0000929ASTDeclContextNameLookupTrait::internal_key_type
930ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000932
Richard Smitha06c7e62015-08-26 23:55:49 +0000933 auto Kind = (DeclarationName::NameKind)*d++;
934 uint64_t Data;
935 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000937 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::ObjCZeroArgSelector:
941 case DeclarationName::ObjCOneArgSelector:
942 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000943 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 (uint64_t)Reader.getLocalSelector(
945 F, endian::readNext<uint32_t, little, unaligned>(
946 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 break;
948 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000949 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 break;
951 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000952 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000953 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 break;
955 case DeclarationName::CXXConstructorName:
956 case DeclarationName::CXXDestructorName:
957 case DeclarationName::CXXConversionFunctionName:
958 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +0000959 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 }
962
Richard Smitha06c7e62015-08-26 23:55:49 +0000963 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000964}
965
Richard Smithd88a7f12015-09-01 20:35:42 +0000966void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
967 const unsigned char *d,
968 unsigned DataLen,
969 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000970 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +0000971 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
972 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
973 Val.insert(Reader.getGlobalDeclID(F, LocalID));
974 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000975}
976
Richard Smith0f4e2c42015-08-06 04:23:48 +0000977bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
978 BitstreamCursor &Cursor,
979 uint64_t Offset,
980 DeclContext *DC) {
981 assert(Offset != 0);
982
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000984 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985
Richard Smith0f4e2c42015-08-06 04:23:48 +0000986 RecordData Record;
987 StringRef Blob;
988 unsigned Code = Cursor.ReadCode();
989 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
990 if (RecCode != DECL_CONTEXT_LEXICAL) {
991 Error("Expected lexical block");
992 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 }
994
Richard Smith82f8fcd2015-08-06 22:07:25 +0000995 assert(!isa<TranslationUnitDecl>(DC) &&
996 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000997 // If we are handling a C++ class template instantiation, we can see multiple
998 // lexical updates for the same record. It's important that we select only one
999 // of them, so that field numbering works properly. Just pick the first one we
1000 // see.
1001 auto &Lex = LexicalDecls[DC];
1002 if (!Lex.first) {
1003 Lex = std::make_pair(
1004 &M, llvm::makeArrayRef(
1005 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1006 Blob.data()),
1007 Blob.size() / 4));
1008 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001009 DC->setHasExternalLexicalStorage(true);
1010 return false;
1011}
Guy Benyei11169dd2012-12-18 14:30:41 +00001012
Richard Smith0f4e2c42015-08-06 04:23:48 +00001013bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1014 BitstreamCursor &Cursor,
1015 uint64_t Offset,
1016 DeclID ID) {
1017 assert(Offset != 0);
1018
1019 SavedStreamPosition SavedPosition(Cursor);
1020 Cursor.JumpToBit(Offset);
1021
1022 RecordData Record;
1023 StringRef Blob;
1024 unsigned Code = Cursor.ReadCode();
1025 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1026 if (RecCode != DECL_CONTEXT_VISIBLE) {
1027 Error("Expected visible lookup table block");
1028 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 }
1030
Richard Smith0f4e2c42015-08-06 04:23:48 +00001031 // We can't safely determine the primary context yet, so delay attaching the
1032 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001033 auto *Data = (const unsigned char*)Blob.data();
1034 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 return false;
1036}
1037
1038void ASTReader::Error(StringRef Msg) {
1039 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001040 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1041 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001042 Diag(diag::note_module_cache_path)
1043 << PP.getHeaderSearchInfo().getModuleCachePath();
1044 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001045}
1046
1047void ASTReader::Error(unsigned DiagID,
1048 StringRef Arg1, StringRef Arg2) {
1049 if (Diags.isDiagnosticInFlight())
1050 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1051 else
1052 Diag(DiagID) << Arg1 << Arg2;
1053}
1054
1055//===----------------------------------------------------------------------===//
1056// Source Manager Deserialization
1057//===----------------------------------------------------------------------===//
1058
1059/// \brief Read the line table in the source manager block.
1060/// \returns true if there was an error.
1061bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001062 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 unsigned Idx = 0;
1064 LineTableInfo &LineTable = SourceMgr.getLineTable();
1065
1066 // Parse the file names
1067 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001068 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001070 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1072 }
Richard Smith63078492015-09-01 07:41:55 +00001073 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001074
1075 // Parse the line entries
1076 std::vector<LineEntry> Entries;
1077 while (Idx < Record.size()) {
1078 int FID = Record[Idx++];
1079 assert(FID >= 0 && "Serialized line entries for non-local file.");
1080 // Remap FileID from 1-based old view.
1081 FID += F.SLocEntryBaseID - 1;
1082
1083 // Extract the line entries
1084 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001085 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001086 Entries.clear();
1087 Entries.reserve(NumEntries);
1088 for (unsigned I = 0; I != NumEntries; ++I) {
1089 unsigned FileOffset = Record[Idx++];
1090 unsigned LineNo = Record[Idx++];
1091 int FilenameID = FileIDs[Record[Idx++]];
1092 SrcMgr::CharacteristicKind FileKind
1093 = (SrcMgr::CharacteristicKind)Record[Idx++];
1094 unsigned IncludeOffset = Record[Idx++];
1095 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1096 FileKind, IncludeOffset));
1097 }
1098 LineTable.AddEntry(FileID::get(FID), Entries);
1099 }
1100
1101 return false;
1102}
1103
1104/// \brief Read a source manager block
1105bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1106 using namespace SrcMgr;
1107
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001108 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001109
1110 // Set the source-location entry cursor to the current position in
1111 // the stream. This cursor will be used to read the contents of the
1112 // source manager block initially, and then lazily read
1113 // source-location entries as needed.
1114 SLocEntryCursor = F.Stream;
1115
1116 // The stream itself is going to skip over the source manager block.
1117 if (F.Stream.SkipBlock()) {
1118 Error("malformed block record in AST file");
1119 return true;
1120 }
1121
1122 // Enter the source manager block.
1123 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1124 Error("malformed source manager block record in AST file");
1125 return true;
1126 }
1127
1128 RecordData Record;
1129 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001130 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1131
1132 switch (E.Kind) {
1133 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1134 case llvm::BitstreamEntry::Error:
1135 Error("malformed block record in AST file");
1136 return true;
1137 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001139 case llvm::BitstreamEntry::Record:
1140 // The interesting case.
1141 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001143
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001145 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001146 StringRef Blob;
1147 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 default: // Default behavior: ignore.
1149 break;
1150
1151 case SM_SLOC_FILE_ENTRY:
1152 case SM_SLOC_BUFFER_ENTRY:
1153 case SM_SLOC_EXPANSION_ENTRY:
1154 // Once we hit one of the source location entries, we're done.
1155 return false;
1156 }
1157 }
1158}
1159
1160/// \brief If a header file is not found at the path that we expect it to be
1161/// and the PCH file was moved from its original location, try to resolve the
1162/// file by assuming that header+PCH were moved together and the header is in
1163/// the same place relative to the PCH.
1164static std::string
1165resolveFileRelativeToOriginalDir(const std::string &Filename,
1166 const std::string &OriginalDir,
1167 const std::string &CurrDir) {
1168 assert(OriginalDir != CurrDir &&
1169 "No point trying to resolve the file if the PCH dir didn't change");
1170 using namespace llvm::sys;
1171 SmallString<128> filePath(Filename);
1172 fs::make_absolute(filePath);
1173 assert(path::is_absolute(OriginalDir));
1174 SmallString<128> currPCHPath(CurrDir);
1175
1176 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1177 fileDirE = path::end(path::parent_path(filePath));
1178 path::const_iterator origDirI = path::begin(OriginalDir),
1179 origDirE = path::end(OriginalDir);
1180 // Skip the common path components from filePath and OriginalDir.
1181 while (fileDirI != fileDirE && origDirI != origDirE &&
1182 *fileDirI == *origDirI) {
1183 ++fileDirI;
1184 ++origDirI;
1185 }
1186 for (; origDirI != origDirE; ++origDirI)
1187 path::append(currPCHPath, "..");
1188 path::append(currPCHPath, fileDirI, fileDirE);
1189 path::append(currPCHPath, path::filename(Filename));
1190 return currPCHPath.str();
1191}
1192
1193bool ASTReader::ReadSLocEntry(int ID) {
1194 if (ID == 0)
1195 return false;
1196
1197 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1198 Error("source location entry ID out-of-range for AST file");
1199 return true;
1200 }
1201
1202 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1203 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001204 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 unsigned BaseOffset = F->SLocEntryBaseOffset;
1206
1207 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001208 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1209 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 Error("incorrectly-formatted source location entry in AST file");
1211 return true;
1212 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001213
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001215 StringRef Blob;
1216 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 default:
1218 Error("incorrectly-formatted source location entry in AST file");
1219 return true;
1220
1221 case SM_SLOC_FILE_ENTRY: {
1222 // We will detect whether a file changed and return 'Failure' for it, but
1223 // we will also try to fail gracefully by setting up the SLocEntry.
1224 unsigned InputID = Record[4];
1225 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001226 const FileEntry *File = IF.getFile();
1227 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001228
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001229 // Note that we only check if a File was returned. If it was out-of-date
1230 // we have complained but we will continue creating a FileID to recover
1231 // gracefully.
1232 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 return true;
1234
1235 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1236 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1237 // This is the module's main file.
1238 IncludeLoc = getImportLocation(F);
1239 }
1240 SrcMgr::CharacteristicKind
1241 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1242 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1243 ID, BaseOffset + Record[0]);
1244 SrcMgr::FileInfo &FileInfo =
1245 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1246 FileInfo.NumCreatedFIDs = Record[5];
1247 if (Record[3])
1248 FileInfo.setHasLineDirectives();
1249
1250 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1251 unsigned NumFileDecls = Record[7];
1252 if (NumFileDecls) {
1253 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1254 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1255 NumFileDecls));
1256 }
1257
1258 const SrcMgr::ContentCache *ContentCache
1259 = SourceMgr.getOrCreateContentCache(File,
1260 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1261 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001262 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1263 !ContentCache->getRawBuffer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001264 unsigned Code = SLocEntryCursor.ReadCode();
1265 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267
1268 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1269 Error("AST record has invalid code");
1270 return true;
1271 }
1272
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001273 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001274 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001275 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 }
1277
1278 break;
1279 }
1280
1281 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001282 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001283 unsigned Offset = Record[0];
1284 SrcMgr::CharacteristicKind
1285 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1286 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001287 if (IncludeLoc.isInvalid() &&
1288 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001289 IncludeLoc = getImportLocation(F);
1290 }
1291 unsigned Code = SLocEntryCursor.ReadCode();
1292 Record.clear();
1293 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001294 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001295
1296 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1297 Error("AST record has invalid code");
1298 return true;
1299 }
1300
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001301 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1302 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001303 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001304 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 break;
1306 }
1307
1308 case SM_SLOC_EXPANSION_ENTRY: {
1309 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1310 SourceMgr.createExpansionLoc(SpellingLoc,
1311 ReadSourceLocation(*F, Record[2]),
1312 ReadSourceLocation(*F, Record[3]),
1313 Record[4],
1314 ID,
1315 BaseOffset + Record[0]);
1316 break;
1317 }
1318 }
1319
1320 return false;
1321}
1322
1323std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1324 if (ID == 0)
1325 return std::make_pair(SourceLocation(), "");
1326
1327 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1328 Error("source location entry ID out-of-range for AST file");
1329 return std::make_pair(SourceLocation(), "");
1330 }
1331
1332 // Find which module file this entry lands in.
1333 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001334 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001335 return std::make_pair(SourceLocation(), "");
1336
1337 // FIXME: Can we map this down to a particular submodule? That would be
1338 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001339 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001340}
1341
1342/// \brief Find the location where the module F is imported.
1343SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1344 if (F->ImportLoc.isValid())
1345 return F->ImportLoc;
1346
1347 // Otherwise we have a PCH. It's considered to be "imported" at the first
1348 // location of its includer.
1349 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001350 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001351 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001352 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 return F->ImportedBy[0]->FirstLoc;
1355}
1356
1357/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1358/// specified cursor. Read the abbreviations that are at the top of the block
1359/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001360bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001361 if (Cursor.EnterSubBlock(BlockID))
1362 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001363
1364 while (true) {
1365 uint64_t Offset = Cursor.GetCurrentBitNo();
1366 unsigned Code = Cursor.ReadCode();
1367
1368 // We expect all abbrevs to be at the start of the block.
1369 if (Code != llvm::bitc::DEFINE_ABBREV) {
1370 Cursor.JumpToBit(Offset);
1371 return false;
1372 }
1373 Cursor.ReadAbbrevRecord();
1374 }
1375}
1376
Richard Smithe40f2ba2013-08-07 21:41:30 +00001377Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001378 unsigned &Idx) {
1379 Token Tok;
1380 Tok.startToken();
1381 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1382 Tok.setLength(Record[Idx++]);
1383 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1384 Tok.setIdentifierInfo(II);
1385 Tok.setKind((tok::TokenKind)Record[Idx++]);
1386 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1387 return Tok;
1388}
1389
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001391 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001392
1393 // Keep track of where we are in the stream, then jump back there
1394 // after reading this macro.
1395 SavedStreamPosition SavedPosition(Stream);
1396
1397 Stream.JumpToBit(Offset);
1398 RecordData Record;
1399 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001400 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001403 // Advance to the next record, but if we get to the end of the block, don't
1404 // pop it (removing all the abbreviations from the cursor) since we want to
1405 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001406 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001407 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1408
1409 switch (Entry.Kind) {
1410 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1411 case llvm::BitstreamEntry::Error:
1412 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001413 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001414 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001415 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001416 case llvm::BitstreamEntry::Record:
1417 // The interesting case.
1418 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001419 }
1420
1421 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 Record.clear();
1423 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001424 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001426 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001427 case PP_MACRO_DIRECTIVE_HISTORY:
1428 return Macro;
1429
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 case PP_MACRO_OBJECT_LIKE:
1431 case PP_MACRO_FUNCTION_LIKE: {
1432 // If we already have a macro, that means that we've hit the end
1433 // of the definition of the macro we were looking for. We're
1434 // done.
1435 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001436 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001437
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001438 unsigned NextIndex = 1; // Skip identifier ID.
1439 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001441 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001442 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001444 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001445
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1447 // Decode function-like macro info.
1448 bool isC99VarArgs = Record[NextIndex++];
1449 bool isGNUVarArgs = Record[NextIndex++];
1450 bool hasCommaPasting = Record[NextIndex++];
1451 MacroArgs.clear();
1452 unsigned NumArgs = Record[NextIndex++];
1453 for (unsigned i = 0; i != NumArgs; ++i)
1454 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1455
1456 // Install function-like macro info.
1457 MI->setIsFunctionLike();
1458 if (isC99VarArgs) MI->setIsC99Varargs();
1459 if (isGNUVarArgs) MI->setIsGNUVarargs();
1460 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001461 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001462 }
1463
Guy Benyei11169dd2012-12-18 14:30:41 +00001464 // Remember that we saw this macro last so that we add the tokens that
1465 // form its body to it.
1466 Macro = MI;
1467
1468 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1469 Record[NextIndex]) {
1470 // We have a macro definition. Register the association
1471 PreprocessedEntityID
1472 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1473 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001474 PreprocessingRecord::PPEntityID PPID =
1475 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1476 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1477 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001478 if (PPDef)
1479 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 }
1481
1482 ++NumMacrosRead;
1483 break;
1484 }
1485
1486 case PP_TOKEN: {
1487 // If we see a TOKEN before a PP_MACRO_*, then the file is
1488 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001489 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001490
John McCallf413f5e2013-05-03 00:10:13 +00001491 unsigned Idx = 0;
1492 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 Macro->AddTokenToBody(Tok);
1494 break;
1495 }
1496 }
1497 }
1498}
1499
1500PreprocessedEntityID
1501ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1502 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1503 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1504 assert(I != M.PreprocessedEntityRemap.end()
1505 && "Invalid index into preprocessed entity index remap");
1506
1507 return LocalID + I->second;
1508}
1509
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001510unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1511 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001513
Guy Benyei11169dd2012-12-18 14:30:41 +00001514HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001516 internal_key_type ikey = {FE->getSize(),
1517 M.HasTimestamps ? FE->getModificationTime() : 0,
1518 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001519 return ikey;
1520}
Guy Benyei11169dd2012-12-18 14:30:41 +00001521
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001523 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 return false;
1525
Richard Smith7ed1bc92014-12-05 22:42:13 +00001526 if (llvm::sys::path::is_absolute(a.Filename) &&
1527 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001528 return true;
1529
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001531 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001532 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1533 if (!Key.Imported)
1534 return FileMgr.getFile(Key.Filename);
1535
1536 std::string Resolved = Key.Filename;
1537 Reader.ResolveImportedPath(M, Resolved);
1538 return FileMgr.getFile(Resolved);
1539 };
1540
1541 const FileEntry *FEA = GetFile(a);
1542 const FileEntry *FEB = GetFile(b);
1543 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001544}
1545
1546std::pair<unsigned, unsigned>
1547HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001548 using namespace llvm::support;
1549 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001551 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001552}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553
1554HeaderFileInfoTrait::internal_key_type
1555HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001556 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001557 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1559 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001560 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001561 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001562 return ikey;
1563}
1564
Guy Benyei11169dd2012-12-18 14:30:41 +00001565HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001566HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001567 unsigned DataLen) {
1568 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001569 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 HeaderFileInfo HFI;
1571 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001572 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1573 HFI.isImport |= (Flags >> 4) & 0x01;
1574 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1575 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001577 // FIXME: Find a better way to handle this. Maybe just store a
1578 // "has been included" flag?
1579 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1580 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1582 M, endian::readNext<uint32_t, little, unaligned>(d));
1583 if (unsigned FrameworkOffset =
1584 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 // The framework offset is 1 greater than the actual offset,
1586 // since 0 is used as an indicator for "no framework name".
1587 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1588 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1589 }
Richard Smith386bb072015-08-18 23:42:23 +00001590
1591 assert((End - d) % 4 == 0 &&
1592 "Wrong data length in HeaderFileInfo deserialization");
1593 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001594 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001595 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1596 LocalSMID >>= 2;
1597
1598 // This header is part of a module. Associate it with the module to enable
1599 // implicit module import.
1600 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1601 Module *Mod = Reader.getSubmodule(GlobalSMID);
1602 FileManager &FileMgr = Reader.getFileManager();
1603 ModuleMap &ModMap =
1604 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1605
1606 std::string Filename = key.Filename;
1607 if (key.Imported)
1608 Reader.ResolveImportedPath(M, Filename);
1609 // FIXME: This is not always the right filename-as-written, but we're not
1610 // going to use this information to rebuild the module, so it doesn't make
1611 // a lot of difference.
1612 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001613 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1614 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001615 }
1616
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 // This HeaderFileInfo was externally loaded.
1618 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001619 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 return HFI;
1621}
1622
Richard Smithd7329392015-04-21 21:46:32 +00001623void ASTReader::addPendingMacro(IdentifierInfo *II,
1624 ModuleFile *M,
1625 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001626 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1627 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001628}
1629
1630void ASTReader::ReadDefinedMacros() {
1631 // Note that we are loading defined macros.
1632 Deserializing Macros(this);
1633
Pete Cooper57d3f142015-07-30 17:22:52 +00001634 for (auto &I : llvm::reverse(ModuleMgr)) {
1635 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636
1637 // If there was no preprocessor block, skip this file.
1638 if (!MacroCursor.getBitStreamReader())
1639 continue;
1640
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001641 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001642 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001643
1644 RecordData Record;
1645 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001646 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1647
1648 switch (E.Kind) {
1649 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1650 case llvm::BitstreamEntry::Error:
1651 Error("malformed block record in AST file");
1652 return;
1653 case llvm::BitstreamEntry::EndBlock:
1654 goto NextCursor;
1655
1656 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001657 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001658 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001659 default: // Default behavior: ignore.
1660 break;
1661
1662 case PP_MACRO_OBJECT_LIKE:
1663 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001664 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001665 break;
1666
1667 case PP_TOKEN:
1668 // Ignore tokens.
1669 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001670 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 break;
1672 }
1673 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001674 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001675 }
1676}
1677
1678namespace {
1679 /// \brief Visitor class used to look up identifirs in an AST file.
1680 class IdentifierLookupVisitor {
1681 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001682 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001684 unsigned &NumIdentifierLookups;
1685 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001689 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1690 unsigned &NumIdentifierLookups,
1691 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001692 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1693 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001694 NumIdentifierLookups(NumIdentifierLookups),
1695 NumIdentifierLookupHits(NumIdentifierLookupHits),
1696 Found()
1697 {
1698 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001699
1700 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001702 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001704
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 ASTIdentifierLookupTable *IdTable
1706 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1707 if (!IdTable)
1708 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001709
1710 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001711 Found);
1712 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001713 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001714 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 if (Pos == IdTable->end())
1716 return false;
1717
1718 // Dereferencing the iterator has the effect of building the
1719 // IdentifierInfo node and populating it with the various
1720 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001721 ++NumIdentifierLookupHits;
1722 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 return true;
1724 }
1725
1726 // \brief Retrieve the identifier info found within the module
1727 // files.
1728 IdentifierInfo *getIdentifierInfo() const { return Found; }
1729 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001730}
Guy Benyei11169dd2012-12-18 14:30:41 +00001731
1732void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1733 // Note that we are loading an identifier.
1734 Deserializing AnIdentifier(this);
1735
1736 unsigned PriorGeneration = 0;
1737 if (getContext().getLangOpts().Modules)
1738 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001739
1740 // If there is a global index, look there first to determine which modules
1741 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001742 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001743 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001744 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001745 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1746 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001747 }
1748 }
1749
Douglas Gregor7211ac12013-01-25 23:32:03 +00001750 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001751 NumIdentifierLookups,
1752 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001753 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 markIdentifierUpToDate(&II);
1755}
1756
1757void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1758 if (!II)
1759 return;
1760
1761 II->setOutOfDate(false);
1762
1763 // Update the generation for this identifier.
1764 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001765 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001766}
1767
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001768void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1769 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001770 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001771
1772 BitstreamCursor &Cursor = M.MacroCursor;
1773 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001774 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775
Richard Smith713369b2015-04-23 20:40:50 +00001776 struct ModuleMacroRecord {
1777 SubmoduleID SubModID;
1778 MacroInfo *MI;
1779 SmallVector<SubmoduleID, 8> Overrides;
1780 };
1781 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001782
Richard Smithd7329392015-04-21 21:46:32 +00001783 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1784 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1785 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001787 while (true) {
1788 llvm::BitstreamEntry Entry =
1789 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1790 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1791 Error("malformed block record in AST file");
1792 return;
1793 }
1794
1795 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001796 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001797 case PP_MACRO_DIRECTIVE_HISTORY:
1798 break;
1799
1800 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001801 ModuleMacros.push_back(ModuleMacroRecord());
1802 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001803 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1804 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001805 for (int I = 2, N = Record.size(); I != N; ++I)
1806 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001807 continue;
1808 }
1809
1810 default:
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 // We found the macro directive history; that's the last record
1816 // for this macro.
1817 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001818 }
1819
Richard Smithd7329392015-04-21 21:46:32 +00001820 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001821 {
1822 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001823 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001824 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001825 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001826 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001827 Module *Mod = getSubmodule(ModID);
1828 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001829 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001830 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001831 }
1832
1833 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001834 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001835 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001836 }
1837 }
1838
1839 // Don't read the directive history for a module; we don't have anywhere
1840 // to put it.
1841 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1842 return;
1843
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001845 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001846 unsigned Idx = 0, N = Record.size();
1847 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001848 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001850 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1851 switch (K) {
1852 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001853 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001854 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001855 break;
1856 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001857 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001858 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001859 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001860 }
1861 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001862 bool isPublic = Record[Idx++];
1863 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1864 break;
1865 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001866
1867 if (!Latest)
1868 Latest = MD;
1869 if (Earliest)
1870 Earliest->setPrevious(MD);
1871 Earliest = MD;
1872 }
1873
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001874 if (Latest)
1875 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876}
1877
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001878ASTReader::InputFileInfo
1879ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001880 // Go find this input file.
1881 BitstreamCursor &Cursor = F.InputFilesCursor;
1882 SavedStreamPosition SavedPosition(Cursor);
1883 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1884
1885 unsigned Code = Cursor.ReadCode();
1886 RecordData Record;
1887 StringRef Blob;
1888
1889 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1890 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1891 "invalid record type for input file");
1892 (void)Result;
1893
1894 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001895 InputFileInfo R;
1896 R.StoredSize = static_cast<off_t>(Record[1]);
1897 R.StoredTime = static_cast<time_t>(Record[2]);
1898 R.Overridden = static_cast<bool>(Record[3]);
1899 R.Transient = static_cast<bool>(Record[4]);
1900 R.Filename = Blob;
1901 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001902 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001903}
1904
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001905InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001906 // If this ID is bogus, just return an empty input file.
1907 if (ID == 0 || ID > F.InputFilesLoaded.size())
1908 return InputFile();
1909
1910 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001911 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 return F.InputFilesLoaded[ID-1];
1913
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001914 if (F.InputFilesLoaded[ID-1].isNotFound())
1915 return InputFile();
1916
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001918 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 SavedStreamPosition SavedPosition(Cursor);
1920 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1921
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001922 InputFileInfo FI = readInputFileInfo(F, ID);
1923 off_t StoredSize = FI.StoredSize;
1924 time_t StoredTime = FI.StoredTime;
1925 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001926 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001927 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001928
Richard Smitha8cfffa2015-11-26 02:04:16 +00001929 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00001930
1931 // If we didn't find the file, resolve it relative to the
1932 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001933 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001934 F.OriginalDir != CurrentDir) {
1935 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1936 F.OriginalDir,
1937 CurrentDir);
1938 if (!Resolved.empty())
1939 File = FileMgr.getFile(Resolved);
1940 }
1941
1942 // For an overridden file, create a virtual file with the stored
1943 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001944 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00001945 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00001946
Craig Toppera13603a2014-05-22 05:54:18 +00001947 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001948 if (Complain) {
1949 std::string ErrorStr = "could not find file '";
1950 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00001951 ErrorStr += "' referenced by AST file '";
1952 ErrorStr += F.FileName;
1953 ErrorStr += "'";
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001955 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001956 // Record that we didn't find the file.
1957 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1958 return InputFile();
1959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001960
Ben Langmuir198c1682014-03-07 07:27:49 +00001961 // Check if there was a request to override the contents of the file
1962 // that was part of the precompiled header. Overridding such a file
1963 // can lead to problems when lexing using the source locations from the
1964 // PCH.
1965 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00001966 // FIXME: Reject if the overrides are different.
1967 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001968 if (Complain)
1969 Error(diag::err_fe_pch_file_overridden, Filename);
1970 // After emitting the diagnostic, recover by disabling the override so
1971 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001972 //
1973 // FIXME: This recovery is just as broken as the original state; there may
1974 // be another precompiled module that's using the overridden contents, or
1975 // we might be half way through parsing it. Instead, we should treat the
1976 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 SM.disableFileContentsOverride(File);
1978 // The FileEntry is a virtual file entry with the size of the contents
1979 // that would override the original contents. Set it to the original's
1980 // size/time.
1981 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1982 StoredSize, StoredTime);
1983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001984
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 bool IsOutOfDate = false;
1986
1987 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001988 if (!Overridden && //
1989 (StoredSize != File->getSize() ||
1990#if defined(LLVM_ON_WIN32)
1991 false
1992#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 // In our regression testing, the Windows file system seems to
1994 // have inconsistent modification times that sometimes
1995 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001996 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001997 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1998 (StoredTime && StoredTime != File->getModificationTime() &&
1999 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00002000#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002001 )) {
2002 if (Complain) {
2003 // Build a list of the PCH imports that got us here (in reverse).
2004 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2005 while (ImportStack.back()->ImportedBy.size() > 0)
2006 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002007
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 // The top-level PCH is stale.
2009 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2010 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002011
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // Print the import stack.
2013 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2014 Diag(diag::note_pch_required_by)
2015 << Filename << ImportStack[0]->FileName;
2016 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002017 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002019 }
2020
Ben Langmuir198c1682014-03-07 07:27:49 +00002021 if (!Diags.isDiagnosticInFlight())
2022 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 }
2024
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002027 // FIXME: If the file is overridden and we've already opened it,
2028 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002029
Richard Smitha8cfffa2015-11-26 02:04:16 +00002030 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002031
2032 // Note that we've loaded this input file.
2033 F.InputFilesLoaded[ID-1] = IF;
2034 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002035}
2036
Richard Smith7ed1bc92014-12-05 22:42:13 +00002037/// \brief If we are loading a relocatable PCH or module file, and the filename
2038/// is not an absolute path, add the system or module root to the beginning of
2039/// the file name.
2040void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2041 // Resolve relative to the base directory, if we have one.
2042 if (!M.BaseDirectory.empty())
2043 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002044}
2045
Richard Smith7ed1bc92014-12-05 22:42:13 +00002046void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2048 return;
2049
Richard Smith7ed1bc92014-12-05 22:42:13 +00002050 SmallString<128> Buffer;
2051 llvm::sys::path::append(Buffer, Prefix, Filename);
2052 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002053}
2054
Richard Smith0f99d6a2015-08-09 08:48:41 +00002055static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2056 switch (ARR) {
2057 case ASTReader::Failure: return true;
2058 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2059 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2060 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2061 case ASTReader::ConfigurationMismatch:
2062 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2063 case ASTReader::HadErrors: return true;
2064 case ASTReader::Success: return false;
2065 }
2066
2067 llvm_unreachable("unknown ASTReadResult");
2068}
2069
Richard Smith0516b182015-09-08 19:40:14 +00002070ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2071 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2072 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2073 std::string &SuggestedPredefines) {
2074 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2075 return Failure;
2076
2077 // Read all of the records in the options block.
2078 RecordData Record;
2079 ASTReadResult Result = Success;
2080 while (1) {
2081 llvm::BitstreamEntry Entry = Stream.advance();
2082
2083 switch (Entry.Kind) {
2084 case llvm::BitstreamEntry::Error:
2085 case llvm::BitstreamEntry::SubBlock:
2086 return Failure;
2087
2088 case llvm::BitstreamEntry::EndBlock:
2089 return Result;
2090
2091 case llvm::BitstreamEntry::Record:
2092 // The interesting case.
2093 break;
2094 }
2095
2096 // Read and process a record.
2097 Record.clear();
2098 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2099 case LANGUAGE_OPTIONS: {
2100 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2101 if (ParseLanguageOptions(Record, Complain, Listener,
2102 AllowCompatibleConfigurationMismatch))
2103 Result = ConfigurationMismatch;
2104 break;
2105 }
2106
2107 case TARGET_OPTIONS: {
2108 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2109 if (ParseTargetOptions(Record, Complain, Listener,
2110 AllowCompatibleConfigurationMismatch))
2111 Result = ConfigurationMismatch;
2112 break;
2113 }
2114
2115 case DIAGNOSTIC_OPTIONS: {
2116 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2117 if (!AllowCompatibleConfigurationMismatch &&
2118 ParseDiagnosticOptions(Record, Complain, Listener))
2119 return OutOfDate;
2120 break;
2121 }
2122
2123 case FILE_SYSTEM_OPTIONS: {
2124 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2125 if (!AllowCompatibleConfigurationMismatch &&
2126 ParseFileSystemOptions(Record, Complain, Listener))
2127 Result = ConfigurationMismatch;
2128 break;
2129 }
2130
2131 case HEADER_SEARCH_OPTIONS: {
2132 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2133 if (!AllowCompatibleConfigurationMismatch &&
2134 ParseHeaderSearchOptions(Record, Complain, Listener))
2135 Result = ConfigurationMismatch;
2136 break;
2137 }
2138
2139 case PREPROCESSOR_OPTIONS:
2140 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2141 if (!AllowCompatibleConfigurationMismatch &&
2142 ParsePreprocessorOptions(Record, Complain, Listener,
2143 SuggestedPredefines))
2144 Result = ConfigurationMismatch;
2145 break;
2146 }
2147 }
2148}
2149
Guy Benyei11169dd2012-12-18 14:30:41 +00002150ASTReader::ASTReadResult
2151ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002152 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002153 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002155 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002156 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002157
2158 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2159 Error("malformed block record in AST file");
2160 return Failure;
2161 }
2162
2163 // Read all of the records and blocks in the control block.
2164 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002165 unsigned NumInputs = 0;
2166 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002167 while (1) {
2168 llvm::BitstreamEntry Entry = Stream.advance();
2169
2170 switch (Entry.Kind) {
2171 case llvm::BitstreamEntry::Error:
2172 Error("malformed block record in AST file");
2173 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002174 case llvm::BitstreamEntry::EndBlock: {
2175 // Validate input files.
2176 const HeaderSearchOptions &HSOpts =
2177 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002178
Richard Smitha1825302014-10-23 22:18:29 +00002179 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002180 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2181 // loaded module files, ignore missing inputs.
2182 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002184
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002185 // If we are reading a module, we will create a verification timestamp,
2186 // so we verify all input files. Otherwise, verify only user input
2187 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002188
2189 unsigned N = NumUserInputs;
2190 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002191 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002192 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002193 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002194 N = NumInputs;
2195
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002196 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002197 InputFile IF = getInputFile(F, I+1, Complain);
2198 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002202
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002203 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002204 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002205
Ben Langmuircb69b572014-03-07 06:40:32 +00002206 if (Listener && Listener->needsInputFileVisitation()) {
2207 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2208 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002209 for (unsigned I = 0; I < N; ++I) {
2210 bool IsSystem = I >= NumUserInputs;
2211 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002212 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2213 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002214 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002215 }
2216
Richard Smith8a308ec2015-11-05 00:54:55 +00002217 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002218 }
2219
Chris Lattnere7b154b2013-01-19 21:39:22 +00002220 case llvm::BitstreamEntry::SubBlock:
2221 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 case INPUT_FILES_BLOCK_ID:
2223 F.InputFilesCursor = Stream;
2224 if (Stream.SkipBlock() || // Skip with the main cursor
2225 // Read the abbreviations
2226 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2227 Error("malformed block record in AST file");
2228 return Failure;
2229 }
2230 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002231
2232 case OPTIONS_BLOCK_ID:
2233 // If we're reading the first module for this group, check its options
2234 // are compatible with ours. For modules it imports, no further checking
2235 // is required, because we checked them when we built it.
2236 if (Listener && !ImportedBy) {
2237 // Should we allow the configuration of the module file to differ from
2238 // the configuration of the current translation unit in a compatible
2239 // way?
2240 //
2241 // FIXME: Allow this for files explicitly specified with -include-pch.
2242 bool AllowCompatibleConfigurationMismatch =
2243 F.Kind == MK_ExplicitModule;
2244
Richard Smith8a308ec2015-11-05 00:54:55 +00002245 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2246 AllowCompatibleConfigurationMismatch,
2247 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002248 if (Result == Failure) {
2249 Error("malformed block record in AST file");
2250 return Result;
2251 }
2252
Richard Smith8a308ec2015-11-05 00:54:55 +00002253 if (DisableValidation ||
2254 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2255 Result = Success;
2256
2257 // If we've diagnosed a problem, we're done.
2258 if (Result != Success &&
2259 isDiagnosedResult(Result, ClientLoadCapabilities))
Richard Smith0516b182015-09-08 19:40:14 +00002260 return Result;
2261 } else if (Stream.SkipBlock()) {
2262 Error("malformed block record in AST file");
2263 return Failure;
2264 }
2265 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002266
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002268 if (Stream.SkipBlock()) {
2269 Error("malformed block record in AST file");
2270 return Failure;
2271 }
2272 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002274
2275 case llvm::BitstreamEntry::Record:
2276 // The interesting case.
2277 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 }
2279
2280 // Read and process a record.
2281 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002282 StringRef Blob;
2283 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 case METADATA: {
2285 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2286 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002287 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2288 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 return VersionMismatch;
2290 }
2291
Richard Smithe75ee0f2015-08-17 07:13:32 +00002292 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2294 Diag(diag::err_pch_with_compiler_errors);
2295 return HadErrors;
2296 }
2297
2298 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002299 // Relative paths in a relocatable PCH are relative to our sysroot.
2300 if (F.RelocatablePCH)
2301 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002302
Richard Smithe75ee0f2015-08-17 07:13:32 +00002303 F.HasTimestamps = Record[5];
2304
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002306 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002307 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2308 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002309 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 return VersionMismatch;
2311 }
2312 break;
2313 }
2314
Ben Langmuir487ea142014-10-23 18:05:36 +00002315 case SIGNATURE:
2316 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2317 F.Signature = Record[0];
2318 break;
2319
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 case IMPORTS: {
2321 // Load each of the imported PCH files.
2322 unsigned Idx = 0, N = Record.size();
2323 while (Idx < N) {
2324 // Read information about the AST file.
2325 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2326 // The import location will be the local one for now; we will adjust
2327 // all import locations of module imports after the global source
2328 // location info are setup.
2329 SourceLocation ImportLoc =
2330 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002331 off_t StoredSize = (off_t)Record[Idx++];
2332 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002333 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002334 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002335
Richard Smith0f99d6a2015-08-09 08:48:41 +00002336 // If our client can't cope with us being out of date, we can't cope with
2337 // our dependency being missing.
2338 unsigned Capabilities = ClientLoadCapabilities;
2339 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2340 Capabilities &= ~ARR_Missing;
2341
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002343 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2344 Loaded, StoredSize, StoredModTime,
2345 StoredSignature, Capabilities);
2346
2347 // If we diagnosed a problem, produce a backtrace.
2348 if (isDiagnosedResult(Result, Capabilities))
2349 Diag(diag::note_module_file_imported_by)
2350 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2351
2352 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 case Failure: return Failure;
2354 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002355 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 case OutOfDate: return OutOfDate;
2357 case VersionMismatch: return VersionMismatch;
2358 case ConfigurationMismatch: return ConfigurationMismatch;
2359 case HadErrors: return HadErrors;
2360 case Success: break;
2361 }
2362 }
2363 break;
2364 }
2365
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 case ORIGINAL_FILE:
2367 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002368 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002370 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 break;
2372
2373 case ORIGINAL_FILE_ID:
2374 F.OriginalSourceFileID = FileID::get(Record[0]);
2375 break;
2376
2377 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002378 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 break;
2380
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002381 case MODULE_NAME:
2382 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002383 if (Listener)
2384 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002385 break;
2386
Richard Smith223d3f22014-12-06 03:21:08 +00002387 case MODULE_DIRECTORY: {
2388 assert(!F.ModuleName.empty() &&
2389 "MODULE_DIRECTORY found before MODULE_NAME");
2390 // If we've already loaded a module map file covering this module, we may
2391 // have a better path for it (relative to the current build).
2392 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2393 if (M && M->Directory) {
2394 // If we're implicitly loading a module, the base directory can't
2395 // change between the build and use.
2396 if (F.Kind != MK_ExplicitModule) {
2397 const DirectoryEntry *BuildDir =
2398 PP.getFileManager().getDirectory(Blob);
2399 if (!BuildDir || BuildDir != M->Directory) {
2400 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2401 Diag(diag::err_imported_module_relocated)
2402 << F.ModuleName << Blob << M->Directory->getName();
2403 return OutOfDate;
2404 }
2405 }
2406 F.BaseDirectory = M->Directory->getName();
2407 } else {
2408 F.BaseDirectory = Blob;
2409 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002410 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002411 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002412
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002413 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002414 if (ASTReadResult Result =
2415 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2416 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002417 break;
2418
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002419 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002420 NumInputs = Record[0];
2421 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002422 F.InputFileOffsets =
2423 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002424 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 break;
2426 }
2427 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002428}
2429
Ben Langmuir2c9af442014-04-10 17:57:43 +00002430ASTReader::ASTReadResult
2431ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002432 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433
2434 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2435 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002436 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 }
2438
2439 // Read all of the records and blocks for the AST file.
2440 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002441 while (1) {
2442 llvm::BitstreamEntry Entry = Stream.advance();
2443
2444 switch (Entry.Kind) {
2445 case llvm::BitstreamEntry::Error:
2446 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002447 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002448 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002449 // Outside of C++, we do not store a lookup map for the translation unit.
2450 // Instead, mark it as needing a lookup map to be built if this module
2451 // contains any declarations lexically within it (which it always does!).
2452 // This usually has no cost, since we very rarely need the lookup map for
2453 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002455 if (DC->hasExternalLexicalStorage() &&
2456 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458
Ben Langmuir2c9af442014-04-10 17:57:43 +00002459 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002461 case llvm::BitstreamEntry::SubBlock:
2462 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 case DECLTYPES_BLOCK_ID:
2464 // We lazily load the decls block, but we want to set up the
2465 // DeclsCursor cursor to point into it. Clone our current bitcode
2466 // cursor to it, enter the block and read the abbrevs in that block.
2467 // With the main cursor, we just skip over it.
2468 F.DeclsCursor = Stream;
2469 if (Stream.SkipBlock() || // Skip with the main cursor.
2470 // Read the abbrevs.
2471 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2472 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002473 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 }
2475 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002476
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 case PREPROCESSOR_BLOCK_ID:
2478 F.MacroCursor = Stream;
2479 if (!PP.getExternalSource())
2480 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002481
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 if (Stream.SkipBlock() ||
2483 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2484 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002485 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 }
2487 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2488 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002489
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 case PREPROCESSOR_DETAIL_BLOCK_ID:
2491 F.PreprocessorDetailCursor = Stream;
2492 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002493 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002495 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002496 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002497 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002499 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2500
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 if (!PP.getPreprocessingRecord())
2502 PP.createPreprocessingRecord();
2503 if (!PP.getPreprocessingRecord()->getExternalSource())
2504 PP.getPreprocessingRecord()->SetExternalSource(*this);
2505 break;
2506
2507 case SOURCE_MANAGER_BLOCK_ID:
2508 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002509 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002511
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002513 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2514 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002516
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002518 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 if (Stream.SkipBlock() ||
2520 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2521 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002522 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 }
2524 CommentsCursors.push_back(std::make_pair(C, &F));
2525 break;
2526 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002527
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002529 if (Stream.SkipBlock()) {
2530 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002532 }
2533 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 }
2535 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002536
2537 case llvm::BitstreamEntry::Record:
2538 // The interesting case.
2539 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 }
2541
2542 // Read and process a record.
2543 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002544 StringRef Blob;
2545 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 default: // Default behavior: ignore.
2547 break;
2548
2549 case TYPE_OFFSET: {
2550 if (F.LocalNumTypes != 0) {
2551 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002552 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002554 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 F.LocalNumTypes = Record[0];
2556 unsigned LocalBaseTypeIndex = Record[1];
2557 F.BaseTypeIndex = getTotalNumTypes();
2558
2559 if (F.LocalNumTypes > 0) {
2560 // Introduce the global -> local mapping for types within this module.
2561 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2562
2563 // Introduce the local -> global mapping for types within this module.
2564 F.TypeRemap.insertOrReplace(
2565 std::make_pair(LocalBaseTypeIndex,
2566 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002567
2568 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 }
2570 break;
2571 }
2572
2573 case DECL_OFFSET: {
2574 if (F.LocalNumDecls != 0) {
2575 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002576 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002578 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 F.LocalNumDecls = Record[0];
2580 unsigned LocalBaseDeclID = Record[1];
2581 F.BaseDeclID = getTotalNumDecls();
2582
2583 if (F.LocalNumDecls > 0) {
2584 // Introduce the global -> local mapping for declarations within this
2585 // module.
2586 GlobalDeclMap.insert(
2587 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2588
2589 // Introduce the local -> global mapping for declarations within this
2590 // module.
2591 F.DeclRemap.insertOrReplace(
2592 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2593
2594 // Introduce the global -> local mapping for declarations within this
2595 // module.
2596 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002597
Ben Langmuir52ca6782014-10-20 16:27:32 +00002598 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2599 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 break;
2601 }
2602
2603 case TU_UPDATE_LEXICAL: {
2604 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002605 LexicalContents Contents(
2606 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2607 Blob.data()),
2608 static_cast<unsigned int>(Blob.size() / 4));
2609 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 TU->setHasExternalLexicalStorage(true);
2611 break;
2612 }
2613
2614 case UPDATE_VISIBLE: {
2615 unsigned Idx = 0;
2616 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002617 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002618 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002619 // If we've already loaded the decl, perform the updates when we finish
2620 // loading this block.
2621 if (Decl *D = GetExistingDecl(ID))
2622 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 break;
2624 }
2625
2626 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002627 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002629 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2630 (const unsigned char *)F.IdentifierTableData + Record[0],
2631 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2632 (const unsigned char *)F.IdentifierTableData,
2633 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002634
2635 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2636 }
2637 break;
2638
2639 case IDENTIFIER_OFFSET: {
2640 if (F.LocalNumIdentifiers != 0) {
2641 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002642 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002644 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 F.LocalNumIdentifiers = Record[0];
2646 unsigned LocalBaseIdentifierID = Record[1];
2647 F.BaseIdentifierID = getTotalNumIdentifiers();
2648
2649 if (F.LocalNumIdentifiers > 0) {
2650 // Introduce the global -> local mapping for identifiers within this
2651 // module.
2652 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2653 &F));
2654
2655 // Introduce the local -> global mapping for identifiers within this
2656 // module.
2657 F.IdentifierRemap.insertOrReplace(
2658 std::make_pair(LocalBaseIdentifierID,
2659 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002660
Ben Langmuir52ca6782014-10-20 16:27:32 +00002661 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2662 + F.LocalNumIdentifiers);
2663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 break;
2665 }
2666
Richard Smith33e0f7e2015-07-22 02:08:40 +00002667 case INTERESTING_IDENTIFIERS:
2668 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2669 break;
2670
Ben Langmuir332aafe2014-01-31 01:06:56 +00002671 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002672 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2673 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002675 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 break;
2677
2678 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002679 if (SpecialTypes.empty()) {
2680 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2681 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2682 break;
2683 }
2684
2685 if (SpecialTypes.size() != Record.size()) {
2686 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002687 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002688 }
2689
2690 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2691 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2692 if (!SpecialTypes[I])
2693 SpecialTypes[I] = ID;
2694 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2695 // merge step?
2696 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 break;
2698
2699 case STATISTICS:
2700 TotalNumStatements += Record[0];
2701 TotalNumMacros += Record[1];
2702 TotalLexicalDeclContexts += Record[2];
2703 TotalVisibleDeclContexts += Record[3];
2704 break;
2705
2706 case UNUSED_FILESCOPED_DECLS:
2707 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2708 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2709 break;
2710
2711 case DELEGATING_CTORS:
2712 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2713 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2714 break;
2715
2716 case WEAK_UNDECLARED_IDENTIFIERS:
2717 if (Record.size() % 4 != 0) {
2718 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002719 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 }
2721
2722 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2723 // files. This isn't the way to do it :)
2724 WeakUndeclaredIdentifiers.clear();
2725
2726 // Translate the weak, undeclared identifiers into global IDs.
2727 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2728 WeakUndeclaredIdentifiers.push_back(
2729 getGlobalIdentifierID(F, Record[I++]));
2730 WeakUndeclaredIdentifiers.push_back(
2731 getGlobalIdentifierID(F, Record[I++]));
2732 WeakUndeclaredIdentifiers.push_back(
2733 ReadSourceLocation(F, Record, I).getRawEncoding());
2734 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2735 }
2736 break;
2737
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002739 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 F.LocalNumSelectors = Record[0];
2741 unsigned LocalBaseSelectorID = Record[1];
2742 F.BaseSelectorID = getTotalNumSelectors();
2743
2744 if (F.LocalNumSelectors > 0) {
2745 // Introduce the global -> local mapping for selectors within this
2746 // module.
2747 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2748
2749 // Introduce the local -> global mapping for selectors within this
2750 // module.
2751 F.SelectorRemap.insertOrReplace(
2752 std::make_pair(LocalBaseSelectorID,
2753 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002754
2755 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
2757 break;
2758 }
2759
2760 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002761 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 if (Record[0])
2763 F.SelectorLookupTable
2764 = ASTSelectorLookupTable::Create(
2765 F.SelectorLookupTableData + Record[0],
2766 F.SelectorLookupTableData,
2767 ASTSelectorLookupTrait(*this, F));
2768 TotalNumMethodPoolEntries += Record[1];
2769 break;
2770
2771 case REFERENCED_SELECTOR_POOL:
2772 if (!Record.empty()) {
2773 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2774 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2775 Record[Idx++]));
2776 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2777 getRawEncoding());
2778 }
2779 }
2780 break;
2781
2782 case PP_COUNTER_VALUE:
2783 if (!Record.empty() && Listener)
2784 Listener->ReadCounter(F, Record[0]);
2785 break;
2786
2787 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002788 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 F.NumFileSortedDecls = Record[0];
2790 break;
2791
2792 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002793 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 F.LocalNumSLocEntries = Record[0];
2795 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002796 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002797 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002799 if (!F.SLocEntryBaseID) {
2800 Error("ran out of source locations");
2801 break;
2802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 // Make our entry in the range map. BaseID is negative and growing, so
2804 // we invert it. Because we invert it, though, we need the other end of
2805 // the range.
2806 unsigned RangeStart =
2807 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2808 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2809 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2810
2811 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2812 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2813 GlobalSLocOffsetMap.insert(
2814 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2815 - SLocSpaceSize,&F));
2816
2817 // Initialize the remapping table.
2818 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002819 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002821 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2823
2824 TotalNumSLocEntries += F.LocalNumSLocEntries;
2825 break;
2826 }
2827
2828 case MODULE_OFFSET_MAP: {
2829 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 const unsigned char *Data = (const unsigned char*)Blob.data();
2831 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002832
2833 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2834 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2835 F.SLocRemap.insert(std::make_pair(0U, 0));
2836 F.SLocRemap.insert(std::make_pair(2U, 1));
2837 }
2838
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002840 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2841 RemapBuilder;
2842 RemapBuilder SLocRemap(F.SLocRemap);
2843 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2844 RemapBuilder MacroRemap(F.MacroRemap);
2845 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2846 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2847 RemapBuilder SelectorRemap(F.SelectorRemap);
2848 RemapBuilder DeclRemap(F.DeclRemap);
2849 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002850
Richard Smithd8879c82015-08-24 21:59:32 +00002851 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002852 using namespace llvm::support;
2853 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 StringRef Name = StringRef((const char*)Data, Len);
2855 Data += Len;
2856 ModuleFile *OM = ModuleMgr.lookup(Name);
2857 if (!OM) {
2858 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 }
2861
Justin Bogner57ba0b22014-03-28 22:03:24 +00002862 uint32_t SLocOffset =
2863 endian::readNext<uint32_t, little, unaligned>(Data);
2864 uint32_t IdentifierIDOffset =
2865 endian::readNext<uint32_t, little, unaligned>(Data);
2866 uint32_t MacroIDOffset =
2867 endian::readNext<uint32_t, little, unaligned>(Data);
2868 uint32_t PreprocessedEntityIDOffset =
2869 endian::readNext<uint32_t, little, unaligned>(Data);
2870 uint32_t SubmoduleIDOffset =
2871 endian::readNext<uint32_t, little, unaligned>(Data);
2872 uint32_t SelectorIDOffset =
2873 endian::readNext<uint32_t, little, unaligned>(Data);
2874 uint32_t DeclIDOffset =
2875 endian::readNext<uint32_t, little, unaligned>(Data);
2876 uint32_t TypeIndexOffset =
2877 endian::readNext<uint32_t, little, unaligned>(Data);
2878
Ben Langmuir785180e2014-10-20 16:27:30 +00002879 uint32_t None = std::numeric_limits<uint32_t>::max();
2880
2881 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2882 RemapBuilder &Remap) {
2883 if (Offset != None)
2884 Remap.insert(std::make_pair(Offset,
2885 static_cast<int>(BaseOffset - Offset)));
2886 };
2887 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2888 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2889 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2890 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2891 PreprocessedEntityRemap);
2892 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2893 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2894 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2895 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002896
2897 // Global -> local mappings.
2898 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2899 }
2900 break;
2901 }
2902
2903 case SOURCE_MANAGER_LINE_TABLE:
2904 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002905 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 break;
2907
2908 case SOURCE_LOCATION_PRELOADS: {
2909 // Need to transform from the local view (1-based IDs) to the global view,
2910 // which is based off F.SLocEntryBaseID.
2911 if (!F.PreloadSLocEntries.empty()) {
2912 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002913 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 }
2915
2916 F.PreloadSLocEntries.swap(Record);
2917 break;
2918 }
2919
2920 case EXT_VECTOR_DECLS:
2921 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2922 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2923 break;
2924
2925 case VTABLE_USES:
2926 if (Record.size() % 3 != 0) {
2927 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 // Later tables overwrite earlier ones.
2932 // FIXME: Modules will have some trouble with this. This is clearly not
2933 // the right way to do this.
2934 VTableUses.clear();
2935
2936 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2937 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2938 VTableUses.push_back(
2939 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2940 VTableUses.push_back(Record[Idx++]);
2941 }
2942 break;
2943
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 case PENDING_IMPLICIT_INSTANTIATIONS:
2945 if (PendingInstantiations.size() % 2 != 0) {
2946 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002947 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 }
2949
2950 if (Record.size() % 2 != 0) {
2951 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002952 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 }
2954
2955 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2956 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2957 PendingInstantiations.push_back(
2958 ReadSourceLocation(F, Record, I).getRawEncoding());
2959 }
2960 break;
2961
2962 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002963 if (Record.size() != 2) {
2964 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002965 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002966 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2968 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2969 break;
2970
2971 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002972 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2973 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2974 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002975
2976 unsigned LocalBasePreprocessedEntityID = Record[0];
2977
2978 unsigned StartingID;
2979 if (!PP.getPreprocessingRecord())
2980 PP.createPreprocessingRecord();
2981 if (!PP.getPreprocessingRecord()->getExternalSource())
2982 PP.getPreprocessingRecord()->SetExternalSource(*this);
2983 StartingID
2984 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002985 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 F.BasePreprocessedEntityID = StartingID;
2987
2988 if (F.NumPreprocessedEntities > 0) {
2989 // Introduce the global -> local mapping for preprocessed entities in
2990 // this module.
2991 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2992
2993 // Introduce the local -> global mapping for preprocessed entities in
2994 // this module.
2995 F.PreprocessedEntityRemap.insertOrReplace(
2996 std::make_pair(LocalBasePreprocessedEntityID,
2997 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2998 }
2999
3000 break;
3001 }
3002
3003 case DECL_UPDATE_OFFSETS: {
3004 if (Record.size() % 2 != 0) {
3005 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003006 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003008 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3009 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3010 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3011
3012 // If we've already loaded the decl, perform the updates when we finish
3013 // loading this block.
3014 if (Decl *D = GetExistingDecl(ID))
3015 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 break;
3018 }
3019
3020 case DECL_REPLACEMENTS: {
3021 if (Record.size() % 3 != 0) {
3022 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003023 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 }
3025 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3026 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3027 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3028 break;
3029 }
3030
3031 case OBJC_CATEGORIES_MAP: {
3032 if (F.LocalNumObjCCategoriesInMap != 0) {
3033 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003034 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 }
3036
3037 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003038 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 break;
3040 }
3041
3042 case OBJC_CATEGORIES:
3043 F.ObjCCategories.swap(Record);
3044 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003045
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 case CXX_BASE_SPECIFIER_OFFSETS: {
3047 if (F.LocalNumCXXBaseSpecifiers != 0) {
3048 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003049 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003051
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003053 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003054 break;
3055 }
3056
3057 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3058 if (F.LocalNumCXXCtorInitializers != 0) {
3059 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3060 return Failure;
3061 }
3062
3063 F.LocalNumCXXCtorInitializers = Record[0];
3064 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 break;
3066 }
3067
3068 case DIAG_PRAGMA_MAPPINGS:
3069 if (F.PragmaDiagMappings.empty())
3070 F.PragmaDiagMappings.swap(Record);
3071 else
3072 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3073 Record.begin(), Record.end());
3074 break;
3075
3076 case CUDA_SPECIAL_DECL_REFS:
3077 // Later tables overwrite earlier ones.
3078 // FIXME: Modules will have trouble with this.
3079 CUDASpecialDeclRefs.clear();
3080 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3081 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3082 break;
3083
3084 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003085 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 if (Record[0]) {
3088 F.HeaderFileInfoTable
3089 = HeaderFileInfoLookupTable::Create(
3090 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3091 (const unsigned char *)F.HeaderFileInfoTableData,
3092 HeaderFileInfoTrait(*this, F,
3093 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003094 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003095
3096 PP.getHeaderSearchInfo().SetExternalSource(this);
3097 if (!PP.getHeaderSearchInfo().getExternalLookup())
3098 PP.getHeaderSearchInfo().SetExternalLookup(this);
3099 }
3100 break;
3101 }
3102
3103 case FP_PRAGMA_OPTIONS:
3104 // Later tables overwrite earlier ones.
3105 FPPragmaOptions.swap(Record);
3106 break;
3107
3108 case OPENCL_EXTENSIONS:
3109 // Later tables overwrite earlier ones.
3110 OpenCLExtensions.swap(Record);
3111 break;
3112
3113 case TENTATIVE_DEFINITIONS:
3114 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3115 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3116 break;
3117
3118 case KNOWN_NAMESPACES:
3119 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3120 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3121 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003122
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003123 case UNDEFINED_BUT_USED:
3124 if (UndefinedButUsed.size() % 2 != 0) {
3125 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003126 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003127 }
3128
3129 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003130 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003131 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003132 }
3133 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003134 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3135 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003136 ReadSourceLocation(F, Record, I).getRawEncoding());
3137 }
3138 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003139 case DELETE_EXPRS_TO_ANALYZE:
3140 for (unsigned I = 0, N = Record.size(); I != N;) {
3141 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3142 const uint64_t Count = Record[I++];
3143 DelayedDeleteExprs.push_back(Count);
3144 for (uint64_t C = 0; C < Count; ++C) {
3145 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3146 bool IsArrayForm = Record[I++] == 1;
3147 DelayedDeleteExprs.push_back(IsArrayForm);
3148 }
3149 }
3150 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003151
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003153 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 // If we aren't loading a module (which has its own exports), make
3155 // all of the imported modules visible.
3156 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003157 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3158 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3159 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3160 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003161 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 }
3163 }
3164 break;
3165 }
3166
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 case MACRO_OFFSET: {
3168 if (F.LocalNumMacros != 0) {
3169 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003170 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003172 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 F.LocalNumMacros = Record[0];
3174 unsigned LocalBaseMacroID = Record[1];
3175 F.BaseMacroID = getTotalNumMacros();
3176
3177 if (F.LocalNumMacros > 0) {
3178 // Introduce the global -> local mapping for macros within this module.
3179 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3180
3181 // Introduce the local -> global mapping for macros within this module.
3182 F.MacroRemap.insertOrReplace(
3183 std::make_pair(LocalBaseMacroID,
3184 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003185
3186 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 }
3188 break;
3189 }
3190
Richard Smithe40f2ba2013-08-07 21:41:30 +00003191 case LATE_PARSED_TEMPLATE: {
3192 LateParsedTemplates.append(Record.begin(), Record.end());
3193 break;
3194 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003195
3196 case OPTIMIZE_PRAGMA_OPTIONS:
3197 if (Record.size() != 1) {
3198 Error("invalid pragma optimize record");
3199 return Failure;
3200 }
3201 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3202 break;
Nico Weber72889432014-09-06 01:25:55 +00003203
3204 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3205 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3206 UnusedLocalTypedefNameCandidates.push_back(
3207 getGlobalDeclID(F, Record[I]));
3208 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 }
3210 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003211}
3212
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003213ASTReader::ASTReadResult
3214ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3215 const ModuleFile *ImportedBy,
3216 unsigned ClientLoadCapabilities) {
3217 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003218 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003219
Richard Smithe842a472014-10-22 02:05:46 +00003220 if (F.Kind == MK_ExplicitModule) {
3221 // For an explicitly-loaded module, we don't care whether the original
3222 // module map file exists or matches.
3223 return Success;
3224 }
3225
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003226 // Try to resolve ModuleName in the current header search context and
3227 // verify that it is found in the same module map file as we saved. If the
3228 // top-level AST file is a main file, skip this check because there is no
3229 // usable header search context.
3230 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003231 "MODULE_NAME should come before MODULE_MAP_FILE");
3232 if (F.Kind == MK_ImplicitModule &&
3233 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3234 // An implicitly-loaded module file should have its module listed in some
3235 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003236 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003237 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3238 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3239 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003240 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003241 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3242 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3243 // This module was defined by an imported (explicit) module.
3244 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3245 << ASTFE->getName();
3246 else
3247 // This module was built with a different module map.
3248 Diag(diag::err_imported_module_not_found)
3249 << F.ModuleName << F.FileName << ImportedBy->FileName
3250 << F.ModuleMapPath;
3251 }
3252 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003253 }
3254
Richard Smithe842a472014-10-22 02:05:46 +00003255 assert(M->Name == F.ModuleName && "found module with different name");
3256
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003257 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003258 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003259 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3260 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003261 assert(ImportedBy && "top-level import should be verified");
3262 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3263 Diag(diag::err_imported_module_modmap_changed)
3264 << F.ModuleName << ImportedBy->FileName
3265 << ModMap->getName() << F.ModuleMapPath;
3266 return OutOfDate;
3267 }
3268
3269 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3270 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3271 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003272 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003273 const FileEntry *F =
3274 FileMgr.getFile(Filename, false, false);
3275 if (F == nullptr) {
3276 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3277 Error("could not find file '" + Filename +"' referenced by AST file");
3278 return OutOfDate;
3279 }
3280 AdditionalStoredMaps.insert(F);
3281 }
3282
3283 // Check any additional module map files (e.g. module.private.modulemap)
3284 // that are not in the pcm.
3285 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3286 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3287 // Remove files that match
3288 // Note: SmallPtrSet::erase is really remove
3289 if (!AdditionalStoredMaps.erase(ModMap)) {
3290 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3291 Diag(diag::err_module_different_modmap)
3292 << F.ModuleName << /*new*/0 << ModMap->getName();
3293 return OutOfDate;
3294 }
3295 }
3296 }
3297
3298 // Check any additional module map files that are in the pcm, but not
3299 // found in header search. Cases that match are already removed.
3300 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3301 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3302 Diag(diag::err_module_different_modmap)
3303 << F.ModuleName << /*not new*/1 << ModMap->getName();
3304 return OutOfDate;
3305 }
3306 }
3307
3308 if (Listener)
3309 Listener->ReadModuleMapFile(F.ModuleMapPath);
3310 return Success;
3311}
3312
3313
Douglas Gregorc1489562013-02-12 23:36:21 +00003314/// \brief Move the given method to the back of the global list of methods.
3315static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3316 // Find the entry for this selector in the method pool.
3317 Sema::GlobalMethodPool::iterator Known
3318 = S.MethodPool.find(Method->getSelector());
3319 if (Known == S.MethodPool.end())
3320 return;
3321
3322 // Retrieve the appropriate method list.
3323 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3324 : Known->second.second;
3325 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003326 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003327 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003328 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003329 Found = true;
3330 } else {
3331 // Keep searching.
3332 continue;
3333 }
3334 }
3335
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003336 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003337 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003338 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003339 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003340 }
3341}
3342
Richard Smithde711422015-04-23 21:20:19 +00003343void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003344 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003345 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003346 bool wasHidden = D->Hidden;
3347 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348
Richard Smith49f906a2014-03-01 00:08:04 +00003349 if (wasHidden && SemaObj) {
3350 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3351 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 }
3354 }
3355}
3356
Richard Smith49f906a2014-03-01 00:08:04 +00003357void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003358 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003359 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003361 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003362 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003364 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003365
3366 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003367 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 // there is nothing more to do.
3369 continue;
3370 }
Richard Smith49f906a2014-03-01 00:08:04 +00003371
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 if (!Mod->isAvailable()) {
3373 // Modules that aren't available cannot be made visible.
3374 continue;
3375 }
3376
3377 // Update the module's name visibility.
3378 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003379
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 // If we've already deserialized any names from this module,
3381 // mark them as visible.
3382 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3383 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003384 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003385 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003386 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003387 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3388 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003389 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003390
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003392 SmallVector<Module *, 16> Exports;
3393 Mod->getExportedModules(Exports);
3394 for (SmallVectorImpl<Module *>::iterator
3395 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3396 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003397 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003398 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 }
3400 }
3401}
3402
Douglas Gregore060e572013-01-25 01:03:03 +00003403bool ASTReader::loadGlobalIndex() {
3404 if (GlobalIndex)
3405 return false;
3406
3407 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3408 !Context.getLangOpts().Modules)
3409 return true;
3410
3411 // Try to load the global index.
3412 TriedLoadingGlobalIndex = true;
3413 StringRef ModuleCachePath
3414 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3415 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003416 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003417 if (!Result.first)
3418 return true;
3419
3420 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003421 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003422 return false;
3423}
3424
3425bool ASTReader::isGlobalIndexUnavailable() const {
3426 return Context.getLangOpts().Modules && UseGlobalIndex &&
3427 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3428}
3429
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003430static void updateModuleTimestamp(ModuleFile &MF) {
3431 // Overwrite the timestamp file contents so that file's mtime changes.
3432 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003433 std::error_code EC;
3434 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3435 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003436 return;
3437 OS << "Timestamp file\n";
3438}
3439
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003440/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3441/// cursor into the start of the given block ID, returning false on success and
3442/// true on failure.
3443static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3444 while (1) {
3445 llvm::BitstreamEntry Entry = Cursor.advance();
3446 switch (Entry.Kind) {
3447 case llvm::BitstreamEntry::Error:
3448 case llvm::BitstreamEntry::EndBlock:
3449 return true;
3450
3451 case llvm::BitstreamEntry::Record:
3452 // Ignore top-level records.
3453 Cursor.skipRecord(Entry.ID);
3454 break;
3455
3456 case llvm::BitstreamEntry::SubBlock:
3457 if (Entry.ID == BlockID) {
3458 if (Cursor.EnterSubBlock(BlockID))
3459 return true;
3460 // Found it!
3461 return false;
3462 }
3463
3464 if (Cursor.SkipBlock())
3465 return true;
3466 }
3467 }
3468}
3469
Guy Benyei11169dd2012-12-18 14:30:41 +00003470ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3471 ModuleKind Type,
3472 SourceLocation ImportLoc,
3473 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003474 llvm::SaveAndRestore<SourceLocation>
3475 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3476
Richard Smithd1c46742014-04-30 02:24:17 +00003477 // Defer any pending actions until we get to the end of reading the AST file.
3478 Deserializing AnASTFile(this);
3479
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003481 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003482
3483 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003484 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003486 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003487 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 ClientLoadCapabilities)) {
3489 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003490 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 case OutOfDate:
3492 case VersionMismatch:
3493 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003494 case HadErrors: {
3495 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3496 for (const ImportedModule &IM : Loaded)
3497 LoadedSet.insert(IM.Mod);
3498
Douglas Gregor7029ce12013-03-19 00:28:20 +00003499 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003500 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003501 Context.getLangOpts().Modules
3502 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003503 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003504
3505 // If we find that any modules are unusable, the global index is going
3506 // to be out-of-date. Just remove it.
3507 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003508 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003510 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 case Success:
3512 break;
3513 }
3514
3515 // Here comes stuff that we only do once the entire chain is loaded.
3516
3517 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003518 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3519 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 M != MEnd; ++M) {
3521 ModuleFile &F = *M->Mod;
3522
3523 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003524 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3525 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003526
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003527 // Read the extension blocks.
3528 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3529 if (ASTReadResult Result = ReadExtensionBlock(F))
3530 return Result;
3531 }
3532
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 // Once read, set the ModuleFile bit base offset and update the size in
3534 // bits of all files we've seen.
3535 F.GlobalBitOffset = TotalModulesSizeInBits;
3536 TotalModulesSizeInBits += F.SizeInBits;
3537 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3538
3539 // Preload SLocEntries.
3540 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3541 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3542 // Load it through the SourceManager and don't call ReadSLocEntry()
3543 // directly because the entry may have already been loaded in which case
3544 // calling ReadSLocEntry() directly would trigger an assertion in
3545 // SourceManager.
3546 SourceMgr.getLoadedSLocEntryByID(Index);
3547 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003548
3549 // Preload all the pending interesting identifiers by marking them out of
3550 // date.
3551 for (auto Offset : F.PreloadIdentifierOffsets) {
3552 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3553 F.IdentifierTableData + Offset);
3554
3555 ASTIdentifierLookupTrait Trait(*this, F);
3556 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3557 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003558 auto &II = PP.getIdentifierTable().getOwn(Key);
3559 II.setOutOfDate(true);
3560
3561 // Mark this identifier as being from an AST file so that we can track
3562 // whether we need to serialize it.
3563 if (!II.isFromAST()) {
3564 II.setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +00003565 bool IsModule = PP.getCurrentModule() != nullptr;
3566 if (isInterestingIdentifier(*this, II, IsModule))
Richard Smith79bf9202015-08-24 03:33:22 +00003567 II.setChangedSinceDeserialization();
3568 }
3569
3570 // Associate the ID with the identifier so that the writer can reuse it.
3571 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3572 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003573 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 }
3575
Douglas Gregor603cd862013-03-22 18:50:14 +00003576 // Setup the import locations and notify the module manager that we've
3577 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003578 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3579 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 M != MEnd; ++M) {
3581 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003582
3583 ModuleMgr.moduleFileAccepted(&F);
3584
3585 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003586 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 if (!M->ImportedBy)
3588 F.ImportLoc = M->ImportLoc;
3589 else
3590 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3591 M->ImportLoc.getRawEncoding());
3592 }
3593
Richard Smith33e0f7e2015-07-22 02:08:40 +00003594 if (!Context.getLangOpts().CPlusPlus ||
3595 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3596 // Mark all of the identifiers in the identifier table as being out of date,
3597 // so that various accessors know to check the loaded modules when the
3598 // identifier is used.
3599 //
3600 // For C++ modules, we don't need information on many identifiers (just
3601 // those that provide macros or are poisoned), so we mark all of
3602 // the interesting ones via PreloadIdentifierOffsets.
3603 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3604 IdEnd = PP.getIdentifierTable().end();
3605 Id != IdEnd; ++Id)
3606 Id->second->setOutOfDate(true);
3607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003608
3609 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003610 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3611 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3613 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003614
3615 switch (Unresolved.Kind) {
3616 case UnresolvedModuleRef::Conflict:
3617 if (ResolvedMod) {
3618 Module::Conflict Conflict;
3619 Conflict.Other = ResolvedMod;
3620 Conflict.Message = Unresolved.String.str();
3621 Unresolved.Mod->Conflicts.push_back(Conflict);
3622 }
3623 continue;
3624
3625 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003627 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003629
Douglas Gregorfb912652013-03-20 21:10:35 +00003630 case UnresolvedModuleRef::Export:
3631 if (ResolvedMod || Unresolved.IsWildcard)
3632 Unresolved.Mod->Exports.push_back(
3633 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3634 continue;
3635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003637 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003638
3639 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3640 // Might be unnecessary as use declarations are only used to build the
3641 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003642
3643 InitializeContext();
3644
Richard Smith3d8e97e2013-10-18 06:54:39 +00003645 if (SemaObj)
3646 UpdateSema();
3647
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 if (DeserializationListener)
3649 DeserializationListener->ReaderInitialized(this);
3650
3651 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003652 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003653 PrimaryModule.OriginalSourceFileID
3654 = FileID::get(PrimaryModule.SLocEntryBaseID
3655 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3656
3657 // If this AST file is a precompiled preamble, then set the
3658 // preamble file ID of the source manager to the file source file
3659 // from which the preamble was built.
3660 if (Type == MK_Preamble) {
3661 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3662 } else if (Type == MK_MainFile) {
3663 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3664 }
3665 }
3666
3667 // For any Objective-C class definitions we have already loaded, make sure
3668 // that we load any additional categories.
3669 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3670 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3671 ObjCClassesLoaded[I],
3672 PreviousGeneration);
3673 }
Douglas Gregore060e572013-01-25 01:03:03 +00003674
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003675 if (PP.getHeaderSearchInfo()
3676 .getHeaderSearchOpts()
3677 .ModulesValidateOncePerBuildSession) {
3678 // Now we are certain that the module and all modules it depends on are
3679 // up to date. Create or update timestamp files for modules that are
3680 // located in the module cache (not for PCH files that could be anywhere
3681 // in the filesystem).
3682 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3683 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003684 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003685 updateModuleTimestamp(*M.Mod);
3686 }
3687 }
3688 }
3689
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 return Success;
3691}
3692
Ben Langmuir487ea142014-10-23 18:05:36 +00003693static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3694
Ben Langmuir70a1b812015-03-24 04:43:52 +00003695/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3696static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3697 return Stream.Read(8) == 'C' &&
3698 Stream.Read(8) == 'P' &&
3699 Stream.Read(8) == 'C' &&
3700 Stream.Read(8) == 'H';
3701}
3702
Richard Smith0f99d6a2015-08-09 08:48:41 +00003703static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3704 switch (Kind) {
3705 case MK_PCH:
3706 return 0; // PCH
3707 case MK_ImplicitModule:
3708 case MK_ExplicitModule:
3709 return 1; // module
3710 case MK_MainFile:
3711 case MK_Preamble:
3712 return 2; // main source file
3713 }
3714 llvm_unreachable("unknown module kind");
3715}
3716
Guy Benyei11169dd2012-12-18 14:30:41 +00003717ASTReader::ASTReadResult
3718ASTReader::ReadASTCore(StringRef FileName,
3719 ModuleKind Type,
3720 SourceLocation ImportLoc,
3721 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003722 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003723 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003724 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 unsigned ClientLoadCapabilities) {
3726 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003728 ModuleManager::AddModuleResult AddResult
3729 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003730 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003731 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003732 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003733
Douglas Gregor7029ce12013-03-19 00:28:20 +00003734 switch (AddResult) {
3735 case ModuleManager::AlreadyLoaded:
3736 return Success;
3737
3738 case ModuleManager::NewlyLoaded:
3739 // Load module file below.
3740 break;
3741
3742 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003743 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003744 // it.
3745 if (ClientLoadCapabilities & ARR_Missing)
3746 return Missing;
3747
3748 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003749 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3750 << FileName << ErrorStr.empty()
3751 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003752 return Failure;
3753
3754 case ModuleManager::OutOfDate:
3755 // We couldn't load the module file because it is out-of-date. If the
3756 // client can handle out-of-date, return it.
3757 if (ClientLoadCapabilities & ARR_OutOfDate)
3758 return OutOfDate;
3759
3760 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003761 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3762 << FileName << ErrorStr.empty()
3763 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 return Failure;
3765 }
3766
Douglas Gregor7029ce12013-03-19 00:28:20 +00003767 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003768
3769 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3770 // module?
3771 if (FileName != "-") {
3772 CurrentDir = llvm::sys::path::parent_path(FileName);
3773 if (CurrentDir.empty()) CurrentDir = ".";
3774 }
3775
3776 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003777 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003778 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003779 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003780 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3781
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003783 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003784 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3785 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 return Failure;
3787 }
3788
3789 // This is used for compatibility with older PCH formats.
3790 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003791 while (1) {
3792 llvm::BitstreamEntry Entry = Stream.advance();
3793
3794 switch (Entry.Kind) {
3795 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003796 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003797 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 Error("invalid record at top-level of AST file");
3799 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003800
3801 case llvm::BitstreamEntry::SubBlock:
3802 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 }
3804
Chris Lattnerefa77172013-01-20 00:00:22 +00003805 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 case CONTROL_BLOCK_ID:
3807 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003808 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003810 // Check that we didn't try to load a non-module AST file as a module.
3811 //
3812 // FIXME: Should we also perform the converse check? Loading a module as
3813 // a PCH file sort of works, but it's a bit wonky.
3814 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3815 F.ModuleName.empty()) {
3816 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3817 if (Result != OutOfDate ||
3818 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3819 Diag(diag::err_module_file_not_module) << FileName;
3820 return Result;
3821 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003822 break;
3823
3824 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003825 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 case OutOfDate: return OutOfDate;
3827 case VersionMismatch: return VersionMismatch;
3828 case ConfigurationMismatch: return ConfigurationMismatch;
3829 case HadErrors: return HadErrors;
3830 }
3831 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003832
Guy Benyei11169dd2012-12-18 14:30:41 +00003833 case AST_BLOCK_ID:
3834 if (!HaveReadControlBlock) {
3835 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003836 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 return VersionMismatch;
3838 }
3839
3840 // Record that we've loaded this module.
3841 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3842 return Success;
3843
3844 default:
3845 if (Stream.SkipBlock()) {
3846 Error("malformed block record in AST file");
3847 return Failure;
3848 }
3849 break;
3850 }
3851 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003852
3853 return Success;
3854}
3855
3856/// Parse a record and blob containing module file extension metadata.
3857static bool parseModuleFileExtensionMetadata(
3858 const SmallVectorImpl<uint64_t> &Record,
3859 StringRef Blob,
3860 ModuleFileExtensionMetadata &Metadata) {
3861 if (Record.size() < 4) return true;
3862
3863 Metadata.MajorVersion = Record[0];
3864 Metadata.MinorVersion = Record[1];
3865
3866 unsigned BlockNameLen = Record[2];
3867 unsigned UserInfoLen = Record[3];
3868
3869 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3870
3871 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3872 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3873 Blob.data() + BlockNameLen + UserInfoLen);
3874 return false;
3875}
3876
3877ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3878 BitstreamCursor &Stream = F.Stream;
3879
3880 RecordData Record;
3881 while (true) {
3882 llvm::BitstreamEntry Entry = Stream.advance();
3883 switch (Entry.Kind) {
3884 case llvm::BitstreamEntry::SubBlock:
3885 if (Stream.SkipBlock())
3886 return Failure;
3887
3888 continue;
3889
3890 case llvm::BitstreamEntry::EndBlock:
3891 return Success;
3892
3893 case llvm::BitstreamEntry::Error:
3894 return HadErrors;
3895
3896 case llvm::BitstreamEntry::Record:
3897 break;
3898 }
3899
3900 Record.clear();
3901 StringRef Blob;
3902 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3903 switch (RecCode) {
3904 case EXTENSION_METADATA: {
3905 ModuleFileExtensionMetadata Metadata;
3906 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3907 return Failure;
3908
3909 // Find a module file extension with this block name.
3910 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3911 if (Known == ModuleFileExtensions.end()) break;
3912
3913 // Form a reader.
3914 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3915 F, Stream)) {
3916 F.ExtensionReaders.push_back(std::move(Reader));
3917 }
3918
3919 break;
3920 }
3921 }
3922 }
3923
3924 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003925}
3926
Richard Smitha7e2cc62015-05-01 01:53:09 +00003927void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 // If there's a listener, notify them that we "read" the translation unit.
3929 if (DeserializationListener)
3930 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3931 Context.getTranslationUnitDecl());
3932
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 // FIXME: Find a better way to deal with collisions between these
3934 // built-in types. Right now, we just ignore the problem.
3935
3936 // Load the special types.
3937 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3938 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3939 if (!Context.CFConstantStringTypeDecl)
3940 Context.setCFConstantStringType(GetType(String));
3941 }
3942
3943 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3944 QualType FileType = GetType(File);
3945 if (FileType.isNull()) {
3946 Error("FILE type is NULL");
3947 return;
3948 }
3949
3950 if (!Context.FILEDecl) {
3951 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3952 Context.setFILEDecl(Typedef->getDecl());
3953 else {
3954 const TagType *Tag = FileType->getAs<TagType>();
3955 if (!Tag) {
3956 Error("Invalid FILE type in AST file");
3957 return;
3958 }
3959 Context.setFILEDecl(Tag->getDecl());
3960 }
3961 }
3962 }
3963
3964 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3965 QualType Jmp_bufType = GetType(Jmp_buf);
3966 if (Jmp_bufType.isNull()) {
3967 Error("jmp_buf type is NULL");
3968 return;
3969 }
3970
3971 if (!Context.jmp_bufDecl) {
3972 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3973 Context.setjmp_bufDecl(Typedef->getDecl());
3974 else {
3975 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3976 if (!Tag) {
3977 Error("Invalid jmp_buf type in AST file");
3978 return;
3979 }
3980 Context.setjmp_bufDecl(Tag->getDecl());
3981 }
3982 }
3983 }
3984
3985 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3986 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3987 if (Sigjmp_bufType.isNull()) {
3988 Error("sigjmp_buf type is NULL");
3989 return;
3990 }
3991
3992 if (!Context.sigjmp_bufDecl) {
3993 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3994 Context.setsigjmp_bufDecl(Typedef->getDecl());
3995 else {
3996 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3997 assert(Tag && "Invalid sigjmp_buf type in AST file");
3998 Context.setsigjmp_bufDecl(Tag->getDecl());
3999 }
4000 }
4001 }
4002
4003 if (unsigned ObjCIdRedef
4004 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4005 if (Context.ObjCIdRedefinitionType.isNull())
4006 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4007 }
4008
4009 if (unsigned ObjCClassRedef
4010 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4011 if (Context.ObjCClassRedefinitionType.isNull())
4012 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4013 }
4014
4015 if (unsigned ObjCSelRedef
4016 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4017 if (Context.ObjCSelRedefinitionType.isNull())
4018 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4019 }
4020
4021 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4022 QualType Ucontext_tType = GetType(Ucontext_t);
4023 if (Ucontext_tType.isNull()) {
4024 Error("ucontext_t type is NULL");
4025 return;
4026 }
4027
4028 if (!Context.ucontext_tDecl) {
4029 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4030 Context.setucontext_tDecl(Typedef->getDecl());
4031 else {
4032 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4033 assert(Tag && "Invalid ucontext_t type in AST file");
4034 Context.setucontext_tDecl(Tag->getDecl());
4035 }
4036 }
4037 }
4038 }
4039
4040 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4041
4042 // If there were any CUDA special declarations, deserialize them.
4043 if (!CUDASpecialDeclRefs.empty()) {
4044 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4045 Context.setcudaConfigureCallDecl(
4046 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4047 }
Richard Smith56be7542014-03-21 00:33:59 +00004048
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004050 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004051 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004052 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004053 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004054 /*ImportLoc=*/Import.ImportLoc);
4055 PP.makeModuleVisible(Imported, Import.ImportLoc);
4056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 }
4058 ImportedModules.clear();
4059}
4060
4061void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004062 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004063}
4064
Ben Langmuir70a1b812015-03-24 04:43:52 +00004065/// \brief Reads and return the signature record from \p StreamFile's control
4066/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004067static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4068 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004069 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004070 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004071
4072 // Scan for the CONTROL_BLOCK_ID block.
4073 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4074 return 0;
4075
4076 // Scan for SIGNATURE inside the control block.
4077 ASTReader::RecordData Record;
4078 while (1) {
4079 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4080 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4081 Entry.Kind != llvm::BitstreamEntry::Record)
4082 return 0;
4083
4084 Record.clear();
4085 StringRef Blob;
4086 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4087 return Record[0];
4088 }
4089}
4090
Guy Benyei11169dd2012-12-18 14:30:41 +00004091/// \brief Retrieve the name of the original source file name
4092/// directly from the AST file, without actually loading the AST
4093/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004094std::string ASTReader::getOriginalSourceFile(
4095 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004096 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004098 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004100 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4101 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 return std::string();
4103 }
4104
4105 // Initialize the stream
4106 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004107 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004108 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004109
4110 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004111 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4113 return std::string();
4114 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004115
Chris Lattnere7b154b2013-01-19 21:39:22 +00004116 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004117 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4119 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004121
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004122 // Scan for ORIGINAL_FILE inside the control block.
4123 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004124 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004125 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004126 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4127 return std::string();
4128
4129 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4130 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4131 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004133
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004135 StringRef Blob;
4136 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4137 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004138 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004139}
4140
4141namespace {
4142 class SimplePCHValidator : public ASTReaderListener {
4143 const LangOptions &ExistingLangOpts;
4144 const TargetOptions &ExistingTargetOpts;
4145 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004146 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004148
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 public:
4150 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4151 const TargetOptions &ExistingTargetOpts,
4152 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004153 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 FileManager &FileMgr)
4155 : ExistingLangOpts(ExistingLangOpts),
4156 ExistingTargetOpts(ExistingTargetOpts),
4157 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004158 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 FileMgr(FileMgr)
4160 {
4161 }
4162
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004163 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4164 bool AllowCompatibleDifferences) override {
4165 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4166 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004168 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4169 bool AllowCompatibleDifferences) override {
4170 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4171 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004173 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4174 StringRef SpecificModuleCachePath,
4175 bool Complain) override {
4176 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4177 ExistingModuleCachePath,
4178 nullptr, ExistingLangOpts);
4179 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004180 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4181 bool Complain,
4182 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004183 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004184 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 }
4186 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004187}
Guy Benyei11169dd2012-12-18 14:30:41 +00004188
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004189bool ASTReader::readASTFileControlBlock(
4190 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004191 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004192 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004193 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004195 // FIXME: This allows use of the VFS; we do not allow use of the
4196 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004197 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 if (!Buffer) {
4199 return true;
4200 }
4201
4202 // Initialize the stream
4203 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004204 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004205 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004206
4207 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004208 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004210
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004211 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004212 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004214
4215 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004216 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004217 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004218 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004219
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004221 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004222 bool DoneWithControlBlock = false;
4223 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004224 llvm::BitstreamEntry Entry = Stream.advance();
4225
4226 switch (Entry.Kind) {
4227 case llvm::BitstreamEntry::SubBlock: {
4228 switch (Entry.ID) {
4229 case OPTIONS_BLOCK_ID: {
4230 std::string IgnoredSuggestedPredefines;
4231 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4232 /*AllowCompatibleConfigurationMismatch*/ false,
4233 Listener, IgnoredSuggestedPredefines) != Success)
4234 return true;
4235 break;
4236 }
4237
4238 case INPUT_FILES_BLOCK_ID:
4239 InputFilesCursor = Stream;
4240 if (Stream.SkipBlock() ||
4241 (NeedsInputFiles &&
4242 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4243 return true;
4244 break;
4245
4246 default:
4247 if (Stream.SkipBlock())
4248 return true;
4249 break;
4250 }
4251
4252 continue;
4253 }
4254
4255 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004256 DoneWithControlBlock = true;
4257 break;
Richard Smith0516b182015-09-08 19:40:14 +00004258
4259 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004260 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004261
4262 case llvm::BitstreamEntry::Record:
4263 break;
4264 }
4265
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004266 if (DoneWithControlBlock) break;
4267
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004269 StringRef Blob;
4270 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004271 switch ((ControlRecordTypes)RecCode) {
4272 case METADATA: {
4273 if (Record[0] != VERSION_MAJOR)
4274 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004276 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004277 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004278
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004279 break;
4280 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004281 case MODULE_NAME:
4282 Listener.ReadModuleName(Blob);
4283 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004284 case MODULE_DIRECTORY:
4285 ModuleDir = Blob;
4286 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004287 case MODULE_MAP_FILE: {
4288 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004289 auto Path = ReadString(Record, Idx);
4290 ResolveImportedPath(Path, ModuleDir);
4291 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004292 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004293 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004294 case INPUT_FILE_OFFSETS: {
4295 if (!NeedsInputFiles)
4296 break;
4297
4298 unsigned NumInputFiles = Record[0];
4299 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004300 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004301 for (unsigned I = 0; I != NumInputFiles; ++I) {
4302 // Go find this input file.
4303 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004304
4305 if (isSystemFile && !NeedsSystemInputFiles)
4306 break; // the rest are system input files
4307
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004308 BitstreamCursor &Cursor = InputFilesCursor;
4309 SavedStreamPosition SavedPosition(Cursor);
4310 Cursor.JumpToBit(InputFileOffs[I]);
4311
4312 unsigned Code = Cursor.ReadCode();
4313 RecordData Record;
4314 StringRef Blob;
4315 bool shouldContinue = false;
4316 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4317 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004318 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004319 std::string Filename = Blob;
4320 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004321 shouldContinue = Listener.visitInputFile(
4322 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004323 break;
4324 }
4325 if (!shouldContinue)
4326 break;
4327 }
4328 break;
4329 }
4330
Richard Smithd4b230b2014-10-27 23:01:16 +00004331 case IMPORTS: {
4332 if (!NeedsImports)
4333 break;
4334
4335 unsigned Idx = 0, N = Record.size();
4336 while (Idx < N) {
4337 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004338 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004339 std::string Filename = ReadString(Record, Idx);
4340 ResolveImportedPath(Filename, ModuleDir);
4341 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004342 }
4343 break;
4344 }
4345
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004346 default:
4347 // No other validation to perform.
4348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 }
4350 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004351
4352 // Look for module file extension blocks, if requested.
4353 if (FindModuleFileExtensions) {
4354 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4355 bool DoneWithExtensionBlock = false;
4356 while (!DoneWithExtensionBlock) {
4357 llvm::BitstreamEntry Entry = Stream.advance();
4358
4359 switch (Entry.Kind) {
4360 case llvm::BitstreamEntry::SubBlock:
4361 if (Stream.SkipBlock())
4362 return true;
4363
4364 continue;
4365
4366 case llvm::BitstreamEntry::EndBlock:
4367 DoneWithExtensionBlock = true;
4368 continue;
4369
4370 case llvm::BitstreamEntry::Error:
4371 return true;
4372
4373 case llvm::BitstreamEntry::Record:
4374 break;
4375 }
4376
4377 Record.clear();
4378 StringRef Blob;
4379 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4380 switch (RecCode) {
4381 case EXTENSION_METADATA: {
4382 ModuleFileExtensionMetadata Metadata;
4383 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4384 return true;
4385
4386 Listener.readModuleFileExtension(Metadata);
4387 break;
4388 }
4389 }
4390 }
4391 }
4392 }
4393
4394 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004395}
4396
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004397bool ASTReader::isAcceptableASTFile(
4398 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004399 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004400 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4401 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004402 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4403 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004404 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004405 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004406 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004407}
4408
Ben Langmuir2c9af442014-04-10 17:57:43 +00004409ASTReader::ASTReadResult
4410ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 // Enter the submodule block.
4412 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4413 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004414 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 }
4416
4417 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4418 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004419 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 RecordData Record;
4421 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004422 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4423
4424 switch (Entry.Kind) {
4425 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4426 case llvm::BitstreamEntry::Error:
4427 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004428 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004429 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004430 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004431 case llvm::BitstreamEntry::Record:
4432 // The interesting case.
4433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004435
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004437 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004439 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4440
4441 if ((Kind == SUBMODULE_METADATA) != First) {
4442 Error("submodule metadata record should be at beginning of block");
4443 return Failure;
4444 }
4445 First = false;
4446
4447 // Submodule information is only valid if we have a current module.
4448 // FIXME: Should we error on these cases?
4449 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4450 Kind != SUBMODULE_DEFINITION)
4451 continue;
4452
4453 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 default: // Default behavior: ignore.
4455 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004456
Richard Smith03478d92014-10-23 22:12:14 +00004457 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004458 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004460 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 }
Richard Smith03478d92014-10-23 22:12:14 +00004462
Chris Lattner0e6c9402013-01-20 02:38:54 +00004463 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004464 unsigned Idx = 0;
4465 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4466 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4467 bool IsFramework = Record[Idx++];
4468 bool IsExplicit = Record[Idx++];
4469 bool IsSystem = Record[Idx++];
4470 bool IsExternC = Record[Idx++];
4471 bool InferSubmodules = Record[Idx++];
4472 bool InferExplicitSubmodules = Record[Idx++];
4473 bool InferExportWildcard = Record[Idx++];
4474 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004475
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004476 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004477 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004479
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 // Retrieve this (sub)module from the module map, creating it if
4481 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004482 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004484
4485 // FIXME: set the definition loc for CurrentModule, or call
4486 // ModMap.setInferredModuleAllowedBy()
4487
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4489 if (GlobalIndex >= SubmodulesLoaded.size() ||
4490 SubmodulesLoaded[GlobalIndex]) {
4491 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004494
Douglas Gregor7029ce12013-03-19 00:28:20 +00004495 if (!ParentModule) {
4496 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4497 if (CurFile != F.File) {
4498 if (!Diags.isDiagnosticInFlight()) {
4499 Diag(diag::err_module_file_conflict)
4500 << CurrentModule->getTopLevelModuleName()
4501 << CurFile->getName()
4502 << F.File->getName();
4503 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004504 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004505 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004506 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004507
4508 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004509 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004510
Adrian Prantl15bcf702015-06-30 17:39:43 +00004511 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 CurrentModule->IsFromModuleFile = true;
4513 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004514 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004515 CurrentModule->InferSubmodules = InferSubmodules;
4516 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4517 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004518 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 if (DeserializationListener)
4520 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4521
4522 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004523
Douglas Gregorfb912652013-03-20 21:10:35 +00004524 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004525 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004526 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004527 CurrentModule->UnresolvedConflicts.clear();
4528 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 break;
4530 }
4531
4532 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004533 std::string Filename = Blob;
4534 ResolveImportedPath(F, Filename);
4535 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004537 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4538 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004539 // This can be a spurious difference caused by changing the VFS to
4540 // point to a different copy of the file, and it is too late to
4541 // to rebuild safely.
4542 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4543 // after input file validation only real problems would remain and we
4544 // could just error. For now, assume it's okay.
4545 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547 }
4548 break;
4549 }
4550
Richard Smith202210b2014-10-24 20:23:01 +00004551 case SUBMODULE_HEADER:
4552 case SUBMODULE_EXCLUDED_HEADER:
4553 case SUBMODULE_PRIVATE_HEADER:
4554 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004555 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4556 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004557 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558
Richard Smith202210b2014-10-24 20:23:01 +00004559 case SUBMODULE_TEXTUAL_HEADER:
4560 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4561 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4562 // them here.
4563 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004564
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004566 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 break;
4568 }
4569
4570 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004571 std::string Dirname = Blob;
4572 ResolveImportedPath(F, Dirname);
4573 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004575 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4576 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004577 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4578 Error("mismatched umbrella directories in submodule");
4579 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 }
4581 }
4582 break;
4583 }
4584
4585 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 F.BaseSubmoduleID = getTotalNumSubmodules();
4587 F.LocalNumSubmodules = Record[0];
4588 unsigned LocalBaseSubmoduleID = Record[1];
4589 if (F.LocalNumSubmodules > 0) {
4590 // Introduce the global -> local mapping for submodules within this
4591 // module.
4592 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4593
4594 // Introduce the local -> global mapping for submodules within this
4595 // module.
4596 F.SubmoduleRemap.insertOrReplace(
4597 std::make_pair(LocalBaseSubmoduleID,
4598 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004599
Ben Langmuir52ca6782014-10-20 16:27:32 +00004600 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4601 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 break;
4603 }
4604
4605 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004607 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 Unresolved.File = &F;
4609 Unresolved.Mod = CurrentModule;
4610 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004611 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004613 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 }
4615 break;
4616 }
4617
4618 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004620 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 Unresolved.File = &F;
4622 Unresolved.Mod = CurrentModule;
4623 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004624 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004626 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 }
4628
4629 // Once we've loaded the set of exports, there's no reason to keep
4630 // the parsed, unresolved exports around.
4631 CurrentModule->UnresolvedExports.clear();
4632 break;
4633 }
4634 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004635 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 Context.getTargetInfo());
4637 break;
4638 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004639
4640 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004641 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004642 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004643 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004644
4645 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004646 CurrentModule->ConfigMacros.push_back(Blob.str());
4647 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004648
4649 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004650 UnresolvedModuleRef Unresolved;
4651 Unresolved.File = &F;
4652 Unresolved.Mod = CurrentModule;
4653 Unresolved.ID = Record[0];
4654 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4655 Unresolved.IsWildcard = false;
4656 Unresolved.String = Blob;
4657 UnresolvedModuleRefs.push_back(Unresolved);
4658 break;
4659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 }
4661 }
4662}
4663
4664/// \brief Parse the record that corresponds to a LangOptions data
4665/// structure.
4666///
4667/// This routine parses the language options from the AST file and then gives
4668/// them to the AST listener if one is set.
4669///
4670/// \returns true if the listener deems the file unacceptable, false otherwise.
4671bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4672 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004673 ASTReaderListener &Listener,
4674 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004675 LangOptions LangOpts;
4676 unsigned Idx = 0;
4677#define LANGOPT(Name, Bits, Default, Description) \
4678 LangOpts.Name = Record[Idx++];
4679#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4680 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4681#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004682#define SANITIZER(NAME, ID) \
4683 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004684#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004685
Ben Langmuircd98cb72015-06-23 18:20:18 +00004686 for (unsigned N = Record[Idx++]; N; --N)
4687 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4688
Guy Benyei11169dd2012-12-18 14:30:41 +00004689 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4690 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4691 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004692
Ben Langmuird4a667a2015-06-23 18:20:23 +00004693 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004694
4695 // Comment options.
4696 for (unsigned N = Record[Idx++]; N; --N) {
4697 LangOpts.CommentOpts.BlockCommandNames.push_back(
4698 ReadString(Record, Idx));
4699 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004700 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004701
Samuel Antaoee8fb302016-01-06 13:42:12 +00004702 // OpenMP offloading options.
4703 for (unsigned N = Record[Idx++]; N; --N) {
4704 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4705 }
4706
4707 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4708
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004709 return Listener.ReadLanguageOptions(LangOpts, Complain,
4710 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004711}
4712
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004713bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4714 ASTReaderListener &Listener,
4715 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 unsigned Idx = 0;
4717 TargetOptions TargetOpts;
4718 TargetOpts.Triple = ReadString(Record, Idx);
4719 TargetOpts.CPU = ReadString(Record, Idx);
4720 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 for (unsigned N = Record[Idx++]; N; --N) {
4722 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4723 }
4724 for (unsigned N = Record[Idx++]; N; --N) {
4725 TargetOpts.Features.push_back(ReadString(Record, Idx));
4726 }
4727
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004728 return Listener.ReadTargetOptions(TargetOpts, Complain,
4729 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004730}
4731
4732bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4733 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004734 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004736#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004737#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004738 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004739#include "clang/Basic/DiagnosticOptions.def"
4740
Richard Smith3be1cb22014-08-07 00:24:21 +00004741 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004742 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004743 for (unsigned N = Record[Idx++]; N; --N)
4744 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004745
4746 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4747}
4748
4749bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4750 ASTReaderListener &Listener) {
4751 FileSystemOptions FSOpts;
4752 unsigned Idx = 0;
4753 FSOpts.WorkingDir = ReadString(Record, Idx);
4754 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4755}
4756
4757bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4758 bool Complain,
4759 ASTReaderListener &Listener) {
4760 HeaderSearchOptions HSOpts;
4761 unsigned Idx = 0;
4762 HSOpts.Sysroot = ReadString(Record, Idx);
4763
4764 // Include entries.
4765 for (unsigned N = Record[Idx++]; N; --N) {
4766 std::string Path = ReadString(Record, Idx);
4767 frontend::IncludeDirGroup Group
4768 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 bool IsFramework = Record[Idx++];
4770 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004771 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4772 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 }
4774
4775 // System header prefixes.
4776 for (unsigned N = Record[Idx++]; N; --N) {
4777 std::string Prefix = ReadString(Record, Idx);
4778 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004779 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004780 }
4781
4782 HSOpts.ResourceDir = ReadString(Record, Idx);
4783 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004784 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 HSOpts.DisableModuleHash = Record[Idx++];
4786 HSOpts.UseBuiltinIncludes = Record[Idx++];
4787 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4788 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4789 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004790 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004791
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004792 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4793 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004794}
4795
4796bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4797 bool Complain,
4798 ASTReaderListener &Listener,
4799 std::string &SuggestedPredefines) {
4800 PreprocessorOptions PPOpts;
4801 unsigned Idx = 0;
4802
4803 // Macro definitions/undefs
4804 for (unsigned N = Record[Idx++]; N; --N) {
4805 std::string Macro = ReadString(Record, Idx);
4806 bool IsUndef = Record[Idx++];
4807 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4808 }
4809
4810 // Includes
4811 for (unsigned N = Record[Idx++]; N; --N) {
4812 PPOpts.Includes.push_back(ReadString(Record, Idx));
4813 }
4814
4815 // Macro Includes
4816 for (unsigned N = Record[Idx++]; N; --N) {
4817 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4818 }
4819
4820 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004821 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4823 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4824 PPOpts.ObjCXXARCStandardLibrary =
4825 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4826 SuggestedPredefines.clear();
4827 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4828 SuggestedPredefines);
4829}
4830
4831std::pair<ModuleFile *, unsigned>
4832ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4833 GlobalPreprocessedEntityMapType::iterator
4834 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4835 assert(I != GlobalPreprocessedEntityMap.end() &&
4836 "Corrupted global preprocessed entity map");
4837 ModuleFile *M = I->second;
4838 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4839 return std::make_pair(M, LocalIndex);
4840}
4841
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004842llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004843ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4844 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4845 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4846 Mod.NumPreprocessedEntities);
4847
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004848 return llvm::make_range(PreprocessingRecord::iterator(),
4849 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004850}
4851
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004852llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004853ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004854 return llvm::make_range(
4855 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4856 ModuleDeclIterator(this, &Mod,
4857 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004858}
4859
4860PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4861 PreprocessedEntityID PPID = Index+1;
4862 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4863 ModuleFile &M = *PPInfo.first;
4864 unsigned LocalIndex = PPInfo.second;
4865 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4866
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 if (!PP.getPreprocessingRecord()) {
4868 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004869 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 }
4871
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004872 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4873 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4874
4875 llvm::BitstreamEntry Entry =
4876 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4877 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004878 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004879
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 // Read the record.
4881 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4882 ReadSourceLocation(M, PPOffs.End));
4883 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004884 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 RecordData Record;
4886 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004887 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4888 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 switch (RecType) {
4890 case PPD_MACRO_EXPANSION: {
4891 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004892 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004893 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 if (isBuiltin)
4895 Name = getLocalIdentifier(M, Record[1]);
4896 else {
Richard Smith66a81862015-05-04 02:25:31 +00004897 PreprocessedEntityID GlobalID =
4898 getGlobalPreprocessedEntityID(M, Record[1]);
4899 Def = cast<MacroDefinitionRecord>(
4900 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 }
4902
4903 MacroExpansion *ME;
4904 if (isBuiltin)
4905 ME = new (PPRec) MacroExpansion(Name, Range);
4906 else
4907 ME = new (PPRec) MacroExpansion(Def, Range);
4908
4909 return ME;
4910 }
4911
4912 case PPD_MACRO_DEFINITION: {
4913 // Decode the identifier info and then check again; if the macro is
4914 // still defined and associated with the identifier,
4915 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004916 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004917
4918 if (DeserializationListener)
4919 DeserializationListener->MacroDefinitionRead(PPID, MD);
4920
4921 return MD;
4922 }
4923
4924 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004925 const char *FullFileNameStart = Blob.data() + Record[0];
4926 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004927 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 if (!FullFileName.empty())
4929 File = PP.getFileManager().getFile(FullFileName);
4930
4931 // FIXME: Stable encoding
4932 InclusionDirective::InclusionKind Kind
4933 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4934 InclusionDirective *ID
4935 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004936 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 Record[1], Record[3],
4938 File,
4939 Range);
4940 return ID;
4941 }
4942 }
4943
4944 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4945}
4946
4947/// \brief \arg SLocMapI points at a chunk of a module that contains no
4948/// preprocessed entities or the entities it contains are not the ones we are
4949/// looking for. Find the next module that contains entities and return the ID
4950/// of the first entry.
4951PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4952 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4953 ++SLocMapI;
4954 for (GlobalSLocOffsetMapType::const_iterator
4955 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4956 ModuleFile &M = *SLocMapI->second;
4957 if (M.NumPreprocessedEntities)
4958 return M.BasePreprocessedEntityID;
4959 }
4960
4961 return getTotalNumPreprocessedEntities();
4962}
4963
4964namespace {
4965
4966template <unsigned PPEntityOffset::*PPLoc>
4967struct PPEntityComp {
4968 const ASTReader &Reader;
4969 ModuleFile &M;
4970
4971 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4972
4973 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4974 SourceLocation LHS = getLoc(L);
4975 SourceLocation RHS = getLoc(R);
4976 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4977 }
4978
4979 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4980 SourceLocation LHS = getLoc(L);
4981 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4982 }
4983
4984 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4985 SourceLocation RHS = getLoc(R);
4986 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4987 }
4988
4989 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4990 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4991 }
4992};
4993
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004994}
Guy Benyei11169dd2012-12-18 14:30:41 +00004995
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004996PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4997 bool EndsAfter) const {
4998 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 return getTotalNumPreprocessedEntities();
5000
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005001 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5002 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5004 "Corrupted global sloc offset map");
5005
5006 if (SLocMapI->second->NumPreprocessedEntities == 0)
5007 return findNextPreprocessedEntity(SLocMapI);
5008
5009 ModuleFile &M = *SLocMapI->second;
5010 typedef const PPEntityOffset *pp_iterator;
5011 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5012 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5013
5014 size_t Count = M.NumPreprocessedEntities;
5015 size_t Half;
5016 pp_iterator First = pp_begin;
5017 pp_iterator PPI;
5018
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005019 if (EndsAfter) {
5020 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5021 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5022 } else {
5023 // Do a binary search manually instead of using std::lower_bound because
5024 // The end locations of entities may be unordered (when a macro expansion
5025 // is inside another macro argument), but for this case it is not important
5026 // whether we get the first macro expansion or its containing macro.
5027 while (Count > 0) {
5028 Half = Count / 2;
5029 PPI = First;
5030 std::advance(PPI, Half);
5031 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5032 Loc)) {
5033 First = PPI;
5034 ++First;
5035 Count = Count - Half - 1;
5036 } else
5037 Count = Half;
5038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 }
5040
5041 if (PPI == pp_end)
5042 return findNextPreprocessedEntity(SLocMapI);
5043
5044 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5045}
5046
Guy Benyei11169dd2012-12-18 14:30:41 +00005047/// \brief Returns a pair of [Begin, End) indices of preallocated
5048/// preprocessed entities that \arg Range encompasses.
5049std::pair<unsigned, unsigned>
5050 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5051 if (Range.isInvalid())
5052 return std::make_pair(0,0);
5053 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5054
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005055 PreprocessedEntityID BeginID =
5056 findPreprocessedEntity(Range.getBegin(), false);
5057 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 return std::make_pair(BeginID, EndID);
5059}
5060
5061/// \brief Optionally returns true or false if the preallocated preprocessed
5062/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005063Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 FileID FID) {
5065 if (FID.isInvalid())
5066 return false;
5067
5068 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5069 ModuleFile &M = *PPInfo.first;
5070 unsigned LocalIndex = PPInfo.second;
5071 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5072
5073 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5074 if (Loc.isInvalid())
5075 return false;
5076
5077 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5078 return true;
5079 else
5080 return false;
5081}
5082
5083namespace {
5084 /// \brief Visitor used to search for information about a header file.
5085 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 const FileEntry *FE;
5087
David Blaikie05785d12013-02-20 22:23:23 +00005088 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005089
5090 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005091 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5092 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005093
5094 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 HeaderFileInfoLookupTable *Table
5096 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5097 if (!Table)
5098 return false;
5099
5100 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005101 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 if (Pos == Table->end())
5103 return false;
5104
Richard Smithbdf2d932015-07-30 03:37:16 +00005105 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005106 return true;
5107 }
5108
David Blaikie05785d12013-02-20 22:23:23 +00005109 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005111}
Guy Benyei11169dd2012-12-18 14:30:41 +00005112
5113HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005114 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005115 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005116 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005118
5119 return HeaderFileInfo();
5120}
5121
5122void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5123 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005124 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5126 ModuleFile &F = *(*I);
5127 unsigned Idx = 0;
5128 DiagStates.clear();
5129 assert(!Diag.DiagStates.empty());
5130 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5131 while (Idx < F.PragmaDiagMappings.size()) {
5132 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5133 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5134 if (DiagStateID != 0) {
5135 Diag.DiagStatePoints.push_back(
5136 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5137 FullSourceLoc(Loc, SourceMgr)));
5138 continue;
5139 }
5140
5141 assert(DiagStateID == 0);
5142 // A new DiagState was created here.
5143 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5144 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5145 DiagStates.push_back(NewState);
5146 Diag.DiagStatePoints.push_back(
5147 DiagnosticsEngine::DiagStatePoint(NewState,
5148 FullSourceLoc(Loc, SourceMgr)));
5149 while (1) {
5150 assert(Idx < F.PragmaDiagMappings.size() &&
5151 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5152 if (Idx >= F.PragmaDiagMappings.size()) {
5153 break; // Something is messed up but at least avoid infinite loop in
5154 // release build.
5155 }
5156 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5157 if (DiagID == (unsigned)-1) {
5158 break; // no more diag/map pairs for this location.
5159 }
Alp Tokerc726c362014-06-10 09:31:37 +00005160 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5161 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5162 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 }
5164 }
5165 }
5166}
5167
5168/// \brief Get the correct cursor and offset for loading a type.
5169ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5170 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5171 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5172 ModuleFile *M = I->second;
5173 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5174}
5175
5176/// \brief Read and return the type with the given index..
5177///
5178/// The index is the type ID, shifted and minus the number of predefs. This
5179/// routine actually reads the record corresponding to the type at the given
5180/// location. It is a helper routine for GetType, which deals with reading type
5181/// IDs.
5182QualType ASTReader::readTypeRecord(unsigned Index) {
5183 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005184 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005185
5186 // Keep track of where we are in the stream, then jump back there
5187 // after reading this type.
5188 SavedStreamPosition SavedPosition(DeclsCursor);
5189
5190 ReadingKindTracker ReadingKind(Read_Type, *this);
5191
5192 // Note that we are loading a type record.
5193 Deserializing AType(this);
5194
5195 unsigned Idx = 0;
5196 DeclsCursor.JumpToBit(Loc.Offset);
5197 RecordData Record;
5198 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005199 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 case TYPE_EXT_QUAL: {
5201 if (Record.size() != 2) {
5202 Error("Incorrect encoding of extended qualifier type");
5203 return QualType();
5204 }
5205 QualType Base = readType(*Loc.F, Record, Idx);
5206 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5207 return Context.getQualifiedType(Base, Quals);
5208 }
5209
5210 case TYPE_COMPLEX: {
5211 if (Record.size() != 1) {
5212 Error("Incorrect encoding of complex type");
5213 return QualType();
5214 }
5215 QualType ElemType = readType(*Loc.F, Record, Idx);
5216 return Context.getComplexType(ElemType);
5217 }
5218
5219 case TYPE_POINTER: {
5220 if (Record.size() != 1) {
5221 Error("Incorrect encoding of pointer type");
5222 return QualType();
5223 }
5224 QualType PointeeType = readType(*Loc.F, Record, Idx);
5225 return Context.getPointerType(PointeeType);
5226 }
5227
Reid Kleckner8a365022013-06-24 17:51:48 +00005228 case TYPE_DECAYED: {
5229 if (Record.size() != 1) {
5230 Error("Incorrect encoding of decayed type");
5231 return QualType();
5232 }
5233 QualType OriginalType = readType(*Loc.F, Record, Idx);
5234 QualType DT = Context.getAdjustedParameterType(OriginalType);
5235 if (!isa<DecayedType>(DT))
5236 Error("Decayed type does not decay");
5237 return DT;
5238 }
5239
Reid Kleckner0503a872013-12-05 01:23:43 +00005240 case TYPE_ADJUSTED: {
5241 if (Record.size() != 2) {
5242 Error("Incorrect encoding of adjusted type");
5243 return QualType();
5244 }
5245 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5246 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5247 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5248 }
5249
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 case TYPE_BLOCK_POINTER: {
5251 if (Record.size() != 1) {
5252 Error("Incorrect encoding of block pointer type");
5253 return QualType();
5254 }
5255 QualType PointeeType = readType(*Loc.F, Record, Idx);
5256 return Context.getBlockPointerType(PointeeType);
5257 }
5258
5259 case TYPE_LVALUE_REFERENCE: {
5260 if (Record.size() != 2) {
5261 Error("Incorrect encoding of lvalue reference type");
5262 return QualType();
5263 }
5264 QualType PointeeType = readType(*Loc.F, Record, Idx);
5265 return Context.getLValueReferenceType(PointeeType, Record[1]);
5266 }
5267
5268 case TYPE_RVALUE_REFERENCE: {
5269 if (Record.size() != 1) {
5270 Error("Incorrect encoding of rvalue reference type");
5271 return QualType();
5272 }
5273 QualType PointeeType = readType(*Loc.F, Record, Idx);
5274 return Context.getRValueReferenceType(PointeeType);
5275 }
5276
5277 case TYPE_MEMBER_POINTER: {
5278 if (Record.size() != 2) {
5279 Error("Incorrect encoding of member pointer type");
5280 return QualType();
5281 }
5282 QualType PointeeType = readType(*Loc.F, Record, Idx);
5283 QualType ClassType = readType(*Loc.F, Record, Idx);
5284 if (PointeeType.isNull() || ClassType.isNull())
5285 return QualType();
5286
5287 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5288 }
5289
5290 case TYPE_CONSTANT_ARRAY: {
5291 QualType ElementType = readType(*Loc.F, Record, Idx);
5292 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5293 unsigned IndexTypeQuals = Record[2];
5294 unsigned Idx = 3;
5295 llvm::APInt Size = ReadAPInt(Record, Idx);
5296 return Context.getConstantArrayType(ElementType, Size,
5297 ASM, IndexTypeQuals);
5298 }
5299
5300 case TYPE_INCOMPLETE_ARRAY: {
5301 QualType ElementType = readType(*Loc.F, Record, Idx);
5302 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5303 unsigned IndexTypeQuals = Record[2];
5304 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5305 }
5306
5307 case TYPE_VARIABLE_ARRAY: {
5308 QualType ElementType = readType(*Loc.F, Record, Idx);
5309 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5310 unsigned IndexTypeQuals = Record[2];
5311 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5312 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5313 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5314 ASM, IndexTypeQuals,
5315 SourceRange(LBLoc, RBLoc));
5316 }
5317
5318 case TYPE_VECTOR: {
5319 if (Record.size() != 3) {
5320 Error("incorrect encoding of vector type in AST file");
5321 return QualType();
5322 }
5323
5324 QualType ElementType = readType(*Loc.F, Record, Idx);
5325 unsigned NumElements = Record[1];
5326 unsigned VecKind = Record[2];
5327 return Context.getVectorType(ElementType, NumElements,
5328 (VectorType::VectorKind)VecKind);
5329 }
5330
5331 case TYPE_EXT_VECTOR: {
5332 if (Record.size() != 3) {
5333 Error("incorrect encoding of extended vector type in AST file");
5334 return QualType();
5335 }
5336
5337 QualType ElementType = readType(*Loc.F, Record, Idx);
5338 unsigned NumElements = Record[1];
5339 return Context.getExtVectorType(ElementType, NumElements);
5340 }
5341
5342 case TYPE_FUNCTION_NO_PROTO: {
5343 if (Record.size() != 6) {
5344 Error("incorrect encoding of no-proto function type");
5345 return QualType();
5346 }
5347 QualType ResultType = readType(*Loc.F, Record, Idx);
5348 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5349 (CallingConv)Record[4], Record[5]);
5350 return Context.getFunctionNoProtoType(ResultType, Info);
5351 }
5352
5353 case TYPE_FUNCTION_PROTO: {
5354 QualType ResultType = readType(*Loc.F, Record, Idx);
5355
5356 FunctionProtoType::ExtProtoInfo EPI;
5357 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5358 /*hasregparm*/ Record[2],
5359 /*regparm*/ Record[3],
5360 static_cast<CallingConv>(Record[4]),
5361 /*produces*/ Record[5]);
5362
5363 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005364
5365 EPI.Variadic = Record[Idx++];
5366 EPI.HasTrailingReturn = Record[Idx++];
5367 EPI.TypeQuals = Record[Idx++];
5368 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005369 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005370 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005371
5372 unsigned NumParams = Record[Idx++];
5373 SmallVector<QualType, 16> ParamTypes;
5374 for (unsigned I = 0; I != NumParams; ++I)
5375 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5376
Jordan Rose5c382722013-03-08 21:51:21 +00005377 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005378 }
5379
5380 case TYPE_UNRESOLVED_USING: {
5381 unsigned Idx = 0;
5382 return Context.getTypeDeclType(
5383 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5384 }
5385
5386 case TYPE_TYPEDEF: {
5387 if (Record.size() != 2) {
5388 Error("incorrect encoding of typedef type");
5389 return QualType();
5390 }
5391 unsigned Idx = 0;
5392 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5393 QualType Canonical = readType(*Loc.F, Record, Idx);
5394 if (!Canonical.isNull())
5395 Canonical = Context.getCanonicalType(Canonical);
5396 return Context.getTypedefType(Decl, Canonical);
5397 }
5398
5399 case TYPE_TYPEOF_EXPR:
5400 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5401
5402 case TYPE_TYPEOF: {
5403 if (Record.size() != 1) {
5404 Error("incorrect encoding of typeof(type) in AST file");
5405 return QualType();
5406 }
5407 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5408 return Context.getTypeOfType(UnderlyingType);
5409 }
5410
5411 case TYPE_DECLTYPE: {
5412 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5413 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5414 }
5415
5416 case TYPE_UNARY_TRANSFORM: {
5417 QualType BaseType = readType(*Loc.F, Record, Idx);
5418 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5419 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5420 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5421 }
5422
Richard Smith74aeef52013-04-26 16:15:35 +00005423 case TYPE_AUTO: {
5424 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005425 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005426 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005427 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005429
5430 case TYPE_RECORD: {
5431 if (Record.size() != 2) {
5432 Error("incorrect encoding of record type");
5433 return QualType();
5434 }
5435 unsigned Idx = 0;
5436 bool IsDependent = Record[Idx++];
5437 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5438 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5439 QualType T = Context.getRecordType(RD);
5440 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5441 return T;
5442 }
5443
5444 case TYPE_ENUM: {
5445 if (Record.size() != 2) {
5446 Error("incorrect encoding of enum type");
5447 return QualType();
5448 }
5449 unsigned Idx = 0;
5450 bool IsDependent = Record[Idx++];
5451 QualType T
5452 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5453 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5454 return T;
5455 }
5456
5457 case TYPE_ATTRIBUTED: {
5458 if (Record.size() != 3) {
5459 Error("incorrect encoding of attributed type");
5460 return QualType();
5461 }
5462 QualType modifiedType = readType(*Loc.F, Record, Idx);
5463 QualType equivalentType = readType(*Loc.F, Record, Idx);
5464 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5465 return Context.getAttributedType(kind, modifiedType, equivalentType);
5466 }
5467
5468 case TYPE_PAREN: {
5469 if (Record.size() != 1) {
5470 Error("incorrect encoding of paren type");
5471 return QualType();
5472 }
5473 QualType InnerType = readType(*Loc.F, Record, Idx);
5474 return Context.getParenType(InnerType);
5475 }
5476
5477 case TYPE_PACK_EXPANSION: {
5478 if (Record.size() != 2) {
5479 Error("incorrect encoding of pack expansion type");
5480 return QualType();
5481 }
5482 QualType Pattern = readType(*Loc.F, Record, Idx);
5483 if (Pattern.isNull())
5484 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005485 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005486 if (Record[1])
5487 NumExpansions = Record[1] - 1;
5488 return Context.getPackExpansionType(Pattern, NumExpansions);
5489 }
5490
5491 case TYPE_ELABORATED: {
5492 unsigned Idx = 0;
5493 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5494 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5495 QualType NamedType = readType(*Loc.F, Record, Idx);
5496 return Context.getElaboratedType(Keyword, NNS, NamedType);
5497 }
5498
5499 case TYPE_OBJC_INTERFACE: {
5500 unsigned Idx = 0;
5501 ObjCInterfaceDecl *ItfD
5502 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5503 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5504 }
5505
5506 case TYPE_OBJC_OBJECT: {
5507 unsigned Idx = 0;
5508 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005509 unsigned NumTypeArgs = Record[Idx++];
5510 SmallVector<QualType, 4> TypeArgs;
5511 for (unsigned I = 0; I != NumTypeArgs; ++I)
5512 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 unsigned NumProtos = Record[Idx++];
5514 SmallVector<ObjCProtocolDecl*, 4> Protos;
5515 for (unsigned I = 0; I != NumProtos; ++I)
5516 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005517 bool IsKindOf = Record[Idx++];
5518 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 }
5520
5521 case TYPE_OBJC_OBJECT_POINTER: {
5522 unsigned Idx = 0;
5523 QualType Pointee = readType(*Loc.F, Record, Idx);
5524 return Context.getObjCObjectPointerType(Pointee);
5525 }
5526
5527 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5528 unsigned Idx = 0;
5529 QualType Parm = readType(*Loc.F, Record, Idx);
5530 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005531 return Context.getSubstTemplateTypeParmType(
5532 cast<TemplateTypeParmType>(Parm),
5533 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005534 }
5535
5536 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5537 unsigned Idx = 0;
5538 QualType Parm = readType(*Loc.F, Record, Idx);
5539 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5540 return Context.getSubstTemplateTypeParmPackType(
5541 cast<TemplateTypeParmType>(Parm),
5542 ArgPack);
5543 }
5544
5545 case TYPE_INJECTED_CLASS_NAME: {
5546 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5547 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5548 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5549 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005550 const Type *T = nullptr;
5551 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5552 if (const Type *Existing = DI->getTypeForDecl()) {
5553 T = Existing;
5554 break;
5555 }
5556 }
5557 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005558 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005559 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5560 DI->setTypeForDecl(T);
5561 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005562 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 }
5564
5565 case TYPE_TEMPLATE_TYPE_PARM: {
5566 unsigned Idx = 0;
5567 unsigned Depth = Record[Idx++];
5568 unsigned Index = Record[Idx++];
5569 bool Pack = Record[Idx++];
5570 TemplateTypeParmDecl *D
5571 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5572 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5573 }
5574
5575 case TYPE_DEPENDENT_NAME: {
5576 unsigned Idx = 0;
5577 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5578 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005579 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005580 QualType Canon = readType(*Loc.F, Record, Idx);
5581 if (!Canon.isNull())
5582 Canon = Context.getCanonicalType(Canon);
5583 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5584 }
5585
5586 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5587 unsigned Idx = 0;
5588 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5589 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005590 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005591 unsigned NumArgs = Record[Idx++];
5592 SmallVector<TemplateArgument, 8> Args;
5593 Args.reserve(NumArgs);
5594 while (NumArgs--)
5595 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5596 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5597 Args.size(), Args.data());
5598 }
5599
5600 case TYPE_DEPENDENT_SIZED_ARRAY: {
5601 unsigned Idx = 0;
5602
5603 // ArrayType
5604 QualType ElementType = readType(*Loc.F, Record, Idx);
5605 ArrayType::ArraySizeModifier ASM
5606 = (ArrayType::ArraySizeModifier)Record[Idx++];
5607 unsigned IndexTypeQuals = Record[Idx++];
5608
5609 // DependentSizedArrayType
5610 Expr *NumElts = ReadExpr(*Loc.F);
5611 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5612
5613 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5614 IndexTypeQuals, Brackets);
5615 }
5616
5617 case TYPE_TEMPLATE_SPECIALIZATION: {
5618 unsigned Idx = 0;
5619 bool IsDependent = Record[Idx++];
5620 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5621 SmallVector<TemplateArgument, 8> Args;
5622 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5623 QualType Underlying = readType(*Loc.F, Record, Idx);
5624 QualType T;
5625 if (Underlying.isNull())
5626 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5627 Args.size());
5628 else
5629 T = Context.getTemplateSpecializationType(Name, Args.data(),
5630 Args.size(), Underlying);
5631 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5632 return T;
5633 }
5634
5635 case TYPE_ATOMIC: {
5636 if (Record.size() != 1) {
5637 Error("Incorrect encoding of atomic type");
5638 return QualType();
5639 }
5640 QualType ValueType = readType(*Loc.F, Record, Idx);
5641 return Context.getAtomicType(ValueType);
5642 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005643
5644 case TYPE_PIPE: {
5645 if (Record.size() != 1) {
5646 Error("Incorrect encoding of pipe type");
5647 return QualType();
5648 }
5649
5650 // Reading the pipe element type.
5651 QualType ElementType = readType(*Loc.F, Record, Idx);
5652 return Context.getPipeType(ElementType);
5653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005654 }
5655 llvm_unreachable("Invalid TypeCode!");
5656}
5657
Richard Smith564417a2014-03-20 21:47:22 +00005658void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5659 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005660 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005661 const RecordData &Record, unsigned &Idx) {
5662 ExceptionSpecificationType EST =
5663 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005664 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005665 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005666 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005667 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005668 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005669 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005670 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005671 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005672 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5673 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005674 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005675 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005676 }
5677}
5678
Guy Benyei11169dd2012-12-18 14:30:41 +00005679class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5680 ASTReader &Reader;
5681 ModuleFile &F;
5682 const ASTReader::RecordData &Record;
5683 unsigned &Idx;
5684
5685 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5686 unsigned &I) {
5687 return Reader.ReadSourceLocation(F, R, I);
5688 }
5689
5690 template<typename T>
5691 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5692 return Reader.ReadDeclAs<T>(F, Record, Idx);
5693 }
5694
5695public:
5696 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5697 const ASTReader::RecordData &Record, unsigned &Idx)
5698 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5699 { }
5700
5701 // We want compile-time assurance that we've enumerated all of
5702 // these, so unfortunately we have to declare them first, then
5703 // define them out-of-line.
5704#define ABSTRACT_TYPELOC(CLASS, PARENT)
5705#define TYPELOC(CLASS, PARENT) \
5706 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5707#include "clang/AST/TypeLocNodes.def"
5708
5709 void VisitFunctionTypeLoc(FunctionTypeLoc);
5710 void VisitArrayTypeLoc(ArrayTypeLoc);
5711};
5712
5713void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5714 // nothing to do
5715}
5716void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5717 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5718 if (TL.needsExtraLocalData()) {
5719 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5720 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5721 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5722 TL.setModeAttr(Record[Idx++]);
5723 }
5724}
5725void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5726 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5727}
5728void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5729 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5730}
Reid Kleckner8a365022013-06-24 17:51:48 +00005731void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5732 // nothing to do
5733}
Reid Kleckner0503a872013-12-05 01:23:43 +00005734void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5735 // nothing to do
5736}
Guy Benyei11169dd2012-12-18 14:30:41 +00005737void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5738 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5739}
5740void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5741 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5744 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5745}
5746void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5747 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5748 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5749}
5750void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5751 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5752 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5753 if (Record[Idx++])
5754 TL.setSizeExpr(Reader.ReadExpr(F));
5755 else
Craig Toppera13603a2014-05-22 05:54:18 +00005756 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005757}
5758void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5759 VisitArrayTypeLoc(TL);
5760}
5761void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5762 VisitArrayTypeLoc(TL);
5763}
5764void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5765 VisitArrayTypeLoc(TL);
5766}
5767void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5768 DependentSizedArrayTypeLoc TL) {
5769 VisitArrayTypeLoc(TL);
5770}
5771void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5772 DependentSizedExtVectorTypeLoc TL) {
5773 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5774}
5775void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5776 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5777}
5778void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5779 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5780}
5781void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5782 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5783 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5784 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5785 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005786 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5787 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005788 }
5789}
5790void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5791 VisitFunctionTypeLoc(TL);
5792}
5793void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5794 VisitFunctionTypeLoc(TL);
5795}
5796void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5797 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5798}
5799void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5800 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801}
5802void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5803 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5804 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5805 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5806}
5807void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5808 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5809 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5810 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5811 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5812}
5813void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5814 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5815}
5816void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5817 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5818 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5819 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5820 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5821}
5822void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5823 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5826 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5829 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5830}
5831void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5832 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5833 if (TL.hasAttrOperand()) {
5834 SourceRange range;
5835 range.setBegin(ReadSourceLocation(Record, Idx));
5836 range.setEnd(ReadSourceLocation(Record, Idx));
5837 TL.setAttrOperandParensRange(range);
5838 }
5839 if (TL.hasAttrExprOperand()) {
5840 if (Record[Idx++])
5841 TL.setAttrExprOperand(Reader.ReadExpr(F));
5842 else
Craig Toppera13603a2014-05-22 05:54:18 +00005843 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 } else if (TL.hasAttrEnumOperand())
5845 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5846}
5847void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5848 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5849}
5850void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5851 SubstTemplateTypeParmTypeLoc TL) {
5852 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5853}
5854void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5855 SubstTemplateTypeParmPackTypeLoc TL) {
5856 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5857}
5858void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5859 TemplateSpecializationTypeLoc TL) {
5860 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5861 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5862 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5863 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5864 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5865 TL.setArgLocInfo(i,
5866 Reader.GetTemplateArgumentLocInfo(F,
5867 TL.getTypePtr()->getArg(i).getKind(),
5868 Record, Idx));
5869}
5870void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5871 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5872 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5873}
5874void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5875 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5876 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5877}
5878void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5879 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5880}
5881void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5882 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5883 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5884 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5885}
5886void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5887 DependentTemplateSpecializationTypeLoc TL) {
5888 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5889 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5890 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5891 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5892 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5893 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5894 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5895 TL.setArgLocInfo(I,
5896 Reader.GetTemplateArgumentLocInfo(F,
5897 TL.getTypePtr()->getArg(I).getKind(),
5898 Record, Idx));
5899}
5900void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5901 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5902}
5903void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5904 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5905}
5906void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5907 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005908 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5909 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5910 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5911 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5912 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5913 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005914 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5915 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5916}
5917void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5918 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5919}
5920void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5921 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5922 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5923 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5924}
Xiuli Pan9c14e282016-01-09 12:53:17 +00005925void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
5926 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5927}
Guy Benyei11169dd2012-12-18 14:30:41 +00005928
5929TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5930 const RecordData &Record,
5931 unsigned &Idx) {
5932 QualType InfoTy = readType(F, Record, Idx);
5933 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005934 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005935
5936 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5937 TypeLocReader TLR(*this, F, Record, Idx);
5938 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5939 TLR.Visit(TL);
5940 return TInfo;
5941}
5942
5943QualType ASTReader::GetType(TypeID ID) {
5944 unsigned FastQuals = ID & Qualifiers::FastMask;
5945 unsigned Index = ID >> Qualifiers::FastWidth;
5946
5947 if (Index < NUM_PREDEF_TYPE_IDS) {
5948 QualType T;
5949 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005950 case PREDEF_TYPE_NULL_ID:
5951 return QualType();
5952 case PREDEF_TYPE_VOID_ID:
5953 T = Context.VoidTy;
5954 break;
5955 case PREDEF_TYPE_BOOL_ID:
5956 T = Context.BoolTy;
5957 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005958
5959 case PREDEF_TYPE_CHAR_U_ID:
5960 case PREDEF_TYPE_CHAR_S_ID:
5961 // FIXME: Check that the signedness of CharTy is correct!
5962 T = Context.CharTy;
5963 break;
5964
Alexey Baderbdf7c842015-09-15 12:18:29 +00005965 case PREDEF_TYPE_UCHAR_ID:
5966 T = Context.UnsignedCharTy;
5967 break;
5968 case PREDEF_TYPE_USHORT_ID:
5969 T = Context.UnsignedShortTy;
5970 break;
5971 case PREDEF_TYPE_UINT_ID:
5972 T = Context.UnsignedIntTy;
5973 break;
5974 case PREDEF_TYPE_ULONG_ID:
5975 T = Context.UnsignedLongTy;
5976 break;
5977 case PREDEF_TYPE_ULONGLONG_ID:
5978 T = Context.UnsignedLongLongTy;
5979 break;
5980 case PREDEF_TYPE_UINT128_ID:
5981 T = Context.UnsignedInt128Ty;
5982 break;
5983 case PREDEF_TYPE_SCHAR_ID:
5984 T = Context.SignedCharTy;
5985 break;
5986 case PREDEF_TYPE_WCHAR_ID:
5987 T = Context.WCharTy;
5988 break;
5989 case PREDEF_TYPE_SHORT_ID:
5990 T = Context.ShortTy;
5991 break;
5992 case PREDEF_TYPE_INT_ID:
5993 T = Context.IntTy;
5994 break;
5995 case PREDEF_TYPE_LONG_ID:
5996 T = Context.LongTy;
5997 break;
5998 case PREDEF_TYPE_LONGLONG_ID:
5999 T = Context.LongLongTy;
6000 break;
6001 case PREDEF_TYPE_INT128_ID:
6002 T = Context.Int128Ty;
6003 break;
6004 case PREDEF_TYPE_HALF_ID:
6005 T = Context.HalfTy;
6006 break;
6007 case PREDEF_TYPE_FLOAT_ID:
6008 T = Context.FloatTy;
6009 break;
6010 case PREDEF_TYPE_DOUBLE_ID:
6011 T = Context.DoubleTy;
6012 break;
6013 case PREDEF_TYPE_LONGDOUBLE_ID:
6014 T = Context.LongDoubleTy;
6015 break;
6016 case PREDEF_TYPE_OVERLOAD_ID:
6017 T = Context.OverloadTy;
6018 break;
6019 case PREDEF_TYPE_BOUND_MEMBER:
6020 T = Context.BoundMemberTy;
6021 break;
6022 case PREDEF_TYPE_PSEUDO_OBJECT:
6023 T = Context.PseudoObjectTy;
6024 break;
6025 case PREDEF_TYPE_DEPENDENT_ID:
6026 T = Context.DependentTy;
6027 break;
6028 case PREDEF_TYPE_UNKNOWN_ANY:
6029 T = Context.UnknownAnyTy;
6030 break;
6031 case PREDEF_TYPE_NULLPTR_ID:
6032 T = Context.NullPtrTy;
6033 break;
6034 case PREDEF_TYPE_CHAR16_ID:
6035 T = Context.Char16Ty;
6036 break;
6037 case PREDEF_TYPE_CHAR32_ID:
6038 T = Context.Char32Ty;
6039 break;
6040 case PREDEF_TYPE_OBJC_ID:
6041 T = Context.ObjCBuiltinIdTy;
6042 break;
6043 case PREDEF_TYPE_OBJC_CLASS:
6044 T = Context.ObjCBuiltinClassTy;
6045 break;
6046 case PREDEF_TYPE_OBJC_SEL:
6047 T = Context.ObjCBuiltinSelTy;
6048 break;
6049 case PREDEF_TYPE_IMAGE1D_ID:
6050 T = Context.OCLImage1dTy;
6051 break;
6052 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6053 T = Context.OCLImage1dArrayTy;
6054 break;
6055 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6056 T = Context.OCLImage1dBufferTy;
6057 break;
6058 case PREDEF_TYPE_IMAGE2D_ID:
6059 T = Context.OCLImage2dTy;
6060 break;
6061 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6062 T = Context.OCLImage2dArrayTy;
6063 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006064 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6065 T = Context.OCLImage2dDepthTy;
6066 break;
6067 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6068 T = Context.OCLImage2dArrayDepthTy;
6069 break;
6070 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6071 T = Context.OCLImage2dMSAATy;
6072 break;
6073 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6074 T = Context.OCLImage2dArrayMSAATy;
6075 break;
6076 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6077 T = Context.OCLImage2dMSAADepthTy;
6078 break;
6079 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6080 T = Context.OCLImage2dArrayMSAADepthTy;
6081 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006082 case PREDEF_TYPE_IMAGE3D_ID:
6083 T = Context.OCLImage3dTy;
6084 break;
6085 case PREDEF_TYPE_SAMPLER_ID:
6086 T = Context.OCLSamplerTy;
6087 break;
6088 case PREDEF_TYPE_EVENT_ID:
6089 T = Context.OCLEventTy;
6090 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006091 case PREDEF_TYPE_CLK_EVENT_ID:
6092 T = Context.OCLClkEventTy;
6093 break;
6094 case PREDEF_TYPE_QUEUE_ID:
6095 T = Context.OCLQueueTy;
6096 break;
6097 case PREDEF_TYPE_NDRANGE_ID:
6098 T = Context.OCLNDRangeTy;
6099 break;
6100 case PREDEF_TYPE_RESERVE_ID_ID:
6101 T = Context.OCLReserveIDTy;
6102 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006103 case PREDEF_TYPE_AUTO_DEDUCT:
6104 T = Context.getAutoDeductType();
6105 break;
6106
6107 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6108 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 break;
6110
6111 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6112 T = Context.ARCUnbridgedCastTy;
6113 break;
6114
Guy Benyei11169dd2012-12-18 14:30:41 +00006115 case PREDEF_TYPE_BUILTIN_FN:
6116 T = Context.BuiltinFnTy;
6117 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006118
6119 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6120 T = Context.OMPArraySectionTy;
6121 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 }
6123
6124 assert(!T.isNull() && "Unknown predefined type");
6125 return T.withFastQualifiers(FastQuals);
6126 }
6127
6128 Index -= NUM_PREDEF_TYPE_IDS;
6129 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6130 if (TypesLoaded[Index].isNull()) {
6131 TypesLoaded[Index] = readTypeRecord(Index);
6132 if (TypesLoaded[Index].isNull())
6133 return QualType();
6134
6135 TypesLoaded[Index]->setFromAST();
6136 if (DeserializationListener)
6137 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6138 TypesLoaded[Index]);
6139 }
6140
6141 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6142}
6143
6144QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6145 return GetType(getGlobalTypeID(F, LocalID));
6146}
6147
6148serialization::TypeID
6149ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6150 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6151 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6152
6153 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6154 return LocalID;
6155
6156 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6157 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6158 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6159
6160 unsigned GlobalIndex = LocalIndex + I->second;
6161 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6162}
6163
6164TemplateArgumentLocInfo
6165ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6166 TemplateArgument::ArgKind Kind,
6167 const RecordData &Record,
6168 unsigned &Index) {
6169 switch (Kind) {
6170 case TemplateArgument::Expression:
6171 return ReadExpr(F);
6172 case TemplateArgument::Type:
6173 return GetTypeSourceInfo(F, Record, Index);
6174 case TemplateArgument::Template: {
6175 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6176 Index);
6177 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6178 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6179 SourceLocation());
6180 }
6181 case TemplateArgument::TemplateExpansion: {
6182 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6183 Index);
6184 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6185 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6186 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6187 EllipsisLoc);
6188 }
6189 case TemplateArgument::Null:
6190 case TemplateArgument::Integral:
6191 case TemplateArgument::Declaration:
6192 case TemplateArgument::NullPtr:
6193 case TemplateArgument::Pack:
6194 // FIXME: Is this right?
6195 return TemplateArgumentLocInfo();
6196 }
6197 llvm_unreachable("unexpected template argument loc");
6198}
6199
6200TemplateArgumentLoc
6201ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6202 const RecordData &Record, unsigned &Index) {
6203 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6204
6205 if (Arg.getKind() == TemplateArgument::Expression) {
6206 if (Record[Index++]) // bool InfoHasSameExpr.
6207 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6208 }
6209 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6210 Record, Index));
6211}
6212
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006213const ASTTemplateArgumentListInfo*
6214ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6215 const RecordData &Record,
6216 unsigned &Index) {
6217 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6218 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6219 unsigned NumArgsAsWritten = Record[Index++];
6220 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6221 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6222 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6223 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6224}
6225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6227 return GetDecl(ID);
6228}
6229
Richard Smith50895422015-01-31 03:04:55 +00006230template<typename TemplateSpecializationDecl>
6231static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6232 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6233 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6234}
6235
Richard Smith053f6c62014-05-16 23:01:30 +00006236void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006237 if (NumCurrentElementsDeserializing) {
6238 // We arrange to not care about the complete redeclaration chain while we're
6239 // deserializing. Just remember that the AST has marked this one as complete
6240 // but that it's not actually complete yet, so we know we still need to
6241 // complete it later.
6242 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6243 return;
6244 }
6245
Richard Smith053f6c62014-05-16 23:01:30 +00006246 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6247
Richard Smith053f6c62014-05-16 23:01:30 +00006248 // If this is a named declaration, complete it by looking it up
6249 // within its context.
6250 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006251 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006252 // all mergeable entities within it.
6253 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6254 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6255 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006256 if (!getContext().getLangOpts().CPlusPlus &&
6257 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006258 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006259 // the identifier instead. (For C++ modules, we don't store decls
6260 // in the serialized identifier table, so we do the lookup in the TU.)
6261 auto *II = Name.getAsIdentifierInfo();
6262 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006263 if (II->isOutOfDate())
6264 updateOutOfDateIdentifier(*II);
6265 } else
6266 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006267 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006268 // Find all declarations of this kind from the relevant context.
6269 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6270 auto *DC = cast<DeclContext>(DCDecl);
6271 SmallVector<Decl*, 8> Decls;
6272 FindExternalLexicalDecls(
6273 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6274 }
Richard Smith053f6c62014-05-16 23:01:30 +00006275 }
6276 }
Richard Smith50895422015-01-31 03:04:55 +00006277
6278 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6279 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6280 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6281 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6282 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6283 if (auto *Template = FD->getPrimaryTemplate())
6284 Template->LoadLazySpecializations();
6285 }
Richard Smith053f6c62014-05-16 23:01:30 +00006286}
6287
Richard Smithc2bb8182015-03-24 06:36:48 +00006288uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6289 const RecordData &Record,
6290 unsigned &Idx) {
6291 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6292 Error("malformed AST file: missing C++ ctor initializers");
6293 return 0;
6294 }
6295
6296 unsigned LocalID = Record[Idx++];
6297 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6298}
6299
6300CXXCtorInitializer **
6301ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6302 RecordLocation Loc = getLocalBitOffset(Offset);
6303 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6304 SavedStreamPosition SavedPosition(Cursor);
6305 Cursor.JumpToBit(Loc.Offset);
6306 ReadingKindTracker ReadingKind(Read_Decl, *this);
6307
6308 RecordData Record;
6309 unsigned Code = Cursor.ReadCode();
6310 unsigned RecCode = Cursor.readRecord(Code, Record);
6311 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6312 Error("malformed AST file: missing C++ ctor initializers");
6313 return nullptr;
6314 }
6315
6316 unsigned Idx = 0;
6317 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6318}
6319
Richard Smithcd45dbc2014-04-19 03:48:30 +00006320uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6321 const RecordData &Record,
6322 unsigned &Idx) {
6323 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6324 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006326 }
6327
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 unsigned LocalID = Record[Idx++];
6329 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6330}
6331
6332CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6333 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006334 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 SavedStreamPosition SavedPosition(Cursor);
6336 Cursor.JumpToBit(Loc.Offset);
6337 ReadingKindTracker ReadingKind(Read_Decl, *this);
6338 RecordData Record;
6339 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006340 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006342 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006343 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 }
6345
6346 unsigned Idx = 0;
6347 unsigned NumBases = Record[Idx++];
6348 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6349 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6350 for (unsigned I = 0; I != NumBases; ++I)
6351 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6352 return Bases;
6353}
6354
6355serialization::DeclID
6356ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6357 if (LocalID < NUM_PREDEF_DECL_IDS)
6358 return LocalID;
6359
6360 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6361 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6362 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6363
6364 return LocalID + I->second;
6365}
6366
6367bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6368 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006369 // Predefined decls aren't from any module.
6370 if (ID < NUM_PREDEF_DECL_IDS)
6371 return false;
6372
Richard Smithbcda1a92015-07-12 23:51:20 +00006373 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6374 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006375}
6376
Douglas Gregor9f782892013-01-21 15:25:38 +00006377ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006378 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006379 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6381 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6382 return I->second;
6383}
6384
6385SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6386 if (ID < NUM_PREDEF_DECL_IDS)
6387 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006388
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6390
6391 if (Index > DeclsLoaded.size()) {
6392 Error("declaration ID out-of-range for AST file");
6393 return SourceLocation();
6394 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006395
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 if (Decl *D = DeclsLoaded[Index])
6397 return D->getLocation();
6398
6399 unsigned RawLocation = 0;
6400 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6401 return ReadSourceLocation(*Rec.F, RawLocation);
6402}
6403
Richard Smithfe620d22015-03-05 23:24:12 +00006404static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6405 switch (ID) {
6406 case PREDEF_DECL_NULL_ID:
6407 return nullptr;
6408
6409 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6410 return Context.getTranslationUnitDecl();
6411
6412 case PREDEF_DECL_OBJC_ID_ID:
6413 return Context.getObjCIdDecl();
6414
6415 case PREDEF_DECL_OBJC_SEL_ID:
6416 return Context.getObjCSelDecl();
6417
6418 case PREDEF_DECL_OBJC_CLASS_ID:
6419 return Context.getObjCClassDecl();
6420
6421 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6422 return Context.getObjCProtocolDecl();
6423
6424 case PREDEF_DECL_INT_128_ID:
6425 return Context.getInt128Decl();
6426
6427 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6428 return Context.getUInt128Decl();
6429
6430 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6431 return Context.getObjCInstanceTypeDecl();
6432
6433 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6434 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006435
Richard Smith9b88a4c2015-07-27 05:40:23 +00006436 case PREDEF_DECL_VA_LIST_TAG:
6437 return Context.getVaListTagDecl();
6438
Charles Davisc7d5c942015-09-17 20:55:33 +00006439 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6440 return Context.getBuiltinMSVaListDecl();
6441
Richard Smithf19e1272015-03-07 00:04:49 +00006442 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6443 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006444
6445 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6446 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006447
6448 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6449 return Context.getCFConstantStringDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006450 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006451 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006452}
6453
Richard Smithcd45dbc2014-04-19 03:48:30 +00006454Decl *ASTReader::GetExistingDecl(DeclID ID) {
6455 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006456 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6457 if (D) {
6458 // Track that we have merged the declaration with ID \p ID into the
6459 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006460 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006461 if (Merged.empty())
6462 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 }
Richard Smithfe620d22015-03-05 23:24:12 +00006464 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006466
Guy Benyei11169dd2012-12-18 14:30:41 +00006467 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6468
6469 if (Index >= DeclsLoaded.size()) {
6470 assert(0 && "declaration ID out-of-range for AST file");
6471 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006472 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006473 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006474
6475 return DeclsLoaded[Index];
6476}
6477
6478Decl *ASTReader::GetDecl(DeclID ID) {
6479 if (ID < NUM_PREDEF_DECL_IDS)
6480 return GetExistingDecl(ID);
6481
6482 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6483
6484 if (Index >= DeclsLoaded.size()) {
6485 assert(0 && "declaration ID out-of-range for AST file");
6486 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006487 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006488 }
6489
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 if (!DeclsLoaded[Index]) {
6491 ReadDeclRecord(ID);
6492 if (DeserializationListener)
6493 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6494 }
6495
6496 return DeclsLoaded[Index];
6497}
6498
6499DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6500 DeclID GlobalID) {
6501 if (GlobalID < NUM_PREDEF_DECL_IDS)
6502 return GlobalID;
6503
6504 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6505 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6506 ModuleFile *Owner = I->second;
6507
6508 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6509 = M.GlobalToLocalDeclIDs.find(Owner);
6510 if (Pos == M.GlobalToLocalDeclIDs.end())
6511 return 0;
6512
6513 return GlobalID - Owner->BaseDeclID + Pos->second;
6514}
6515
6516serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6517 const RecordData &Record,
6518 unsigned &Idx) {
6519 if (Idx >= Record.size()) {
6520 Error("Corrupted AST file");
6521 return 0;
6522 }
6523
6524 return getGlobalDeclID(F, Record[Idx++]);
6525}
6526
6527/// \brief Resolve the offset of a statement into a statement.
6528///
6529/// This operation will read a new statement from the external
6530/// source each time it is called, and is meant to be used via a
6531/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6532Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6533 // Switch case IDs are per Decl.
6534 ClearSwitchCaseIDs();
6535
6536 // Offset here is a global offset across the entire chain.
6537 RecordLocation Loc = getLocalBitOffset(Offset);
6538 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6539 return ReadStmtFromStream(*Loc.F);
6540}
6541
Richard Smith3cb15722015-08-05 22:41:45 +00006542void ASTReader::FindExternalLexicalDecls(
6543 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6544 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006545 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6546
Richard Smith9ccdd932015-08-06 22:14:12 +00006547 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006548 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6549 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6550 auto K = (Decl::Kind)+LexicalDecls[I];
6551 if (!IsKindWeWant(K))
6552 continue;
6553
6554 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6555
6556 // Don't add predefined declarations to the lexical context more
6557 // than once.
6558 if (ID < NUM_PREDEF_DECL_IDS) {
6559 if (PredefsVisited[ID])
6560 continue;
6561
6562 PredefsVisited[ID] = true;
6563 }
6564
6565 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006566 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006567 if (!DC->isDeclInLexicalTraversal(D))
6568 Decls.push_back(D);
6569 }
6570 }
6571 };
6572
6573 if (isa<TranslationUnitDecl>(DC)) {
6574 for (auto Lexical : TULexicalDecls)
6575 Visit(Lexical.first, Lexical.second);
6576 } else {
6577 auto I = LexicalDecls.find(DC);
6578 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006579 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006580 }
6581
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006583}
6584
6585namespace {
6586
6587class DeclIDComp {
6588 ASTReader &Reader;
6589 ModuleFile &Mod;
6590
6591public:
6592 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6593
6594 bool operator()(LocalDeclID L, LocalDeclID R) const {
6595 SourceLocation LHS = getLocation(L);
6596 SourceLocation RHS = getLocation(R);
6597 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6598 }
6599
6600 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6601 SourceLocation RHS = getLocation(R);
6602 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6603 }
6604
6605 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6606 SourceLocation LHS = getLocation(L);
6607 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6608 }
6609
6610 SourceLocation getLocation(LocalDeclID ID) const {
6611 return Reader.getSourceManager().getFileLoc(
6612 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6613 }
6614};
6615
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006616}
Guy Benyei11169dd2012-12-18 14:30:41 +00006617
6618void ASTReader::FindFileRegionDecls(FileID File,
6619 unsigned Offset, unsigned Length,
6620 SmallVectorImpl<Decl *> &Decls) {
6621 SourceManager &SM = getSourceManager();
6622
6623 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6624 if (I == FileDeclIDs.end())
6625 return;
6626
6627 FileDeclsInfo &DInfo = I->second;
6628 if (DInfo.Decls.empty())
6629 return;
6630
6631 SourceLocation
6632 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6633 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6634
6635 DeclIDComp DIDComp(*this, *DInfo.Mod);
6636 ArrayRef<serialization::LocalDeclID>::iterator
6637 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6638 BeginLoc, DIDComp);
6639 if (BeginIt != DInfo.Decls.begin())
6640 --BeginIt;
6641
6642 // If we are pointing at a top-level decl inside an objc container, we need
6643 // to backtrack until we find it otherwise we will fail to report that the
6644 // region overlaps with an objc container.
6645 while (BeginIt != DInfo.Decls.begin() &&
6646 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6647 ->isTopLevelDeclInObjCContainer())
6648 --BeginIt;
6649
6650 ArrayRef<serialization::LocalDeclID>::iterator
6651 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6652 EndLoc, DIDComp);
6653 if (EndIt != DInfo.Decls.end())
6654 ++EndIt;
6655
6656 for (ArrayRef<serialization::LocalDeclID>::iterator
6657 DIt = BeginIt; DIt != EndIt; ++DIt)
6658 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6659}
6660
Richard Smith9ce12e32013-02-07 03:30:24 +00006661bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006662ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6663 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006664 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006665 "DeclContext has no visible decls in storage");
6666 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006667 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006668
Richard Smithd88a7f12015-09-01 20:35:42 +00006669 auto It = Lookups.find(DC);
6670 if (It == Lookups.end())
6671 return false;
6672
Richard Smith8c913ec2014-08-14 02:21:01 +00006673 Deserializing LookupResults(this);
6674
Richard Smithd88a7f12015-09-01 20:35:42 +00006675 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006676 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006677 for (DeclID ID : It->second.Table.find(Name)) {
6678 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6679 if (ND->getDeclName() == Name)
6680 Decls.push_back(ND);
6681 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006682
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 ++NumVisibleDeclContextsRead;
6684 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006685 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006686}
6687
Guy Benyei11169dd2012-12-18 14:30:41 +00006688void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6689 if (!DC->hasExternalVisibleStorage())
6690 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006691
6692 auto It = Lookups.find(DC);
6693 assert(It != Lookups.end() &&
6694 "have external visible storage but no lookup tables");
6695
Craig Topper79be4cd2013-07-05 04:33:53 +00006696 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006697
Richard Smithd88a7f12015-09-01 20:35:42 +00006698 for (DeclID ID : It->second.Table.findAll()) {
6699 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6700 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006701 }
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 ++NumVisibleDeclContextsRead;
6704
Craig Topper79be4cd2013-07-05 04:33:53 +00006705 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6707 }
6708 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6709}
6710
Richard Smithd88a7f12015-09-01 20:35:42 +00006711const serialization::reader::DeclContextLookupTable *
6712ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6713 auto I = Lookups.find(Primary);
6714 return I == Lookups.end() ? nullptr : &I->second;
6715}
6716
Guy Benyei11169dd2012-12-18 14:30:41 +00006717/// \brief Under non-PCH compilation the consumer receives the objc methods
6718/// before receiving the implementation, and codegen depends on this.
6719/// We simulate this by deserializing and passing to consumer the methods of the
6720/// implementation before passing the deserialized implementation decl.
6721static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6722 ASTConsumer *Consumer) {
6723 assert(ImplD && Consumer);
6724
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006725 for (auto *I : ImplD->methods())
6726 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006727
6728 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6729}
6730
6731void ASTReader::PassInterestingDeclsToConsumer() {
6732 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006733
6734 if (PassingDeclsToConsumer)
6735 return;
6736
6737 // Guard variable to avoid recursively redoing the process of passing
6738 // decls to consumer.
6739 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6740 true);
6741
Richard Smith9e2341d2015-03-23 03:25:59 +00006742 // Ensure that we've loaded all potentially-interesting declarations
6743 // that need to be eagerly loaded.
6744 for (auto ID : EagerlyDeserializedDecls)
6745 GetDecl(ID);
6746 EagerlyDeserializedDecls.clear();
6747
Guy Benyei11169dd2012-12-18 14:30:41 +00006748 while (!InterestingDecls.empty()) {
6749 Decl *D = InterestingDecls.front();
6750 InterestingDecls.pop_front();
6751
6752 PassInterestingDeclToConsumer(D);
6753 }
6754}
6755
6756void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6757 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6758 PassObjCImplDeclToConsumer(ImplD, Consumer);
6759 else
6760 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6761}
6762
6763void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6764 this->Consumer = Consumer;
6765
Richard Smith9e2341d2015-03-23 03:25:59 +00006766 if (Consumer)
6767 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006768
6769 if (DeserializationListener)
6770 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006771}
6772
6773void ASTReader::PrintStats() {
6774 std::fprintf(stderr, "*** AST File Statistics:\n");
6775
6776 unsigned NumTypesLoaded
6777 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6778 QualType());
6779 unsigned NumDeclsLoaded
6780 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006781 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 unsigned NumIdentifiersLoaded
6783 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6784 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006785 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 unsigned NumMacrosLoaded
6787 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6788 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006789 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006790 unsigned NumSelectorsLoaded
6791 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6792 SelectorsLoaded.end(),
6793 Selector());
6794
6795 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6796 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6797 NumSLocEntriesRead, TotalNumSLocEntries,
6798 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6799 if (!TypesLoaded.empty())
6800 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6801 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6802 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6803 if (!DeclsLoaded.empty())
6804 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6805 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6806 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6807 if (!IdentifiersLoaded.empty())
6808 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6809 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6810 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6811 if (!MacrosLoaded.empty())
6812 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6813 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6814 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6815 if (!SelectorsLoaded.empty())
6816 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6817 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6818 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6819 if (TotalNumStatements)
6820 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6821 NumStatementsRead, TotalNumStatements,
6822 ((float)NumStatementsRead/TotalNumStatements * 100));
6823 if (TotalNumMacros)
6824 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6825 NumMacrosRead, TotalNumMacros,
6826 ((float)NumMacrosRead/TotalNumMacros * 100));
6827 if (TotalLexicalDeclContexts)
6828 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6829 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6830 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6831 * 100));
6832 if (TotalVisibleDeclContexts)
6833 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6834 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6835 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6836 * 100));
6837 if (TotalNumMethodPoolEntries) {
6838 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6839 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6840 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6841 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006843 if (NumMethodPoolLookups) {
6844 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6845 NumMethodPoolHits, NumMethodPoolLookups,
6846 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6847 }
6848 if (NumMethodPoolTableLookups) {
6849 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6850 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6851 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6852 * 100.0));
6853 }
6854
Douglas Gregor00a50f72013-01-25 00:38:33 +00006855 if (NumIdentifierLookupHits) {
6856 std::fprintf(stderr,
6857 " %u / %u identifier table lookups succeeded (%f%%)\n",
6858 NumIdentifierLookupHits, NumIdentifierLookups,
6859 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6860 }
6861
Douglas Gregore060e572013-01-25 01:03:03 +00006862 if (GlobalIndex) {
6863 std::fprintf(stderr, "\n");
6864 GlobalIndex->printStats();
6865 }
6866
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 std::fprintf(stderr, "\n");
6868 dump();
6869 std::fprintf(stderr, "\n");
6870}
6871
6872template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6873static void
6874dumpModuleIDMap(StringRef Name,
6875 const ContinuousRangeMap<Key, ModuleFile *,
6876 InitialCapacity> &Map) {
6877 if (Map.begin() == Map.end())
6878 return;
6879
6880 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6881 llvm::errs() << Name << ":\n";
6882 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6883 I != IEnd; ++I) {
6884 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6885 << "\n";
6886 }
6887}
6888
Yaron Kerencdae9412016-01-29 19:38:18 +00006889LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6891 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6892 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6893 dumpModuleIDMap("Global type map", GlobalTypeMap);
6894 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6895 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6896 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6897 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6898 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6899 dumpModuleIDMap("Global preprocessed entity map",
6900 GlobalPreprocessedEntityMap);
6901
6902 llvm::errs() << "\n*** PCH/Modules Loaded:";
6903 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6904 MEnd = ModuleMgr.end();
6905 M != MEnd; ++M)
6906 (*M)->dump();
6907}
6908
6909/// Return the amount of memory used by memory buffers, breaking down
6910/// by heap-backed versus mmap'ed memory.
6911void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6912 for (ModuleConstIterator I = ModuleMgr.begin(),
6913 E = ModuleMgr.end(); I != E; ++I) {
6914 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6915 size_t bytes = buf->getBufferSize();
6916 switch (buf->getBufferKind()) {
6917 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6918 sizes.malloc_bytes += bytes;
6919 break;
6920 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6921 sizes.mmap_bytes += bytes;
6922 break;
6923 }
6924 }
6925 }
6926}
6927
6928void ASTReader::InitializeSema(Sema &S) {
6929 SemaObj = &S;
6930 S.addExternalSource(this);
6931
6932 // Makes sure any declarations that were deserialized "too early"
6933 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006934 for (uint64_t ID : PreloadedDeclIDs) {
6935 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6936 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006938 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006939
Richard Smith3d8e97e2013-10-18 06:54:39 +00006940 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 if (!FPPragmaOptions.empty()) {
6942 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6943 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6944 }
6945
Richard Smith3d8e97e2013-10-18 06:54:39 +00006946 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 if (!OpenCLExtensions.empty()) {
6948 unsigned I = 0;
6949#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6950#include "clang/Basic/OpenCLExtensions.def"
6951
6952 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6953 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006954
6955 UpdateSema();
6956}
6957
6958void ASTReader::UpdateSema() {
6959 assert(SemaObj && "no Sema to update");
6960
6961 // Load the offsets of the declarations that Sema references.
6962 // They will be lazily deserialized when needed.
6963 if (!SemaDeclRefs.empty()) {
6964 assert(SemaDeclRefs.size() % 2 == 0);
6965 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6966 if (!SemaObj->StdNamespace)
6967 SemaObj->StdNamespace = SemaDeclRefs[I];
6968 if (!SemaObj->StdBadAlloc)
6969 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6970 }
6971 SemaDeclRefs.clear();
6972 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006973
6974 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6975 // encountered the pragma in the source.
6976 if(OptimizeOffPragmaLocation.isValid())
6977 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006978}
6979
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006980IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 // Note that we are loading an identifier.
6982 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006983
Douglas Gregor7211ac12013-01-25 23:32:03 +00006984 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006985 NumIdentifierLookups,
6986 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006987
6988 // We don't need to do identifier table lookups in C++ modules (we preload
6989 // all interesting declarations, and don't need to use the scope for name
6990 // lookups). Perform the lookup in PCH files, though, since we don't build
6991 // a complete initial identifier table if we're carrying on from a PCH.
6992 if (Context.getLangOpts().CPlusPlus) {
6993 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006994 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006995 break;
6996 } else {
6997 // If there is a global index, look there first to determine which modules
6998 // provably do not have any results for this identifier.
6999 GlobalModuleIndex::HitSet Hits;
7000 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7001 if (!loadGlobalIndex()) {
7002 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7003 HitsPtr = &Hits;
7004 }
7005 }
7006
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007007 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007008 }
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 IdentifierInfo *II = Visitor.getIdentifierInfo();
7011 markIdentifierUpToDate(II);
7012 return II;
7013}
7014
7015namespace clang {
7016 /// \brief An identifier-lookup iterator that enumerates all of the
7017 /// identifiers stored within a set of AST files.
7018 class ASTIdentifierIterator : public IdentifierIterator {
7019 /// \brief The AST reader whose identifiers are being enumerated.
7020 const ASTReader &Reader;
7021
7022 /// \brief The current index into the chain of AST files stored in
7023 /// the AST reader.
7024 unsigned Index;
7025
7026 /// \brief The current position within the identifier lookup table
7027 /// of the current AST file.
7028 ASTIdentifierLookupTable::key_iterator Current;
7029
7030 /// \brief The end position within the identifier lookup table of
7031 /// the current AST file.
7032 ASTIdentifierLookupTable::key_iterator End;
7033
7034 public:
7035 explicit ASTIdentifierIterator(const ASTReader &Reader);
7036
Craig Topper3e89dfe2014-03-13 02:13:41 +00007037 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007039}
Guy Benyei11169dd2012-12-18 14:30:41 +00007040
7041ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7042 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7043 ASTIdentifierLookupTable *IdTable
7044 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7045 Current = IdTable->key_begin();
7046 End = IdTable->key_end();
7047}
7048
7049StringRef ASTIdentifierIterator::Next() {
7050 while (Current == End) {
7051 // If we have exhausted all of our AST files, we're done.
7052 if (Index == 0)
7053 return StringRef();
7054
7055 --Index;
7056 ASTIdentifierLookupTable *IdTable
7057 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7058 IdentifierLookupTable;
7059 Current = IdTable->key_begin();
7060 End = IdTable->key_end();
7061 }
7062
7063 // We have any identifiers remaining in the current AST file; return
7064 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007065 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007067 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007068}
7069
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007070IdentifierIterator *ASTReader::getIdentifiers() {
7071 if (!loadGlobalIndex())
7072 return GlobalIndex->createIdentifierIterator();
7073
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 return new ASTIdentifierIterator(*this);
7075}
7076
7077namespace clang { namespace serialization {
7078 class ReadMethodPoolVisitor {
7079 ASTReader &Reader;
7080 Selector Sel;
7081 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007082 unsigned InstanceBits;
7083 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007084 bool InstanceHasMoreThanOneDecl;
7085 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007086 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7087 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088
7089 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007090 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007092 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007093 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7094 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007095
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007096 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 if (!M.SelectorLookupTable)
7098 return false;
7099
7100 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007101 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 return true;
7103
Richard Smithbdf2d932015-07-30 03:37:16 +00007104 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 ASTSelectorLookupTable *PoolTable
7106 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007107 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 if (Pos == PoolTable->end())
7109 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007110
Richard Smithbdf2d932015-07-30 03:37:16 +00007111 ++Reader.NumMethodPoolTableHits;
7112 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007113 // FIXME: Not quite happy with the statistics here. We probably should
7114 // disable this tracking when called via LoadSelector.
7115 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007116 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007118 if (Reader.DeserializationListener)
7119 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007120
Richard Smithbdf2d932015-07-30 03:37:16 +00007121 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7122 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7123 InstanceBits = Data.InstanceBits;
7124 FactoryBits = Data.FactoryBits;
7125 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7126 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 return true;
7128 }
7129
7130 /// \brief Retrieve the instance methods found by this visitor.
7131 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7132 return InstanceMethods;
7133 }
7134
7135 /// \brief Retrieve the instance methods found by this visitor.
7136 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7137 return FactoryMethods;
7138 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007139
7140 unsigned getInstanceBits() const { return InstanceBits; }
7141 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007142 bool instanceHasMoreThanOneDecl() const {
7143 return InstanceHasMoreThanOneDecl;
7144 }
7145 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007147} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007148
7149/// \brief Add the given set of methods to the method list.
7150static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7151 ObjCMethodList &List) {
7152 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7153 S.addMethodToGlobalList(&List, Methods[I]);
7154 }
7155}
7156
7157void ASTReader::ReadMethodPool(Selector Sel) {
7158 // Get the selector generation and update it to the current generation.
7159 unsigned &Generation = SelectorGeneration[Sel];
7160 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007161 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007162
7163 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007164 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007166 ModuleMgr.visit(Visitor);
7167
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007169 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007171
7172 ++NumMethodPoolHits;
7173
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 if (!getSema())
7175 return;
7176
7177 Sema &S = *getSema();
7178 Sema::GlobalMethodPool::iterator Pos
7179 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007180
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007181 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007182 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007183 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007184 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007185
7186 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7187 // when building a module we keep every method individually and may need to
7188 // update hasMoreThanOneDecl as we add the methods.
7189 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7190 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007191}
7192
7193void ASTReader::ReadKnownNamespaces(
7194 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7195 Namespaces.clear();
7196
7197 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7198 if (NamespaceDecl *Namespace
7199 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7200 Namespaces.push_back(Namespace);
7201 }
7202}
7203
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007204void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007205 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007206 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7207 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007208 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007209 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007210 Undefined.insert(std::make_pair(D, Loc));
7211 }
7212}
Nick Lewycky8334af82013-01-26 00:35:08 +00007213
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007214void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7215 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7216 Exprs) {
7217 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7218 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7219 uint64_t Count = DelayedDeleteExprs[Idx++];
7220 for (uint64_t C = 0; C < Count; ++C) {
7221 SourceLocation DeleteLoc =
7222 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7223 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7224 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7225 }
7226 }
7227}
7228
Guy Benyei11169dd2012-12-18 14:30:41 +00007229void ASTReader::ReadTentativeDefinitions(
7230 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7231 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7232 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7233 if (Var)
7234 TentativeDefs.push_back(Var);
7235 }
7236 TentativeDefinitions.clear();
7237}
7238
7239void ASTReader::ReadUnusedFileScopedDecls(
7240 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7241 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7242 DeclaratorDecl *D
7243 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7244 if (D)
7245 Decls.push_back(D);
7246 }
7247 UnusedFileScopedDecls.clear();
7248}
7249
7250void ASTReader::ReadDelegatingConstructors(
7251 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7252 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7253 CXXConstructorDecl *D
7254 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7255 if (D)
7256 Decls.push_back(D);
7257 }
7258 DelegatingCtorDecls.clear();
7259}
7260
7261void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7262 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7263 TypedefNameDecl *D
7264 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7265 if (D)
7266 Decls.push_back(D);
7267 }
7268 ExtVectorDecls.clear();
7269}
7270
Nico Weber72889432014-09-06 01:25:55 +00007271void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7272 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7273 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7274 ++I) {
7275 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7276 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7277 if (D)
7278 Decls.insert(D);
7279 }
7280 UnusedLocalTypedefNameCandidates.clear();
7281}
7282
Guy Benyei11169dd2012-12-18 14:30:41 +00007283void ASTReader::ReadReferencedSelectors(
7284 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7285 if (ReferencedSelectorsData.empty())
7286 return;
7287
7288 // If there are @selector references added them to its pool. This is for
7289 // implementation of -Wselector.
7290 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7291 unsigned I = 0;
7292 while (I < DataSize) {
7293 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7294 SourceLocation SelLoc
7295 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7296 Sels.push_back(std::make_pair(Sel, SelLoc));
7297 }
7298 ReferencedSelectorsData.clear();
7299}
7300
7301void ASTReader::ReadWeakUndeclaredIdentifiers(
7302 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7303 if (WeakUndeclaredIdentifiers.empty())
7304 return;
7305
7306 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7307 IdentifierInfo *WeakId
7308 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7309 IdentifierInfo *AliasId
7310 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7311 SourceLocation Loc
7312 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7313 bool Used = WeakUndeclaredIdentifiers[I++];
7314 WeakInfo WI(AliasId, Loc);
7315 WI.setUsed(Used);
7316 WeakIDs.push_back(std::make_pair(WeakId, WI));
7317 }
7318 WeakUndeclaredIdentifiers.clear();
7319}
7320
7321void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7322 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7323 ExternalVTableUse VT;
7324 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7325 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7326 VT.DefinitionRequired = VTableUses[Idx++];
7327 VTables.push_back(VT);
7328 }
7329
7330 VTableUses.clear();
7331}
7332
7333void ASTReader::ReadPendingInstantiations(
7334 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7335 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7336 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7337 SourceLocation Loc
7338 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7339
7340 Pending.push_back(std::make_pair(D, Loc));
7341 }
7342 PendingInstantiations.clear();
7343}
7344
Richard Smithe40f2ba2013-08-07 21:41:30 +00007345void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007346 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007347 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7348 /* In loop */) {
7349 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7350
7351 LateParsedTemplate *LT = new LateParsedTemplate;
7352 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7353
7354 ModuleFile *F = getOwningModuleFile(LT->D);
7355 assert(F && "No module");
7356
7357 unsigned TokN = LateParsedTemplates[Idx++];
7358 LT->Toks.reserve(TokN);
7359 for (unsigned T = 0; T < TokN; ++T)
7360 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7361
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007362 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007363 }
7364
7365 LateParsedTemplates.clear();
7366}
7367
Guy Benyei11169dd2012-12-18 14:30:41 +00007368void ASTReader::LoadSelector(Selector Sel) {
7369 // It would be complicated to avoid reading the methods anyway. So don't.
7370 ReadMethodPool(Sel);
7371}
7372
7373void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7374 assert(ID && "Non-zero identifier ID required");
7375 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7376 IdentifiersLoaded[ID - 1] = II;
7377 if (DeserializationListener)
7378 DeserializationListener->IdentifierRead(ID, II);
7379}
7380
7381/// \brief Set the globally-visible declarations associated with the given
7382/// identifier.
7383///
7384/// If the AST reader is currently in a state where the given declaration IDs
7385/// cannot safely be resolved, they are queued until it is safe to resolve
7386/// them.
7387///
7388/// \param II an IdentifierInfo that refers to one or more globally-visible
7389/// declarations.
7390///
7391/// \param DeclIDs the set of declaration IDs with the name @p II that are
7392/// visible at global scope.
7393///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007394/// \param Decls if non-null, this vector will be populated with the set of
7395/// deserialized declarations. These declarations will not be pushed into
7396/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007397void
7398ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7399 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007400 SmallVectorImpl<Decl *> *Decls) {
7401 if (NumCurrentElementsDeserializing && !Decls) {
7402 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007403 return;
7404 }
7405
7406 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007407 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 // Queue this declaration so that it will be added to the
7409 // translation unit scope and identifier's declaration chain
7410 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007411 PreloadedDeclIDs.push_back(DeclIDs[I]);
7412 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007414
7415 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7416
7417 // If we're simply supposed to record the declarations, do so now.
7418 if (Decls) {
7419 Decls->push_back(D);
7420 continue;
7421 }
7422
7423 // Introduce this declaration into the translation-unit scope
7424 // and add it to the declaration chain for this identifier, so
7425 // that (unqualified) name lookup will find it.
7426 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007427 }
7428}
7429
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007430IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007432 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007433
7434 if (IdentifiersLoaded.empty()) {
7435 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007436 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 }
7438
7439 ID -= 1;
7440 if (!IdentifiersLoaded[ID]) {
7441 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7442 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7443 ModuleFile *M = I->second;
7444 unsigned Index = ID - M->BaseIdentifierID;
7445 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7446
7447 // All of the strings in the AST file are preceded by a 16-bit length.
7448 // Extract that 16-bit length to avoid having to execute strlen().
7449 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7450 // unsigned integers. This is important to avoid integer overflow when
7451 // we cast them to 'unsigned'.
7452 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7453 unsigned StrLen = (((unsigned) StrLenPtr[0])
7454 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007455 IdentifiersLoaded[ID]
7456 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 if (DeserializationListener)
7458 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7459 }
7460
7461 return IdentifiersLoaded[ID];
7462}
7463
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007464IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7465 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007466}
7467
7468IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7469 if (LocalID < NUM_PREDEF_IDENT_IDS)
7470 return LocalID;
7471
7472 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7473 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7474 assert(I != M.IdentifierRemap.end()
7475 && "Invalid index into identifier index remap");
7476
7477 return LocalID + I->second;
7478}
7479
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007480MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007482 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
7484 if (MacrosLoaded.empty()) {
7485 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007486 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
7488
7489 ID -= NUM_PREDEF_MACRO_IDS;
7490 if (!MacrosLoaded[ID]) {
7491 GlobalMacroMapType::iterator I
7492 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7493 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7494 ModuleFile *M = I->second;
7495 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007496 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7497
7498 if (DeserializationListener)
7499 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7500 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007501 }
7502
7503 return MacrosLoaded[ID];
7504}
7505
7506MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7507 if (LocalID < NUM_PREDEF_MACRO_IDS)
7508 return LocalID;
7509
7510 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7511 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7512 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7513
7514 return LocalID + I->second;
7515}
7516
7517serialization::SubmoduleID
7518ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7519 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7520 return LocalID;
7521
7522 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7523 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7524 assert(I != M.SubmoduleRemap.end()
7525 && "Invalid index into submodule index remap");
7526
7527 return LocalID + I->second;
7528}
7529
7530Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7531 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7532 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007533 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007534 }
7535
7536 if (GlobalID > SubmodulesLoaded.size()) {
7537 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007538 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 }
7540
7541 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7542}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007543
7544Module *ASTReader::getModule(unsigned ID) {
7545 return getSubmodule(ID);
7546}
7547
Richard Smithd88a7f12015-09-01 20:35:42 +00007548ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7549 if (ID & 1) {
7550 // It's a module, look it up by submodule ID.
7551 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7552 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7553 } else {
7554 // It's a prefix (preamble, PCH, ...). Look it up by index.
7555 unsigned IndexFromEnd = ID >> 1;
7556 assert(IndexFromEnd && "got reference to unknown module file");
7557 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7558 }
7559}
7560
7561unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7562 if (!F)
7563 return 1;
7564
7565 // For a file representing a module, use the submodule ID of the top-level
7566 // module as the file ID. For any other kind of file, the number of such
7567 // files loaded beforehand will be the same on reload.
7568 // FIXME: Is this true even if we have an explicit module file and a PCH?
7569 if (F->isModule())
7570 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7571
7572 auto PCHModules = getModuleManager().pch_modules();
7573 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7574 assert(I != PCHModules.end() && "emitting reference to unknown file");
7575 return (I - PCHModules.end()) << 1;
7576}
7577
Adrian Prantl15bcf702015-06-30 17:39:43 +00007578llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7579ASTReader::getSourceDescriptor(unsigned ID) {
7580 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007581 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007582
7583 // If there is only a single PCH, return it instead.
7584 // Chained PCH are not suported.
7585 if (ModuleMgr.size() == 1) {
7586 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007587 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
7588 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir,
7589 MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007590 }
7591 return None;
7592}
7593
Guy Benyei11169dd2012-12-18 14:30:41 +00007594Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7595 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7596}
7597
7598Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7599 if (ID == 0)
7600 return Selector();
7601
7602 if (ID > SelectorsLoaded.size()) {
7603 Error("selector ID out of range in AST file");
7604 return Selector();
7605 }
7606
Craig Toppera13603a2014-05-22 05:54:18 +00007607 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 // Load this selector from the selector table.
7609 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7610 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7611 ModuleFile &M = *I->second;
7612 ASTSelectorLookupTrait Trait(*this, M);
7613 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7614 SelectorsLoaded[ID - 1] =
7615 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7616 if (DeserializationListener)
7617 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7618 }
7619
7620 return SelectorsLoaded[ID - 1];
7621}
7622
7623Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7624 return DecodeSelector(ID);
7625}
7626
7627uint32_t ASTReader::GetNumExternalSelectors() {
7628 // ID 0 (the null selector) is considered an external selector.
7629 return getTotalNumSelectors() + 1;
7630}
7631
7632serialization::SelectorID
7633ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7634 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7635 return LocalID;
7636
7637 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7638 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7639 assert(I != M.SelectorRemap.end()
7640 && "Invalid index into selector index remap");
7641
7642 return LocalID + I->second;
7643}
7644
7645DeclarationName
7646ASTReader::ReadDeclarationName(ModuleFile &F,
7647 const RecordData &Record, unsigned &Idx) {
7648 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7649 switch (Kind) {
7650 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007651 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007652
7653 case DeclarationName::ObjCZeroArgSelector:
7654 case DeclarationName::ObjCOneArgSelector:
7655 case DeclarationName::ObjCMultiArgSelector:
7656 return DeclarationName(ReadSelector(F, Record, Idx));
7657
7658 case DeclarationName::CXXConstructorName:
7659 return Context.DeclarationNames.getCXXConstructorName(
7660 Context.getCanonicalType(readType(F, Record, Idx)));
7661
7662 case DeclarationName::CXXDestructorName:
7663 return Context.DeclarationNames.getCXXDestructorName(
7664 Context.getCanonicalType(readType(F, Record, Idx)));
7665
7666 case DeclarationName::CXXConversionFunctionName:
7667 return Context.DeclarationNames.getCXXConversionFunctionName(
7668 Context.getCanonicalType(readType(F, Record, Idx)));
7669
7670 case DeclarationName::CXXOperatorName:
7671 return Context.DeclarationNames.getCXXOperatorName(
7672 (OverloadedOperatorKind)Record[Idx++]);
7673
7674 case DeclarationName::CXXLiteralOperatorName:
7675 return Context.DeclarationNames.getCXXLiteralOperatorName(
7676 GetIdentifierInfo(F, Record, Idx));
7677
7678 case DeclarationName::CXXUsingDirective:
7679 return DeclarationName::getUsingDirectiveName();
7680 }
7681
7682 llvm_unreachable("Invalid NameKind!");
7683}
7684
7685void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7686 DeclarationNameLoc &DNLoc,
7687 DeclarationName Name,
7688 const RecordData &Record, unsigned &Idx) {
7689 switch (Name.getNameKind()) {
7690 case DeclarationName::CXXConstructorName:
7691 case DeclarationName::CXXDestructorName:
7692 case DeclarationName::CXXConversionFunctionName:
7693 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7694 break;
7695
7696 case DeclarationName::CXXOperatorName:
7697 DNLoc.CXXOperatorName.BeginOpNameLoc
7698 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7699 DNLoc.CXXOperatorName.EndOpNameLoc
7700 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7701 break;
7702
7703 case DeclarationName::CXXLiteralOperatorName:
7704 DNLoc.CXXLiteralOperatorName.OpNameLoc
7705 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7706 break;
7707
7708 case DeclarationName::Identifier:
7709 case DeclarationName::ObjCZeroArgSelector:
7710 case DeclarationName::ObjCOneArgSelector:
7711 case DeclarationName::ObjCMultiArgSelector:
7712 case DeclarationName::CXXUsingDirective:
7713 break;
7714 }
7715}
7716
7717void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7718 DeclarationNameInfo &NameInfo,
7719 const RecordData &Record, unsigned &Idx) {
7720 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7721 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7722 DeclarationNameLoc DNLoc;
7723 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7724 NameInfo.setInfo(DNLoc);
7725}
7726
7727void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7728 const RecordData &Record, unsigned &Idx) {
7729 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7730 unsigned NumTPLists = Record[Idx++];
7731 Info.NumTemplParamLists = NumTPLists;
7732 if (NumTPLists) {
7733 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7734 for (unsigned i=0; i != NumTPLists; ++i)
7735 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7736 }
7737}
7738
7739TemplateName
7740ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7741 unsigned &Idx) {
7742 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7743 switch (Kind) {
7744 case TemplateName::Template:
7745 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7746
7747 case TemplateName::OverloadedTemplate: {
7748 unsigned size = Record[Idx++];
7749 UnresolvedSet<8> Decls;
7750 while (size--)
7751 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7752
7753 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7754 }
7755
7756 case TemplateName::QualifiedTemplate: {
7757 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7758 bool hasTemplKeyword = Record[Idx++];
7759 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7760 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7761 }
7762
7763 case TemplateName::DependentTemplate: {
7764 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7765 if (Record[Idx++]) // isIdentifier
7766 return Context.getDependentTemplateName(NNS,
7767 GetIdentifierInfo(F, Record,
7768 Idx));
7769 return Context.getDependentTemplateName(NNS,
7770 (OverloadedOperatorKind)Record[Idx++]);
7771 }
7772
7773 case TemplateName::SubstTemplateTemplateParm: {
7774 TemplateTemplateParmDecl *param
7775 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7776 if (!param) return TemplateName();
7777 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7778 return Context.getSubstTemplateTemplateParm(param, replacement);
7779 }
7780
7781 case TemplateName::SubstTemplateTemplateParmPack: {
7782 TemplateTemplateParmDecl *Param
7783 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7784 if (!Param)
7785 return TemplateName();
7786
7787 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7788 if (ArgPack.getKind() != TemplateArgument::Pack)
7789 return TemplateName();
7790
7791 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7792 }
7793 }
7794
7795 llvm_unreachable("Unhandled template name kind!");
7796}
7797
Richard Smith2bb3c342015-08-09 01:05:31 +00007798TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7799 const RecordData &Record,
7800 unsigned &Idx,
7801 bool Canonicalize) {
7802 if (Canonicalize) {
7803 // The caller wants a canonical template argument. Sometimes the AST only
7804 // wants template arguments in canonical form (particularly as the template
7805 // argument lists of template specializations) so ensure we preserve that
7806 // canonical form across serialization.
7807 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7808 return Context.getCanonicalTemplateArgument(Arg);
7809 }
7810
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7812 switch (Kind) {
7813 case TemplateArgument::Null:
7814 return TemplateArgument();
7815 case TemplateArgument::Type:
7816 return TemplateArgument(readType(F, Record, Idx));
7817 case TemplateArgument::Declaration: {
7818 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007819 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 }
7821 case TemplateArgument::NullPtr:
7822 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7823 case TemplateArgument::Integral: {
7824 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7825 QualType T = readType(F, Record, Idx);
7826 return TemplateArgument(Context, Value, T);
7827 }
7828 case TemplateArgument::Template:
7829 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7830 case TemplateArgument::TemplateExpansion: {
7831 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007832 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007833 if (unsigned NumExpansions = Record[Idx++])
7834 NumTemplateExpansions = NumExpansions - 1;
7835 return TemplateArgument(Name, NumTemplateExpansions);
7836 }
7837 case TemplateArgument::Expression:
7838 return TemplateArgument(ReadExpr(F));
7839 case TemplateArgument::Pack: {
7840 unsigned NumArgs = Record[Idx++];
7841 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7842 for (unsigned I = 0; I != NumArgs; ++I)
7843 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007844 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007845 }
7846 }
7847
7848 llvm_unreachable("Unhandled template argument kind!");
7849}
7850
7851TemplateParameterList *
7852ASTReader::ReadTemplateParameterList(ModuleFile &F,
7853 const RecordData &Record, unsigned &Idx) {
7854 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7855 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7856 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7857
7858 unsigned NumParams = Record[Idx++];
7859 SmallVector<NamedDecl *, 16> Params;
7860 Params.reserve(NumParams);
7861 while (NumParams--)
7862 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7863
7864 TemplateParameterList* TemplateParams =
7865 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
David Majnemer902f8c62015-12-27 07:16:27 +00007866 Params, RAngleLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 return TemplateParams;
7868}
7869
7870void
7871ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007872ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007874 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007875 unsigned NumTemplateArgs = Record[Idx++];
7876 TemplArgs.reserve(NumTemplateArgs);
7877 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007878 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007879}
7880
7881/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007882void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 const RecordData &Record, unsigned &Idx) {
7884 unsigned NumDecls = Record[Idx++];
7885 Set.reserve(Context, NumDecls);
7886 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007887 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007888 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007889 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 }
7891}
7892
7893CXXBaseSpecifier
7894ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7895 const RecordData &Record, unsigned &Idx) {
7896 bool isVirtual = static_cast<bool>(Record[Idx++]);
7897 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7898 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7899 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7900 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7901 SourceRange Range = ReadSourceRange(F, Record, Idx);
7902 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7903 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7904 EllipsisLoc);
7905 Result.setInheritConstructors(inheritConstructors);
7906 return Result;
7907}
7908
Richard Smithc2bb8182015-03-24 06:36:48 +00007909CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007910ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7911 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007912 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007913 assert(NumInitializers && "wrote ctor initializers but have no inits");
7914 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7915 for (unsigned i = 0; i != NumInitializers; ++i) {
7916 TypeSourceInfo *TInfo = nullptr;
7917 bool IsBaseVirtual = false;
7918 FieldDecl *Member = nullptr;
7919 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007920
Richard Smithc2bb8182015-03-24 06:36:48 +00007921 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7922 switch (Type) {
7923 case CTOR_INITIALIZER_BASE:
7924 TInfo = GetTypeSourceInfo(F, Record, Idx);
7925 IsBaseVirtual = Record[Idx++];
7926 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007927
Richard Smithc2bb8182015-03-24 06:36:48 +00007928 case CTOR_INITIALIZER_DELEGATING:
7929 TInfo = GetTypeSourceInfo(F, Record, Idx);
7930 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007931
Richard Smithc2bb8182015-03-24 06:36:48 +00007932 case CTOR_INITIALIZER_MEMBER:
7933 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7934 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007935
Richard Smithc2bb8182015-03-24 06:36:48 +00007936 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7937 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7938 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007940
7941 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7942 Expr *Init = ReadExpr(F);
7943 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7944 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7945 bool IsWritten = Record[Idx++];
7946 unsigned SourceOrderOrNumArrayIndices;
7947 SmallVector<VarDecl *, 8> Indices;
7948 if (IsWritten) {
7949 SourceOrderOrNumArrayIndices = Record[Idx++];
7950 } else {
7951 SourceOrderOrNumArrayIndices = Record[Idx++];
7952 Indices.reserve(SourceOrderOrNumArrayIndices);
7953 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7954 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7955 }
7956
7957 CXXCtorInitializer *BOMInit;
7958 if (Type == CTOR_INITIALIZER_BASE) {
7959 BOMInit = new (Context)
7960 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7961 RParenLoc, MemberOrEllipsisLoc);
7962 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7963 BOMInit = new (Context)
7964 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7965 } else if (IsWritten) {
7966 if (Member)
7967 BOMInit = new (Context) CXXCtorInitializer(
7968 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7969 else
7970 BOMInit = new (Context)
7971 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7972 LParenLoc, Init, RParenLoc);
7973 } else {
7974 if (IndirectMember) {
7975 assert(Indices.empty() && "Indirect field improperly initialized");
7976 BOMInit = new (Context)
7977 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7978 LParenLoc, Init, RParenLoc);
7979 } else {
7980 BOMInit = CXXCtorInitializer::Create(
7981 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7982 Indices.data(), Indices.size());
7983 }
7984 }
7985
7986 if (IsWritten)
7987 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7988 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 }
7990
Richard Smithc2bb8182015-03-24 06:36:48 +00007991 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007992}
7993
7994NestedNameSpecifier *
7995ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7996 const RecordData &Record, unsigned &Idx) {
7997 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007998 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007999 for (unsigned I = 0; I != N; ++I) {
8000 NestedNameSpecifier::SpecifierKind Kind
8001 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8002 switch (Kind) {
8003 case NestedNameSpecifier::Identifier: {
8004 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8005 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8006 break;
8007 }
8008
8009 case NestedNameSpecifier::Namespace: {
8010 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8011 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8012 break;
8013 }
8014
8015 case NestedNameSpecifier::NamespaceAlias: {
8016 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8017 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8018 break;
8019 }
8020
8021 case NestedNameSpecifier::TypeSpec:
8022 case NestedNameSpecifier::TypeSpecWithTemplate: {
8023 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8024 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008025 return nullptr;
8026
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 bool Template = Record[Idx++];
8028 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8029 break;
8030 }
8031
8032 case NestedNameSpecifier::Global: {
8033 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8034 // No associated value, and there can't be a prefix.
8035 break;
8036 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008037
8038 case NestedNameSpecifier::Super: {
8039 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8040 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8041 break;
8042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 }
8044 Prev = NNS;
8045 }
8046 return NNS;
8047}
8048
8049NestedNameSpecifierLoc
8050ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8051 unsigned &Idx) {
8052 unsigned N = Record[Idx++];
8053 NestedNameSpecifierLocBuilder Builder;
8054 for (unsigned I = 0; I != N; ++I) {
8055 NestedNameSpecifier::SpecifierKind Kind
8056 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8057 switch (Kind) {
8058 case NestedNameSpecifier::Identifier: {
8059 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8060 SourceRange Range = ReadSourceRange(F, Record, Idx);
8061 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8062 break;
8063 }
8064
8065 case NestedNameSpecifier::Namespace: {
8066 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8067 SourceRange Range = ReadSourceRange(F, Record, Idx);
8068 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8069 break;
8070 }
8071
8072 case NestedNameSpecifier::NamespaceAlias: {
8073 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8074 SourceRange Range = ReadSourceRange(F, Record, Idx);
8075 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8076 break;
8077 }
8078
8079 case NestedNameSpecifier::TypeSpec:
8080 case NestedNameSpecifier::TypeSpecWithTemplate: {
8081 bool Template = Record[Idx++];
8082 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8083 if (!T)
8084 return NestedNameSpecifierLoc();
8085 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8086
8087 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8088 Builder.Extend(Context,
8089 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8090 T->getTypeLoc(), ColonColonLoc);
8091 break;
8092 }
8093
8094 case NestedNameSpecifier::Global: {
8095 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8096 Builder.MakeGlobal(Context, ColonColonLoc);
8097 break;
8098 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008099
8100 case NestedNameSpecifier::Super: {
8101 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8102 SourceRange Range = ReadSourceRange(F, Record, Idx);
8103 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8104 break;
8105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 }
8107 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008108
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 return Builder.getWithLocInContext(Context);
8110}
8111
8112SourceRange
8113ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8114 unsigned &Idx) {
8115 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8116 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8117 return SourceRange(beg, end);
8118}
8119
8120/// \brief Read an integral value
8121llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8122 unsigned BitWidth = Record[Idx++];
8123 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8124 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8125 Idx += NumWords;
8126 return Result;
8127}
8128
8129/// \brief Read a signed integral value
8130llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8131 bool isUnsigned = Record[Idx++];
8132 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8133}
8134
8135/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008136llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8137 const llvm::fltSemantics &Sem,
8138 unsigned &Idx) {
8139 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008140}
8141
8142// \brief Read a string
8143std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8144 unsigned Len = Record[Idx++];
8145 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8146 Idx += Len;
8147 return Result;
8148}
8149
Richard Smith7ed1bc92014-12-05 22:42:13 +00008150std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8151 unsigned &Idx) {
8152 std::string Filename = ReadString(Record, Idx);
8153 ResolveImportedPath(F, Filename);
8154 return Filename;
8155}
8156
Guy Benyei11169dd2012-12-18 14:30:41 +00008157VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8158 unsigned &Idx) {
8159 unsigned Major = Record[Idx++];
8160 unsigned Minor = Record[Idx++];
8161 unsigned Subminor = Record[Idx++];
8162 if (Minor == 0)
8163 return VersionTuple(Major);
8164 if (Subminor == 0)
8165 return VersionTuple(Major, Minor - 1);
8166 return VersionTuple(Major, Minor - 1, Subminor - 1);
8167}
8168
8169CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8170 const RecordData &Record,
8171 unsigned &Idx) {
8172 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8173 return CXXTemporary::Create(Context, Decl);
8174}
8175
8176DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008177 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008178}
8179
8180DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8181 return Diags.Report(Loc, DiagID);
8182}
8183
8184/// \brief Retrieve the identifier table associated with the
8185/// preprocessor.
8186IdentifierTable &ASTReader::getIdentifierTable() {
8187 return PP.getIdentifierTable();
8188}
8189
8190/// \brief Record that the given ID maps to the given switch-case
8191/// statement.
8192void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008193 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 "Already have a SwitchCase with this ID");
8195 (*CurrSwitchCaseStmts)[ID] = SC;
8196}
8197
8198/// \brief Retrieve the switch-case statement with the given ID.
8199SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008200 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 return (*CurrSwitchCaseStmts)[ID];
8202}
8203
8204void ASTReader::ClearSwitchCaseIDs() {
8205 CurrSwitchCaseStmts->clear();
8206}
8207
8208void ASTReader::ReadComments() {
8209 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008210 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 serialization::ModuleFile *> >::iterator
8212 I = CommentsCursors.begin(),
8213 E = CommentsCursors.end();
8214 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008215 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008216 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 serialization::ModuleFile &F = *I->second;
8218 SavedStreamPosition SavedPosition(Cursor);
8219
8220 RecordData Record;
8221 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008222 llvm::BitstreamEntry Entry =
8223 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008224
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008225 switch (Entry.Kind) {
8226 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8227 case llvm::BitstreamEntry::Error:
8228 Error("malformed block record in AST file");
8229 return;
8230 case llvm::BitstreamEntry::EndBlock:
8231 goto NextCursor;
8232 case llvm::BitstreamEntry::Record:
8233 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 }
8236
8237 // Read a record.
8238 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008239 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 case COMMENTS_RAW_COMMENT: {
8241 unsigned Idx = 0;
8242 SourceRange SR = ReadSourceRange(F, Record, Idx);
8243 RawComment::CommentKind Kind =
8244 (RawComment::CommentKind) Record[Idx++];
8245 bool IsTrailingComment = Record[Idx++];
8246 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008247 Comments.push_back(new (Context) RawComment(
8248 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8249 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 break;
8251 }
8252 }
8253 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008254 NextCursor:
8255 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008257}
8258
Richard Smithcd45dbc2014-04-19 03:48:30 +00008259std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8260 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008261 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008262 return M->getFullModuleName();
8263
8264 // Otherwise, use the name of the top-level module the decl is within.
8265 if (ModuleFile *M = getOwningModuleFile(D))
8266 return M->ModuleName;
8267
8268 // Not from a module.
8269 return "";
8270}
8271
Guy Benyei11169dd2012-12-18 14:30:41 +00008272void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008273 while (!PendingIdentifierInfos.empty() ||
8274 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008275 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008276 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 // If any identifiers with corresponding top-level declarations have
8278 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008279 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8280 TopLevelDeclsMap;
8281 TopLevelDeclsMap TopLevelDecls;
8282
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008284 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008285 SmallVector<uint32_t, 4> DeclIDs =
8286 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008287 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008288
8289 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008291
Richard Smith851072e2014-05-19 20:59:20 +00008292 // For each decl chain that we wanted to complete while deserializing, mark
8293 // it as "still needs to be completed".
8294 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8295 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8296 }
8297 PendingIncompleteDeclChains.clear();
8298
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008300 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008301 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 PendingDeclChains.clear();
8303
Douglas Gregor6168bd22013-02-18 15:53:43 +00008304 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008305 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8306 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008307 IdentifierInfo *II = TLD->first;
8308 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008309 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008310 }
8311 }
8312
Guy Benyei11169dd2012-12-18 14:30:41 +00008313 // Load any pending macro definitions.
8314 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008315 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8316 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8317 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8318 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008319 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008320 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008321 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008322 if (Info.M->Kind != MK_ImplicitModule &&
8323 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008324 resolvePendingMacro(II, Info);
8325 }
8326 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008327 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008328 ++IDIdx) {
8329 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008330 if (Info.M->Kind == MK_ImplicitModule ||
8331 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008332 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008333 }
8334 }
8335 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008336
8337 // Wire up the DeclContexts for Decls that we delayed setting until
8338 // recursive loading is completed.
8339 while (!PendingDeclContextInfos.empty()) {
8340 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8341 PendingDeclContextInfos.pop_front();
8342 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8343 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8344 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8345 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008346
Richard Smithd1c46742014-04-30 02:24:17 +00008347 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008348 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008349 auto Update = PendingUpdateRecords.pop_back_val();
8350 ReadingKindTracker ReadingKind(Read_Decl, *this);
8351 loadDeclUpdateRecords(Update.first, Update.second);
8352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 }
Richard Smith8a639892015-01-24 01:07:20 +00008354
8355 // At this point, all update records for loaded decls are in place, so any
8356 // fake class definitions should have become real.
8357 assert(PendingFakeDefinitionData.empty() &&
8358 "faked up a class definition but never saw the real one");
8359
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 // If we deserialized any C++ or Objective-C class definitions, any
8361 // Objective-C protocol definitions, or any redeclarable templates, make sure
8362 // that all redeclarations point to the definitions. Note that this can only
8363 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008364 for (Decl *D : PendingDefinitions) {
8365 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008366 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 // Make sure that the TagType points at the definition.
8368 const_cast<TagType*>(TagT)->decl = TD;
8369 }
Richard Smith8ce51082015-03-11 01:44:51 +00008370
Craig Topperc6914d02014-08-25 04:15:02 +00008371 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008372 for (auto *R = getMostRecentExistingDecl(RD); R;
8373 R = R->getPreviousDecl()) {
8374 assert((R == D) ==
8375 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008376 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008377 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008378 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 }
8380
8381 continue;
8382 }
Richard Smith8ce51082015-03-11 01:44:51 +00008383
Craig Topperc6914d02014-08-25 04:15:02 +00008384 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 // Make sure that the ObjCInterfaceType points at the definition.
8386 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8387 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008388
8389 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8390 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8391
Guy Benyei11169dd2012-12-18 14:30:41 +00008392 continue;
8393 }
Richard Smith8ce51082015-03-11 01:44:51 +00008394
Craig Topperc6914d02014-08-25 04:15:02 +00008395 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008396 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8397 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8398
Guy Benyei11169dd2012-12-18 14:30:41 +00008399 continue;
8400 }
Richard Smith8ce51082015-03-11 01:44:51 +00008401
Craig Topperc6914d02014-08-25 04:15:02 +00008402 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008403 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8404 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008405 }
8406 PendingDefinitions.clear();
8407
8408 // Load the bodies of any functions or methods we've encountered. We do
8409 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008410 // have been fully wired up (hasBody relies on this).
8411 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8413 PBEnd = PendingBodies.end();
8414 PB != PBEnd; ++PB) {
8415 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8416 // FIXME: Check for =delete/=default?
8417 // FIXME: Complain about ODR violations here?
8418 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8419 FD->setLazyBody(PB->second);
8420 continue;
8421 }
8422
8423 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8424 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8425 MD->setLazyBody(PB->second);
8426 }
8427 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008428
8429 // Do some cleanup.
8430 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8431 getContext().deduplicateMergedDefinitonsFor(ND);
8432 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008433}
8434
8435void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008436 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8437 return;
8438
Richard Smitha0ce9c42014-07-29 23:23:27 +00008439 // Trigger the import of the full definition of each class that had any
8440 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008441 // These updates may in turn find and diagnose some ODR failures, so take
8442 // ownership of the set first.
8443 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8444 PendingOdrMergeFailures.clear();
8445 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008446 Merge.first->buildLookup();
8447 Merge.first->decls_begin();
8448 Merge.first->bases_begin();
8449 Merge.first->vbases_begin();
8450 for (auto *RD : Merge.second) {
8451 RD->decls_begin();
8452 RD->bases_begin();
8453 RD->vbases_begin();
8454 }
8455 }
8456
8457 // For each declaration from a merged context, check that the canonical
8458 // definition of that context also contains a declaration of the same
8459 // entity.
8460 //
8461 // Caution: this loop does things that might invalidate iterators into
8462 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8463 while (!PendingOdrMergeChecks.empty()) {
8464 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8465
8466 // FIXME: Skip over implicit declarations for now. This matters for things
8467 // like implicitly-declared special member functions. This isn't entirely
8468 // correct; we can end up with multiple unmerged declarations of the same
8469 // implicit entity.
8470 if (D->isImplicit())
8471 continue;
8472
8473 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008474
8475 bool Found = false;
8476 const Decl *DCanon = D->getCanonicalDecl();
8477
Richard Smith01bdb7a2014-08-28 05:44:07 +00008478 for (auto RI : D->redecls()) {
8479 if (RI->getLexicalDeclContext() == CanonDef) {
8480 Found = true;
8481 break;
8482 }
8483 }
8484 if (Found)
8485 continue;
8486
Richard Smith0f4e2c42015-08-06 04:23:48 +00008487 // Quick check failed, time to do the slow thing. Note, we can't just
8488 // look up the name of D in CanonDef here, because the member that is
8489 // in CanonDef might not be found by name lookup (it might have been
8490 // replaced by a more recent declaration in the lookup table), and we
8491 // can't necessarily find it in the redeclaration chain because it might
8492 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008493 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008494 for (auto *CanonMember : CanonDef->decls()) {
8495 if (CanonMember->getCanonicalDecl() == DCanon) {
8496 // This can happen if the declaration is merely mergeable and not
8497 // actually redeclarable (we looked for redeclarations earlier).
8498 //
8499 // FIXME: We should be able to detect this more efficiently, without
8500 // pulling in all of the members of CanonDef.
8501 Found = true;
8502 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008503 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008504 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8505 if (ND->getDeclName() == D->getDeclName())
8506 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008507 }
8508
8509 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008510 // The AST doesn't like TagDecls becoming invalid after they've been
8511 // completed. We only really need to mark FieldDecls as invalid here.
8512 if (!isa<TagDecl>(D))
8513 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008514
8515 // Ensure we don't accidentally recursively enter deserialization while
8516 // we're producing our diagnostic.
8517 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008518
8519 std::string CanonDefModule =
8520 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8521 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8522 << D << getOwningModuleNameForDiagnostic(D)
8523 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8524
8525 if (Candidates.empty())
8526 Diag(cast<Decl>(CanonDef)->getLocation(),
8527 diag::note_module_odr_violation_no_possible_decls) << D;
8528 else {
8529 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8530 Diag(Candidates[I]->getLocation(),
8531 diag::note_module_odr_violation_possible_decl)
8532 << Candidates[I];
8533 }
8534
8535 DiagnosedOdrMergeFailures.insert(CanonDef);
8536 }
8537 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008538
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008539 if (OdrMergeFailures.empty())
8540 return;
8541
8542 // Ensure we don't accidentally recursively enter deserialization while
8543 // we're producing our diagnostics.
8544 Deserializing RecursionGuard(this);
8545
Richard Smithcd45dbc2014-04-19 03:48:30 +00008546 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008547 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008548 // If we've already pointed out a specific problem with this class, don't
8549 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008550 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008551 continue;
8552
8553 bool Diagnosed = false;
8554 for (auto *RD : Merge.second) {
8555 // Multiple different declarations got merged together; tell the user
8556 // where they came from.
8557 if (Merge.first != RD) {
8558 // FIXME: Walk the definition, figure out what's different,
8559 // and diagnose that.
8560 if (!Diagnosed) {
8561 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8562 Diag(Merge.first->getLocation(),
8563 diag::err_module_odr_violation_different_definitions)
8564 << Merge.first << Module.empty() << Module;
8565 Diagnosed = true;
8566 }
8567
8568 Diag(RD->getLocation(),
8569 diag::note_module_odr_violation_different_definitions)
8570 << getOwningModuleNameForDiagnostic(RD);
8571 }
8572 }
8573
8574 if (!Diagnosed) {
8575 // All definitions are updates to the same declaration. This happens if a
8576 // module instantiates the declaration of a class template specialization
8577 // and two or more other modules instantiate its definition.
8578 //
8579 // FIXME: Indicate which modules had instantiations of this definition.
8580 // FIXME: How can this even happen?
8581 Diag(Merge.first->getLocation(),
8582 diag::err_module_odr_violation_different_instantiations)
8583 << Merge.first;
8584 }
8585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008586}
8587
Richard Smithce18a182015-07-14 00:26:00 +00008588void ASTReader::StartedDeserializing() {
8589 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8590 ReadTimer->startTimer();
8591}
8592
Guy Benyei11169dd2012-12-18 14:30:41 +00008593void ASTReader::FinishedDeserializing() {
8594 assert(NumCurrentElementsDeserializing &&
8595 "FinishedDeserializing not paired with StartedDeserializing");
8596 if (NumCurrentElementsDeserializing == 1) {
8597 // We decrease NumCurrentElementsDeserializing only after pending actions
8598 // are finished, to avoid recursively re-calling finishPendingActions().
8599 finishPendingActions();
8600 }
8601 --NumCurrentElementsDeserializing;
8602
Richard Smitha0ce9c42014-07-29 23:23:27 +00008603 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008604 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008605 while (!PendingExceptionSpecUpdates.empty()) {
8606 auto Updates = std::move(PendingExceptionSpecUpdates);
8607 PendingExceptionSpecUpdates.clear();
8608 for (auto Update : Updates) {
8609 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008610 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008611 if (auto *Listener = Context.getASTMutationListener())
8612 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008613 for (auto *Redecl : Update.second->redecls())
8614 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008615 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008616 }
8617
Richard Smithce18a182015-07-14 00:26:00 +00008618 if (ReadTimer)
8619 ReadTimer->stopTimer();
8620
Richard Smith0f4e2c42015-08-06 04:23:48 +00008621 diagnoseOdrViolations();
8622
Richard Smith04d05b52014-03-23 00:27:18 +00008623 // We are not in recursive loading, so it's safe to pass the "interesting"
8624 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008625 if (Consumer)
8626 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 }
8628}
8629
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008630void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008631 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8632 // Remove any fake results before adding any real ones.
8633 auto It = PendingFakeLookupResults.find(II);
8634 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008635 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008636 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008637 // FIXME: this works around module+PCH performance issue.
8638 // Rather than erase the result from the map, which is O(n), just clear
8639 // the vector of NamedDecls.
8640 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008641 }
8642 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008643
8644 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8645 SemaObj->TUScope->AddDecl(D);
8646 } else if (SemaObj->TUScope) {
8647 // Adding the decl to IdResolver may have failed because it was already in
8648 // (even though it was not added in scope). If it is already in, make sure
8649 // it gets in the scope as well.
8650 if (std::find(SemaObj->IdResolver.begin(Name),
8651 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8652 SemaObj->TUScope->AddDecl(D);
8653 }
8654}
8655
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008656ASTReader::ASTReader(
8657 Preprocessor &PP, ASTContext &Context,
8658 const PCHContainerReader &PCHContainerRdr,
8659 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8660 StringRef isysroot, bool DisableValidation,
8661 bool AllowASTWithCompilerErrors,
8662 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8663 bool UseGlobalIndex,
8664 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008665 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008666 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008667 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008668 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008669 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008670 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008671 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008672 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8673 AllowConfigurationMismatch(AllowConfigurationMismatch),
8674 ValidateSystemInputs(ValidateSystemInputs),
8675 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008676 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8677 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8678 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8679 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008680 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8681 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8682 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8683 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8684 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8685 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008686 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008688
8689 for (const auto &Ext : Extensions) {
8690 auto BlockName = Ext->getExtensionMetadata().BlockName;
8691 auto Known = ModuleFileExtensions.find(BlockName);
8692 if (Known != ModuleFileExtensions.end()) {
8693 Diags.Report(diag::warn_duplicate_module_file_extension)
8694 << BlockName;
8695 continue;
8696 }
8697
8698 ModuleFileExtensions.insert({BlockName, Ext});
8699 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008700}
8701
8702ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008703 if (OwnsDeserializationListener)
8704 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008705}