blob: 2defd38e27a6ff91503d229216b9496820fe4022 [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();
1966 if (!Overridden && SM.isFileOverridden(File)) {
1967 if (Complain)
1968 Error(diag::err_fe_pch_file_overridden, Filename);
1969 // After emitting the diagnostic, recover by disabling the override so
1970 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00001971 //
1972 // FIXME: This recovery is just as broken as the original state; there may
1973 // be another precompiled module that's using the overridden contents, or
1974 // we might be half way through parsing it. Instead, we should treat the
1975 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00001976 SM.disableFileContentsOverride(File);
1977 // The FileEntry is a virtual file entry with the size of the contents
1978 // that would override the original contents. Set it to the original's
1979 // size/time.
1980 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1981 StoredSize, StoredTime);
1982 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001983
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 bool IsOutOfDate = false;
1985
1986 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001987 if (!Overridden && //
1988 (StoredSize != File->getSize() ||
1989#if defined(LLVM_ON_WIN32)
1990 false
1991#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001992 // In our regression testing, the Windows file system seems to
1993 // have inconsistent modification times that sometimes
1994 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001995 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001996 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1997 (StoredTime && StoredTime != File->getModificationTime() &&
1998 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001999#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 )) {
2001 if (Complain) {
2002 // Build a list of the PCH imports that got us here (in reverse).
2003 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2004 while (ImportStack.back()->ImportedBy.size() > 0)
2005 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002006
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 // The top-level PCH is stale.
2008 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2009 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002010
Ben Langmuir198c1682014-03-07 07:27:49 +00002011 // Print the import stack.
2012 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2013 Diag(diag::note_pch_required_by)
2014 << Filename << ImportStack[0]->FileName;
2015 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002016 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002017 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002018 }
2019
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 if (!Diags.isDiagnosticInFlight())
2021 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002022 }
2023
Ben Langmuir198c1682014-03-07 07:27:49 +00002024 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002026 // FIXME: If the file is overridden and we've already opened it,
2027 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002028
Richard Smitha8cfffa2015-11-26 02:04:16 +00002029 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002030
2031 // Note that we've loaded this input file.
2032 F.InputFilesLoaded[ID-1] = IF;
2033 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002034}
2035
Richard Smith7ed1bc92014-12-05 22:42:13 +00002036/// \brief If we are loading a relocatable PCH or module file, and the filename
2037/// is not an absolute path, add the system or module root to the beginning of
2038/// the file name.
2039void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2040 // Resolve relative to the base directory, if we have one.
2041 if (!M.BaseDirectory.empty())
2042 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002043}
2044
Richard Smith7ed1bc92014-12-05 22:42:13 +00002045void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2047 return;
2048
Richard Smith7ed1bc92014-12-05 22:42:13 +00002049 SmallString<128> Buffer;
2050 llvm::sys::path::append(Buffer, Prefix, Filename);
2051 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002052}
2053
Richard Smith0f99d6a2015-08-09 08:48:41 +00002054static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2055 switch (ARR) {
2056 case ASTReader::Failure: return true;
2057 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2058 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2059 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2060 case ASTReader::ConfigurationMismatch:
2061 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2062 case ASTReader::HadErrors: return true;
2063 case ASTReader::Success: return false;
2064 }
2065
2066 llvm_unreachable("unknown ASTReadResult");
2067}
2068
Richard Smith0516b182015-09-08 19:40:14 +00002069ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2070 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2071 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2072 std::string &SuggestedPredefines) {
2073 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2074 return Failure;
2075
2076 // Read all of the records in the options block.
2077 RecordData Record;
2078 ASTReadResult Result = Success;
2079 while (1) {
2080 llvm::BitstreamEntry Entry = Stream.advance();
2081
2082 switch (Entry.Kind) {
2083 case llvm::BitstreamEntry::Error:
2084 case llvm::BitstreamEntry::SubBlock:
2085 return Failure;
2086
2087 case llvm::BitstreamEntry::EndBlock:
2088 return Result;
2089
2090 case llvm::BitstreamEntry::Record:
2091 // The interesting case.
2092 break;
2093 }
2094
2095 // Read and process a record.
2096 Record.clear();
2097 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2098 case LANGUAGE_OPTIONS: {
2099 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2100 if (ParseLanguageOptions(Record, Complain, Listener,
2101 AllowCompatibleConfigurationMismatch))
2102 Result = ConfigurationMismatch;
2103 break;
2104 }
2105
2106 case TARGET_OPTIONS: {
2107 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2108 if (ParseTargetOptions(Record, Complain, Listener,
2109 AllowCompatibleConfigurationMismatch))
2110 Result = ConfigurationMismatch;
2111 break;
2112 }
2113
2114 case DIAGNOSTIC_OPTIONS: {
2115 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2116 if (!AllowCompatibleConfigurationMismatch &&
2117 ParseDiagnosticOptions(Record, Complain, Listener))
2118 return OutOfDate;
2119 break;
2120 }
2121
2122 case FILE_SYSTEM_OPTIONS: {
2123 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2124 if (!AllowCompatibleConfigurationMismatch &&
2125 ParseFileSystemOptions(Record, Complain, Listener))
2126 Result = ConfigurationMismatch;
2127 break;
2128 }
2129
2130 case HEADER_SEARCH_OPTIONS: {
2131 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2132 if (!AllowCompatibleConfigurationMismatch &&
2133 ParseHeaderSearchOptions(Record, Complain, Listener))
2134 Result = ConfigurationMismatch;
2135 break;
2136 }
2137
2138 case PREPROCESSOR_OPTIONS:
2139 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2140 if (!AllowCompatibleConfigurationMismatch &&
2141 ParsePreprocessorOptions(Record, Complain, Listener,
2142 SuggestedPredefines))
2143 Result = ConfigurationMismatch;
2144 break;
2145 }
2146 }
2147}
2148
Guy Benyei11169dd2012-12-18 14:30:41 +00002149ASTReader::ASTReadResult
2150ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002151 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002152 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002154 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002155 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002156
2157 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2158 Error("malformed block record in AST file");
2159 return Failure;
2160 }
2161
2162 // Read all of the records and blocks in the control block.
2163 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002164 unsigned NumInputs = 0;
2165 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002166 while (1) {
2167 llvm::BitstreamEntry Entry = Stream.advance();
2168
2169 switch (Entry.Kind) {
2170 case llvm::BitstreamEntry::Error:
2171 Error("malformed block record in AST file");
2172 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002173 case llvm::BitstreamEntry::EndBlock: {
2174 // Validate input files.
2175 const HeaderSearchOptions &HSOpts =
2176 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002177
Richard Smitha1825302014-10-23 22:18:29 +00002178 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002179 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2180 // loaded module files, ignore missing inputs.
2181 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002182 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002183
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002184 // If we are reading a module, we will create a verification timestamp,
2185 // so we verify all input files. Otherwise, verify only user input
2186 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002187
2188 unsigned N = NumUserInputs;
2189 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002190 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002191 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002192 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002193 N = NumInputs;
2194
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002195 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002196 InputFile IF = getInputFile(F, I+1, Complain);
2197 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002199 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002201
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002202 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002203 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002204
Ben Langmuircb69b572014-03-07 06:40:32 +00002205 if (Listener && Listener->needsInputFileVisitation()) {
2206 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2207 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002208 for (unsigned I = 0; I < N; ++I) {
2209 bool IsSystem = I >= NumUserInputs;
2210 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002211 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2212 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002213 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002214 }
2215
Richard Smith8a308ec2015-11-05 00:54:55 +00002216 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002217 }
2218
Chris Lattnere7b154b2013-01-19 21:39:22 +00002219 case llvm::BitstreamEntry::SubBlock:
2220 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 case INPUT_FILES_BLOCK_ID:
2222 F.InputFilesCursor = Stream;
2223 if (Stream.SkipBlock() || // Skip with the main cursor
2224 // Read the abbreviations
2225 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2226 Error("malformed block record in AST file");
2227 return Failure;
2228 }
2229 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002230
2231 case OPTIONS_BLOCK_ID:
2232 // If we're reading the first module for this group, check its options
2233 // are compatible with ours. For modules it imports, no further checking
2234 // is required, because we checked them when we built it.
2235 if (Listener && !ImportedBy) {
2236 // Should we allow the configuration of the module file to differ from
2237 // the configuration of the current translation unit in a compatible
2238 // way?
2239 //
2240 // FIXME: Allow this for files explicitly specified with -include-pch.
2241 bool AllowCompatibleConfigurationMismatch =
2242 F.Kind == MK_ExplicitModule;
2243
Richard Smith8a308ec2015-11-05 00:54:55 +00002244 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2245 AllowCompatibleConfigurationMismatch,
2246 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002247 if (Result == Failure) {
2248 Error("malformed block record in AST file");
2249 return Result;
2250 }
2251
Richard Smith8a308ec2015-11-05 00:54:55 +00002252 if (DisableValidation ||
2253 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2254 Result = Success;
2255
2256 // If we've diagnosed a problem, we're done.
2257 if (Result != Success &&
2258 isDiagnosedResult(Result, ClientLoadCapabilities))
Richard Smith0516b182015-09-08 19:40:14 +00002259 return Result;
2260 } else if (Stream.SkipBlock()) {
2261 Error("malformed block record in AST file");
2262 return Failure;
2263 }
2264 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002265
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002267 if (Stream.SkipBlock()) {
2268 Error("malformed block record in AST file");
2269 return Failure;
2270 }
2271 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002273
2274 case llvm::BitstreamEntry::Record:
2275 // The interesting case.
2276 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 }
2278
2279 // Read and process a record.
2280 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002281 StringRef Blob;
2282 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 case METADATA: {
2284 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2285 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002286 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2287 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 return VersionMismatch;
2289 }
2290
Richard Smithe75ee0f2015-08-17 07:13:32 +00002291 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2293 Diag(diag::err_pch_with_compiler_errors);
2294 return HadErrors;
2295 }
2296
2297 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002298 // Relative paths in a relocatable PCH are relative to our sysroot.
2299 if (F.RelocatablePCH)
2300 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002301
Richard Smithe75ee0f2015-08-17 07:13:32 +00002302 F.HasTimestamps = Record[5];
2303
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002305 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2307 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002308 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 return VersionMismatch;
2310 }
2311 break;
2312 }
2313
Ben Langmuir487ea142014-10-23 18:05:36 +00002314 case SIGNATURE:
2315 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2316 F.Signature = Record[0];
2317 break;
2318
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 case IMPORTS: {
2320 // Load each of the imported PCH files.
2321 unsigned Idx = 0, N = Record.size();
2322 while (Idx < N) {
2323 // Read information about the AST file.
2324 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2325 // The import location will be the local one for now; we will adjust
2326 // all import locations of module imports after the global source
2327 // location info are setup.
2328 SourceLocation ImportLoc =
2329 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002330 off_t StoredSize = (off_t)Record[Idx++];
2331 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002332 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002333 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002334
Richard Smith0f99d6a2015-08-09 08:48:41 +00002335 // If our client can't cope with us being out of date, we can't cope with
2336 // our dependency being missing.
2337 unsigned Capabilities = ClientLoadCapabilities;
2338 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2339 Capabilities &= ~ARR_Missing;
2340
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002342 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2343 Loaded, StoredSize, StoredModTime,
2344 StoredSignature, Capabilities);
2345
2346 // If we diagnosed a problem, produce a backtrace.
2347 if (isDiagnosedResult(Result, Capabilities))
2348 Diag(diag::note_module_file_imported_by)
2349 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2350
2351 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 case Failure: return Failure;
2353 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002354 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 case OutOfDate: return OutOfDate;
2356 case VersionMismatch: return VersionMismatch;
2357 case ConfigurationMismatch: return ConfigurationMismatch;
2358 case HadErrors: return HadErrors;
2359 case Success: break;
2360 }
2361 }
2362 break;
2363 }
2364
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 case ORIGINAL_FILE:
2366 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002367 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002369 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 break;
2371
2372 case ORIGINAL_FILE_ID:
2373 F.OriginalSourceFileID = FileID::get(Record[0]);
2374 break;
2375
2376 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002377 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 break;
2379
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002380 case MODULE_NAME:
2381 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002382 if (Listener)
2383 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002384 break;
2385
Richard Smith223d3f22014-12-06 03:21:08 +00002386 case MODULE_DIRECTORY: {
2387 assert(!F.ModuleName.empty() &&
2388 "MODULE_DIRECTORY found before MODULE_NAME");
2389 // If we've already loaded a module map file covering this module, we may
2390 // have a better path for it (relative to the current build).
2391 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2392 if (M && M->Directory) {
2393 // If we're implicitly loading a module, the base directory can't
2394 // change between the build and use.
2395 if (F.Kind != MK_ExplicitModule) {
2396 const DirectoryEntry *BuildDir =
2397 PP.getFileManager().getDirectory(Blob);
2398 if (!BuildDir || BuildDir != M->Directory) {
2399 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2400 Diag(diag::err_imported_module_relocated)
2401 << F.ModuleName << Blob << M->Directory->getName();
2402 return OutOfDate;
2403 }
2404 }
2405 F.BaseDirectory = M->Directory->getName();
2406 } else {
2407 F.BaseDirectory = Blob;
2408 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002409 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002410 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002411
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002412 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002413 if (ASTReadResult Result =
2414 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2415 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002416 break;
2417
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002418 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002419 NumInputs = Record[0];
2420 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002421 F.InputFileOffsets =
2422 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002423 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 break;
2425 }
2426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002427}
2428
Ben Langmuir2c9af442014-04-10 17:57:43 +00002429ASTReader::ASTReadResult
2430ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002431 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002432
2433 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2434 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002435 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 }
2437
2438 // Read all of the records and blocks for the AST file.
2439 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002440 while (1) {
2441 llvm::BitstreamEntry Entry = Stream.advance();
2442
2443 switch (Entry.Kind) {
2444 case llvm::BitstreamEntry::Error:
2445 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002446 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002447 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002448 // Outside of C++, we do not store a lookup map for the translation unit.
2449 // Instead, mark it as needing a lookup map to be built if this module
2450 // contains any declarations lexically within it (which it always does!).
2451 // This usually has no cost, since we very rarely need the lookup map for
2452 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002454 if (DC->hasExternalLexicalStorage() &&
2455 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002457
Ben Langmuir2c9af442014-04-10 17:57:43 +00002458 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002460 case llvm::BitstreamEntry::SubBlock:
2461 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 case DECLTYPES_BLOCK_ID:
2463 // We lazily load the decls block, but we want to set up the
2464 // DeclsCursor cursor to point into it. Clone our current bitcode
2465 // cursor to it, enter the block and read the abbrevs in that block.
2466 // With the main cursor, we just skip over it.
2467 F.DeclsCursor = Stream;
2468 if (Stream.SkipBlock() || // Skip with the main cursor.
2469 // Read the abbrevs.
2470 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2471 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002472 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 }
2474 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002475
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 case PREPROCESSOR_BLOCK_ID:
2477 F.MacroCursor = Stream;
2478 if (!PP.getExternalSource())
2479 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002480
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 if (Stream.SkipBlock() ||
2482 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2483 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002484 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 }
2486 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2487 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002488
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 case PREPROCESSOR_DETAIL_BLOCK_ID:
2490 F.PreprocessorDetailCursor = Stream;
2491 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002492 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002494 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002495 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002498 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2499
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 if (!PP.getPreprocessingRecord())
2501 PP.createPreprocessingRecord();
2502 if (!PP.getPreprocessingRecord()->getExternalSource())
2503 PP.getPreprocessingRecord()->SetExternalSource(*this);
2504 break;
2505
2506 case SOURCE_MANAGER_BLOCK_ID:
2507 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002508 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002510
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002512 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2513 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002515
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002517 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 if (Stream.SkipBlock() ||
2519 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2520 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002521 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 }
2523 CommentsCursors.push_back(std::make_pair(C, &F));
2524 break;
2525 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002526
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002528 if (Stream.SkipBlock()) {
2529 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002530 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002531 }
2532 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 }
2534 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002535
2536 case llvm::BitstreamEntry::Record:
2537 // The interesting case.
2538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 }
2540
2541 // Read and process a record.
2542 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002543 StringRef Blob;
2544 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 default: // Default behavior: ignore.
2546 break;
2547
2548 case TYPE_OFFSET: {
2549 if (F.LocalNumTypes != 0) {
2550 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002551 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002553 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 F.LocalNumTypes = Record[0];
2555 unsigned LocalBaseTypeIndex = Record[1];
2556 F.BaseTypeIndex = getTotalNumTypes();
2557
2558 if (F.LocalNumTypes > 0) {
2559 // Introduce the global -> local mapping for types within this module.
2560 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2561
2562 // Introduce the local -> global mapping for types within this module.
2563 F.TypeRemap.insertOrReplace(
2564 std::make_pair(LocalBaseTypeIndex,
2565 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002566
2567 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 }
2569 break;
2570 }
2571
2572 case DECL_OFFSET: {
2573 if (F.LocalNumDecls != 0) {
2574 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002575 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002577 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 F.LocalNumDecls = Record[0];
2579 unsigned LocalBaseDeclID = Record[1];
2580 F.BaseDeclID = getTotalNumDecls();
2581
2582 if (F.LocalNumDecls > 0) {
2583 // Introduce the global -> local mapping for declarations within this
2584 // module.
2585 GlobalDeclMap.insert(
2586 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2587
2588 // Introduce the local -> global mapping for declarations within this
2589 // module.
2590 F.DeclRemap.insertOrReplace(
2591 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2592
2593 // Introduce the global -> local mapping for declarations within this
2594 // module.
2595 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002596
Ben Langmuir52ca6782014-10-20 16:27:32 +00002597 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2598 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 break;
2600 }
2601
2602 case TU_UPDATE_LEXICAL: {
2603 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002604 LexicalContents Contents(
2605 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2606 Blob.data()),
2607 static_cast<unsigned int>(Blob.size() / 4));
2608 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 TU->setHasExternalLexicalStorage(true);
2610 break;
2611 }
2612
2613 case UPDATE_VISIBLE: {
2614 unsigned Idx = 0;
2615 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002616 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002617 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002618 // If we've already loaded the decl, perform the updates when we finish
2619 // loading this block.
2620 if (Decl *D = GetExistingDecl(ID))
2621 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 break;
2623 }
2624
2625 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002626 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002628 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2629 (const unsigned char *)F.IdentifierTableData + Record[0],
2630 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2631 (const unsigned char *)F.IdentifierTableData,
2632 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002633
2634 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2635 }
2636 break;
2637
2638 case IDENTIFIER_OFFSET: {
2639 if (F.LocalNumIdentifiers != 0) {
2640 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002641 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002643 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 F.LocalNumIdentifiers = Record[0];
2645 unsigned LocalBaseIdentifierID = Record[1];
2646 F.BaseIdentifierID = getTotalNumIdentifiers();
2647
2648 if (F.LocalNumIdentifiers > 0) {
2649 // Introduce the global -> local mapping for identifiers within this
2650 // module.
2651 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2652 &F));
2653
2654 // Introduce the local -> global mapping for identifiers within this
2655 // module.
2656 F.IdentifierRemap.insertOrReplace(
2657 std::make_pair(LocalBaseIdentifierID,
2658 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002659
Ben Langmuir52ca6782014-10-20 16:27:32 +00002660 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2661 + F.LocalNumIdentifiers);
2662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 break;
2664 }
2665
Richard Smith33e0f7e2015-07-22 02:08:40 +00002666 case INTERESTING_IDENTIFIERS:
2667 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2668 break;
2669
Ben Langmuir332aafe2014-01-31 01:06:56 +00002670 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002671 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2672 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002674 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 break;
2676
2677 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002678 if (SpecialTypes.empty()) {
2679 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2680 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2681 break;
2682 }
2683
2684 if (SpecialTypes.size() != Record.size()) {
2685 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002686 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002687 }
2688
2689 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2690 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2691 if (!SpecialTypes[I])
2692 SpecialTypes[I] = ID;
2693 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2694 // merge step?
2695 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 break;
2697
2698 case STATISTICS:
2699 TotalNumStatements += Record[0];
2700 TotalNumMacros += Record[1];
2701 TotalLexicalDeclContexts += Record[2];
2702 TotalVisibleDeclContexts += Record[3];
2703 break;
2704
2705 case UNUSED_FILESCOPED_DECLS:
2706 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2707 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2708 break;
2709
2710 case DELEGATING_CTORS:
2711 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2712 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2713 break;
2714
2715 case WEAK_UNDECLARED_IDENTIFIERS:
2716 if (Record.size() % 4 != 0) {
2717 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002718 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
2720
2721 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2722 // files. This isn't the way to do it :)
2723 WeakUndeclaredIdentifiers.clear();
2724
2725 // Translate the weak, undeclared identifiers into global IDs.
2726 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2727 WeakUndeclaredIdentifiers.push_back(
2728 getGlobalIdentifierID(F, Record[I++]));
2729 WeakUndeclaredIdentifiers.push_back(
2730 getGlobalIdentifierID(F, Record[I++]));
2731 WeakUndeclaredIdentifiers.push_back(
2732 ReadSourceLocation(F, Record, I).getRawEncoding());
2733 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2734 }
2735 break;
2736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002738 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 F.LocalNumSelectors = Record[0];
2740 unsigned LocalBaseSelectorID = Record[1];
2741 F.BaseSelectorID = getTotalNumSelectors();
2742
2743 if (F.LocalNumSelectors > 0) {
2744 // Introduce the global -> local mapping for selectors within this
2745 // module.
2746 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2747
2748 // Introduce the local -> global mapping for selectors within this
2749 // module.
2750 F.SelectorRemap.insertOrReplace(
2751 std::make_pair(LocalBaseSelectorID,
2752 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002753
2754 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 }
2756 break;
2757 }
2758
2759 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002760 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 if (Record[0])
2762 F.SelectorLookupTable
2763 = ASTSelectorLookupTable::Create(
2764 F.SelectorLookupTableData + Record[0],
2765 F.SelectorLookupTableData,
2766 ASTSelectorLookupTrait(*this, F));
2767 TotalNumMethodPoolEntries += Record[1];
2768 break;
2769
2770 case REFERENCED_SELECTOR_POOL:
2771 if (!Record.empty()) {
2772 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2773 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2774 Record[Idx++]));
2775 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2776 getRawEncoding());
2777 }
2778 }
2779 break;
2780
2781 case PP_COUNTER_VALUE:
2782 if (!Record.empty() && Listener)
2783 Listener->ReadCounter(F, Record[0]);
2784 break;
2785
2786 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002787 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 F.NumFileSortedDecls = Record[0];
2789 break;
2790
2791 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002792 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 F.LocalNumSLocEntries = Record[0];
2794 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002795 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002796 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002798 if (!F.SLocEntryBaseID) {
2799 Error("ran out of source locations");
2800 break;
2801 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 // Make our entry in the range map. BaseID is negative and growing, so
2803 // we invert it. Because we invert it, though, we need the other end of
2804 // the range.
2805 unsigned RangeStart =
2806 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2807 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2808 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2809
2810 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2811 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2812 GlobalSLocOffsetMap.insert(
2813 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2814 - SLocSpaceSize,&F));
2815
2816 // Initialize the remapping table.
2817 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002818 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002820 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2822
2823 TotalNumSLocEntries += F.LocalNumSLocEntries;
2824 break;
2825 }
2826
2827 case MODULE_OFFSET_MAP: {
2828 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002829 const unsigned char *Data = (const unsigned char*)Blob.data();
2830 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002831
2832 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2833 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2834 F.SLocRemap.insert(std::make_pair(0U, 0));
2835 F.SLocRemap.insert(std::make_pair(2U, 1));
2836 }
2837
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002839 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2840 RemapBuilder;
2841 RemapBuilder SLocRemap(F.SLocRemap);
2842 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2843 RemapBuilder MacroRemap(F.MacroRemap);
2844 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2845 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2846 RemapBuilder SelectorRemap(F.SelectorRemap);
2847 RemapBuilder DeclRemap(F.DeclRemap);
2848 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002849
Richard Smithd8879c82015-08-24 21:59:32 +00002850 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002851 using namespace llvm::support;
2852 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 StringRef Name = StringRef((const char*)Data, Len);
2854 Data += Len;
2855 ModuleFile *OM = ModuleMgr.lookup(Name);
2856 if (!OM) {
2857 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002858 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 }
2860
Justin Bogner57ba0b22014-03-28 22:03:24 +00002861 uint32_t SLocOffset =
2862 endian::readNext<uint32_t, little, unaligned>(Data);
2863 uint32_t IdentifierIDOffset =
2864 endian::readNext<uint32_t, little, unaligned>(Data);
2865 uint32_t MacroIDOffset =
2866 endian::readNext<uint32_t, little, unaligned>(Data);
2867 uint32_t PreprocessedEntityIDOffset =
2868 endian::readNext<uint32_t, little, unaligned>(Data);
2869 uint32_t SubmoduleIDOffset =
2870 endian::readNext<uint32_t, little, unaligned>(Data);
2871 uint32_t SelectorIDOffset =
2872 endian::readNext<uint32_t, little, unaligned>(Data);
2873 uint32_t DeclIDOffset =
2874 endian::readNext<uint32_t, little, unaligned>(Data);
2875 uint32_t TypeIndexOffset =
2876 endian::readNext<uint32_t, little, unaligned>(Data);
2877
Ben Langmuir785180e2014-10-20 16:27:30 +00002878 uint32_t None = std::numeric_limits<uint32_t>::max();
2879
2880 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2881 RemapBuilder &Remap) {
2882 if (Offset != None)
2883 Remap.insert(std::make_pair(Offset,
2884 static_cast<int>(BaseOffset - Offset)));
2885 };
2886 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2887 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2888 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2889 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2890 PreprocessedEntityRemap);
2891 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2892 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2893 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2894 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002895
2896 // Global -> local mappings.
2897 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2898 }
2899 break;
2900 }
2901
2902 case SOURCE_MANAGER_LINE_TABLE:
2903 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002904 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 break;
2906
2907 case SOURCE_LOCATION_PRELOADS: {
2908 // Need to transform from the local view (1-based IDs) to the global view,
2909 // which is based off F.SLocEntryBaseID.
2910 if (!F.PreloadSLocEntries.empty()) {
2911 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002912 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 }
2914
2915 F.PreloadSLocEntries.swap(Record);
2916 break;
2917 }
2918
2919 case EXT_VECTOR_DECLS:
2920 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2921 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2922 break;
2923
2924 case VTABLE_USES:
2925 if (Record.size() % 3 != 0) {
2926 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002927 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 }
2929
2930 // Later tables overwrite earlier ones.
2931 // FIXME: Modules will have some trouble with this. This is clearly not
2932 // the right way to do this.
2933 VTableUses.clear();
2934
2935 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2936 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2937 VTableUses.push_back(
2938 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2939 VTableUses.push_back(Record[Idx++]);
2940 }
2941 break;
2942
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 case PENDING_IMPLICIT_INSTANTIATIONS:
2944 if (PendingInstantiations.size() % 2 != 0) {
2945 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002946 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 }
2948
2949 if (Record.size() % 2 != 0) {
2950 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002951 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 }
2953
2954 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2955 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2956 PendingInstantiations.push_back(
2957 ReadSourceLocation(F, Record, I).getRawEncoding());
2958 }
2959 break;
2960
2961 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002962 if (Record.size() != 2) {
2963 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002964 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002965 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2967 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2968 break;
2969
2970 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002971 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2972 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2973 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002974
2975 unsigned LocalBasePreprocessedEntityID = Record[0];
2976
2977 unsigned StartingID;
2978 if (!PP.getPreprocessingRecord())
2979 PP.createPreprocessingRecord();
2980 if (!PP.getPreprocessingRecord()->getExternalSource())
2981 PP.getPreprocessingRecord()->SetExternalSource(*this);
2982 StartingID
2983 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002984 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 F.BasePreprocessedEntityID = StartingID;
2986
2987 if (F.NumPreprocessedEntities > 0) {
2988 // Introduce the global -> local mapping for preprocessed entities in
2989 // this module.
2990 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2991
2992 // Introduce the local -> global mapping for preprocessed entities in
2993 // this module.
2994 F.PreprocessedEntityRemap.insertOrReplace(
2995 std::make_pair(LocalBasePreprocessedEntityID,
2996 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2997 }
2998
2999 break;
3000 }
3001
3002 case DECL_UPDATE_OFFSETS: {
3003 if (Record.size() % 2 != 0) {
3004 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003005 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003007 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3008 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3009 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3010
3011 // If we've already loaded the decl, perform the updates when we finish
3012 // loading this block.
3013 if (Decl *D = GetExistingDecl(ID))
3014 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3015 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 break;
3017 }
3018
3019 case DECL_REPLACEMENTS: {
3020 if (Record.size() % 3 != 0) {
3021 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 }
3024 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3025 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3026 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3027 break;
3028 }
3029
3030 case OBJC_CATEGORIES_MAP: {
3031 if (F.LocalNumObjCCategoriesInMap != 0) {
3032 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
3035
3036 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003037 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 break;
3039 }
3040
3041 case OBJC_CATEGORIES:
3042 F.ObjCCategories.swap(Record);
3043 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 case CXX_BASE_SPECIFIER_OFFSETS: {
3046 if (F.LocalNumCXXBaseSpecifiers != 0) {
3047 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003048 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003050
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003052 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003053 break;
3054 }
3055
3056 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3057 if (F.LocalNumCXXCtorInitializers != 0) {
3058 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3059 return Failure;
3060 }
3061
3062 F.LocalNumCXXCtorInitializers = Record[0];
3063 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 break;
3065 }
3066
3067 case DIAG_PRAGMA_MAPPINGS:
3068 if (F.PragmaDiagMappings.empty())
3069 F.PragmaDiagMappings.swap(Record);
3070 else
3071 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3072 Record.begin(), Record.end());
3073 break;
3074
3075 case CUDA_SPECIAL_DECL_REFS:
3076 // Later tables overwrite earlier ones.
3077 // FIXME: Modules will have trouble with this.
3078 CUDASpecialDeclRefs.clear();
3079 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3080 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3081 break;
3082
3083 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003084 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 if (Record[0]) {
3087 F.HeaderFileInfoTable
3088 = HeaderFileInfoLookupTable::Create(
3089 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3090 (const unsigned char *)F.HeaderFileInfoTableData,
3091 HeaderFileInfoTrait(*this, F,
3092 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003093 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003094
3095 PP.getHeaderSearchInfo().SetExternalSource(this);
3096 if (!PP.getHeaderSearchInfo().getExternalLookup())
3097 PP.getHeaderSearchInfo().SetExternalLookup(this);
3098 }
3099 break;
3100 }
3101
3102 case FP_PRAGMA_OPTIONS:
3103 // Later tables overwrite earlier ones.
3104 FPPragmaOptions.swap(Record);
3105 break;
3106
3107 case OPENCL_EXTENSIONS:
3108 // Later tables overwrite earlier ones.
3109 OpenCLExtensions.swap(Record);
3110 break;
3111
3112 case TENTATIVE_DEFINITIONS:
3113 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3114 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3115 break;
3116
3117 case KNOWN_NAMESPACES:
3118 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3119 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3120 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003121
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003122 case UNDEFINED_BUT_USED:
3123 if (UndefinedButUsed.size() % 2 != 0) {
3124 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003125 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003126 }
3127
3128 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003129 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003130 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003131 }
3132 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003133 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3134 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003135 ReadSourceLocation(F, Record, I).getRawEncoding());
3136 }
3137 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003138 case DELETE_EXPRS_TO_ANALYZE:
3139 for (unsigned I = 0, N = Record.size(); I != N;) {
3140 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3141 const uint64_t Count = Record[I++];
3142 DelayedDeleteExprs.push_back(Count);
3143 for (uint64_t C = 0; C < Count; ++C) {
3144 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3145 bool IsArrayForm = Record[I++] == 1;
3146 DelayedDeleteExprs.push_back(IsArrayForm);
3147 }
3148 }
3149 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003152 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 // If we aren't loading a module (which has its own exports), make
3154 // all of the imported modules visible.
3155 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003156 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3157 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3158 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3159 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003160 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 }
3162 }
3163 break;
3164 }
3165
Guy Benyei11169dd2012-12-18 14:30:41 +00003166 case MACRO_OFFSET: {
3167 if (F.LocalNumMacros != 0) {
3168 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003169 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003171 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 F.LocalNumMacros = Record[0];
3173 unsigned LocalBaseMacroID = Record[1];
3174 F.BaseMacroID = getTotalNumMacros();
3175
3176 if (F.LocalNumMacros > 0) {
3177 // Introduce the global -> local mapping for macros within this module.
3178 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3179
3180 // Introduce the local -> global mapping for macros within this module.
3181 F.MacroRemap.insertOrReplace(
3182 std::make_pair(LocalBaseMacroID,
3183 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003184
3185 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 }
3187 break;
3188 }
3189
Richard Smithe40f2ba2013-08-07 21:41:30 +00003190 case LATE_PARSED_TEMPLATE: {
3191 LateParsedTemplates.append(Record.begin(), Record.end());
3192 break;
3193 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003194
3195 case OPTIMIZE_PRAGMA_OPTIONS:
3196 if (Record.size() != 1) {
3197 Error("invalid pragma optimize record");
3198 return Failure;
3199 }
3200 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3201 break;
Nico Weber72889432014-09-06 01:25:55 +00003202
3203 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3204 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3205 UnusedLocalTypedefNameCandidates.push_back(
3206 getGlobalDeclID(F, Record[I]));
3207 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 }
3209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003210}
3211
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003212ASTReader::ASTReadResult
3213ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3214 const ModuleFile *ImportedBy,
3215 unsigned ClientLoadCapabilities) {
3216 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003217 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003218
Richard Smithe842a472014-10-22 02:05:46 +00003219 if (F.Kind == MK_ExplicitModule) {
3220 // For an explicitly-loaded module, we don't care whether the original
3221 // module map file exists or matches.
3222 return Success;
3223 }
3224
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003225 // Try to resolve ModuleName in the current header search context and
3226 // verify that it is found in the same module map file as we saved. If the
3227 // top-level AST file is a main file, skip this check because there is no
3228 // usable header search context.
3229 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003230 "MODULE_NAME should come before MODULE_MAP_FILE");
3231 if (F.Kind == MK_ImplicitModule &&
3232 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3233 // An implicitly-loaded module file should have its module listed in some
3234 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003235 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003236 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3237 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3238 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003239 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003240 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3241 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3242 // This module was defined by an imported (explicit) module.
3243 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3244 << ASTFE->getName();
3245 else
3246 // This module was built with a different module map.
3247 Diag(diag::err_imported_module_not_found)
3248 << F.ModuleName << F.FileName << ImportedBy->FileName
3249 << F.ModuleMapPath;
3250 }
3251 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003252 }
3253
Richard Smithe842a472014-10-22 02:05:46 +00003254 assert(M->Name == F.ModuleName && "found module with different name");
3255
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003256 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003257 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003258 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3259 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003260 assert(ImportedBy && "top-level import should be verified");
3261 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3262 Diag(diag::err_imported_module_modmap_changed)
3263 << F.ModuleName << ImportedBy->FileName
3264 << ModMap->getName() << F.ModuleMapPath;
3265 return OutOfDate;
3266 }
3267
3268 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3269 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3270 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003271 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003272 const FileEntry *F =
3273 FileMgr.getFile(Filename, false, false);
3274 if (F == nullptr) {
3275 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3276 Error("could not find file '" + Filename +"' referenced by AST file");
3277 return OutOfDate;
3278 }
3279 AdditionalStoredMaps.insert(F);
3280 }
3281
3282 // Check any additional module map files (e.g. module.private.modulemap)
3283 // that are not in the pcm.
3284 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3285 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3286 // Remove files that match
3287 // Note: SmallPtrSet::erase is really remove
3288 if (!AdditionalStoredMaps.erase(ModMap)) {
3289 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3290 Diag(diag::err_module_different_modmap)
3291 << F.ModuleName << /*new*/0 << ModMap->getName();
3292 return OutOfDate;
3293 }
3294 }
3295 }
3296
3297 // Check any additional module map files that are in the pcm, but not
3298 // found in header search. Cases that match are already removed.
3299 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3300 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3301 Diag(diag::err_module_different_modmap)
3302 << F.ModuleName << /*not new*/1 << ModMap->getName();
3303 return OutOfDate;
3304 }
3305 }
3306
3307 if (Listener)
3308 Listener->ReadModuleMapFile(F.ModuleMapPath);
3309 return Success;
3310}
3311
3312
Douglas Gregorc1489562013-02-12 23:36:21 +00003313/// \brief Move the given method to the back of the global list of methods.
3314static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3315 // Find the entry for this selector in the method pool.
3316 Sema::GlobalMethodPool::iterator Known
3317 = S.MethodPool.find(Method->getSelector());
3318 if (Known == S.MethodPool.end())
3319 return;
3320
3321 // Retrieve the appropriate method list.
3322 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3323 : Known->second.second;
3324 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003325 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003326 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003327 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003328 Found = true;
3329 } else {
3330 // Keep searching.
3331 continue;
3332 }
3333 }
3334
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003335 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003336 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003337 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003338 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003339 }
3340}
3341
Richard Smithde711422015-04-23 21:20:19 +00003342void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003343 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003344 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003345 bool wasHidden = D->Hidden;
3346 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003347
Richard Smith49f906a2014-03-01 00:08:04 +00003348 if (wasHidden && SemaObj) {
3349 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3350 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003351 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 }
3353 }
3354}
3355
Richard Smith49f906a2014-03-01 00:08:04 +00003356void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003357 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003358 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003360 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003361 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003363 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003364
3365 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003366 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 // there is nothing more to do.
3368 continue;
3369 }
Richard Smith49f906a2014-03-01 00:08:04 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 if (!Mod->isAvailable()) {
3372 // Modules that aren't available cannot be made visible.
3373 continue;
3374 }
3375
3376 // Update the module's name visibility.
3377 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003378
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 // If we've already deserialized any names from this module,
3380 // mark them as visible.
3381 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3382 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003383 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003385 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003386 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3387 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003391 SmallVector<Module *, 16> Exports;
3392 Mod->getExportedModules(Exports);
3393 for (SmallVectorImpl<Module *>::iterator
3394 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3395 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003396 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003397 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 }
3399 }
3400}
3401
Douglas Gregore060e572013-01-25 01:03:03 +00003402bool ASTReader::loadGlobalIndex() {
3403 if (GlobalIndex)
3404 return false;
3405
3406 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3407 !Context.getLangOpts().Modules)
3408 return true;
3409
3410 // Try to load the global index.
3411 TriedLoadingGlobalIndex = true;
3412 StringRef ModuleCachePath
3413 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3414 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003415 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003416 if (!Result.first)
3417 return true;
3418
3419 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003420 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003421 return false;
3422}
3423
3424bool ASTReader::isGlobalIndexUnavailable() const {
3425 return Context.getLangOpts().Modules && UseGlobalIndex &&
3426 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3427}
3428
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003429static void updateModuleTimestamp(ModuleFile &MF) {
3430 // Overwrite the timestamp file contents so that file's mtime changes.
3431 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003432 std::error_code EC;
3433 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3434 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003435 return;
3436 OS << "Timestamp file\n";
3437}
3438
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003439/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3440/// cursor into the start of the given block ID, returning false on success and
3441/// true on failure.
3442static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3443 while (1) {
3444 llvm::BitstreamEntry Entry = Cursor.advance();
3445 switch (Entry.Kind) {
3446 case llvm::BitstreamEntry::Error:
3447 case llvm::BitstreamEntry::EndBlock:
3448 return true;
3449
3450 case llvm::BitstreamEntry::Record:
3451 // Ignore top-level records.
3452 Cursor.skipRecord(Entry.ID);
3453 break;
3454
3455 case llvm::BitstreamEntry::SubBlock:
3456 if (Entry.ID == BlockID) {
3457 if (Cursor.EnterSubBlock(BlockID))
3458 return true;
3459 // Found it!
3460 return false;
3461 }
3462
3463 if (Cursor.SkipBlock())
3464 return true;
3465 }
3466 }
3467}
3468
Guy Benyei11169dd2012-12-18 14:30:41 +00003469ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3470 ModuleKind Type,
3471 SourceLocation ImportLoc,
3472 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003473 llvm::SaveAndRestore<SourceLocation>
3474 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3475
Richard Smithd1c46742014-04-30 02:24:17 +00003476 // Defer any pending actions until we get to the end of reading the AST file.
3477 Deserializing AnASTFile(this);
3478
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003480 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003481
3482 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003483 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003485 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003486 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 ClientLoadCapabilities)) {
3488 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003489 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 case OutOfDate:
3491 case VersionMismatch:
3492 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003493 case HadErrors: {
3494 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3495 for (const ImportedModule &IM : Loaded)
3496 LoadedSet.insert(IM.Mod);
3497
Douglas Gregor7029ce12013-03-19 00:28:20 +00003498 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003499 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003500 Context.getLangOpts().Modules
3501 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003502 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003503
3504 // If we find that any modules are unusable, the global index is going
3505 // to be out-of-date. Just remove it.
3506 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003507 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003509 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 case Success:
3511 break;
3512 }
3513
3514 // Here comes stuff that we only do once the entire chain is loaded.
3515
3516 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003517 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3518 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 M != MEnd; ++M) {
3520 ModuleFile &F = *M->Mod;
3521
3522 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003523 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3524 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003525
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003526 // Read the extension blocks.
3527 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3528 if (ASTReadResult Result = ReadExtensionBlock(F))
3529 return Result;
3530 }
3531
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 // Once read, set the ModuleFile bit base offset and update the size in
3533 // bits of all files we've seen.
3534 F.GlobalBitOffset = TotalModulesSizeInBits;
3535 TotalModulesSizeInBits += F.SizeInBits;
3536 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3537
3538 // Preload SLocEntries.
3539 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3540 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3541 // Load it through the SourceManager and don't call ReadSLocEntry()
3542 // directly because the entry may have already been loaded in which case
3543 // calling ReadSLocEntry() directly would trigger an assertion in
3544 // SourceManager.
3545 SourceMgr.getLoadedSLocEntryByID(Index);
3546 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003547
3548 // Preload all the pending interesting identifiers by marking them out of
3549 // date.
3550 for (auto Offset : F.PreloadIdentifierOffsets) {
3551 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3552 F.IdentifierTableData + Offset);
3553
3554 ASTIdentifierLookupTrait Trait(*this, F);
3555 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3556 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003557 auto &II = PP.getIdentifierTable().getOwn(Key);
3558 II.setOutOfDate(true);
3559
3560 // Mark this identifier as being from an AST file so that we can track
3561 // whether we need to serialize it.
3562 if (!II.isFromAST()) {
3563 II.setIsFromAST();
Ben Langmuirb9ad4e62015-10-28 22:25:37 +00003564 bool IsModule = PP.getCurrentModule() != nullptr;
3565 if (isInterestingIdentifier(*this, II, IsModule))
Richard Smith79bf9202015-08-24 03:33:22 +00003566 II.setChangedSinceDeserialization();
3567 }
3568
3569 // Associate the ID with the identifier so that the writer can reuse it.
3570 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3571 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 }
3574
Douglas Gregor603cd862013-03-22 18:50:14 +00003575 // Setup the import locations and notify the module manager that we've
3576 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003577 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3578 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 M != MEnd; ++M) {
3580 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003581
3582 ModuleMgr.moduleFileAccepted(&F);
3583
3584 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003585 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 if (!M->ImportedBy)
3587 F.ImportLoc = M->ImportLoc;
3588 else
3589 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3590 M->ImportLoc.getRawEncoding());
3591 }
3592
Richard Smith33e0f7e2015-07-22 02:08:40 +00003593 if (!Context.getLangOpts().CPlusPlus ||
3594 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3595 // Mark all of the identifiers in the identifier table as being out of date,
3596 // so that various accessors know to check the loaded modules when the
3597 // identifier is used.
3598 //
3599 // For C++ modules, we don't need information on many identifiers (just
3600 // those that provide macros or are poisoned), so we mark all of
3601 // the interesting ones via PreloadIdentifierOffsets.
3602 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3603 IdEnd = PP.getIdentifierTable().end();
3604 Id != IdEnd; ++Id)
3605 Id->second->setOutOfDate(true);
3606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003607
3608 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003609 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3610 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3612 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003613
3614 switch (Unresolved.Kind) {
3615 case UnresolvedModuleRef::Conflict:
3616 if (ResolvedMod) {
3617 Module::Conflict Conflict;
3618 Conflict.Other = ResolvedMod;
3619 Conflict.Message = Unresolved.String.str();
3620 Unresolved.Mod->Conflicts.push_back(Conflict);
3621 }
3622 continue;
3623
3624 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003626 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003628
Douglas Gregorfb912652013-03-20 21:10:35 +00003629 case UnresolvedModuleRef::Export:
3630 if (ResolvedMod || Unresolved.IsWildcard)
3631 Unresolved.Mod->Exports.push_back(
3632 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3633 continue;
3634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003636 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003637
3638 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3639 // Might be unnecessary as use declarations are only used to build the
3640 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003641
3642 InitializeContext();
3643
Richard Smith3d8e97e2013-10-18 06:54:39 +00003644 if (SemaObj)
3645 UpdateSema();
3646
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 if (DeserializationListener)
3648 DeserializationListener->ReaderInitialized(this);
3649
3650 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003651 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 PrimaryModule.OriginalSourceFileID
3653 = FileID::get(PrimaryModule.SLocEntryBaseID
3654 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3655
3656 // If this AST file is a precompiled preamble, then set the
3657 // preamble file ID of the source manager to the file source file
3658 // from which the preamble was built.
3659 if (Type == MK_Preamble) {
3660 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3661 } else if (Type == MK_MainFile) {
3662 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3663 }
3664 }
3665
3666 // For any Objective-C class definitions we have already loaded, make sure
3667 // that we load any additional categories.
3668 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3669 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3670 ObjCClassesLoaded[I],
3671 PreviousGeneration);
3672 }
Douglas Gregore060e572013-01-25 01:03:03 +00003673
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003674 if (PP.getHeaderSearchInfo()
3675 .getHeaderSearchOpts()
3676 .ModulesValidateOncePerBuildSession) {
3677 // Now we are certain that the module and all modules it depends on are
3678 // up to date. Create or update timestamp files for modules that are
3679 // located in the module cache (not for PCH files that could be anywhere
3680 // in the filesystem).
3681 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3682 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003683 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003684 updateModuleTimestamp(*M.Mod);
3685 }
3686 }
3687 }
3688
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 return Success;
3690}
3691
Ben Langmuir487ea142014-10-23 18:05:36 +00003692static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3693
Ben Langmuir70a1b812015-03-24 04:43:52 +00003694/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3695static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3696 return Stream.Read(8) == 'C' &&
3697 Stream.Read(8) == 'P' &&
3698 Stream.Read(8) == 'C' &&
3699 Stream.Read(8) == 'H';
3700}
3701
Richard Smith0f99d6a2015-08-09 08:48:41 +00003702static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3703 switch (Kind) {
3704 case MK_PCH:
3705 return 0; // PCH
3706 case MK_ImplicitModule:
3707 case MK_ExplicitModule:
3708 return 1; // module
3709 case MK_MainFile:
3710 case MK_Preamble:
3711 return 2; // main source file
3712 }
3713 llvm_unreachable("unknown module kind");
3714}
3715
Guy Benyei11169dd2012-12-18 14:30:41 +00003716ASTReader::ASTReadResult
3717ASTReader::ReadASTCore(StringRef FileName,
3718 ModuleKind Type,
3719 SourceLocation ImportLoc,
3720 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003721 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003722 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003723 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 unsigned ClientLoadCapabilities) {
3725 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003727 ModuleManager::AddModuleResult AddResult
3728 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003729 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003730 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003731 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003732
Douglas Gregor7029ce12013-03-19 00:28:20 +00003733 switch (AddResult) {
3734 case ModuleManager::AlreadyLoaded:
3735 return Success;
3736
3737 case ModuleManager::NewlyLoaded:
3738 // Load module file below.
3739 break;
3740
3741 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003742 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003743 // it.
3744 if (ClientLoadCapabilities & ARR_Missing)
3745 return Missing;
3746
3747 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003748 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3749 << FileName << ErrorStr.empty()
3750 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003751 return Failure;
3752
3753 case ModuleManager::OutOfDate:
3754 // We couldn't load the module file because it is out-of-date. If the
3755 // client can handle out-of-date, return it.
3756 if (ClientLoadCapabilities & ARR_OutOfDate)
3757 return OutOfDate;
3758
3759 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003760 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3761 << FileName << ErrorStr.empty()
3762 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003763 return Failure;
3764 }
3765
Douglas Gregor7029ce12013-03-19 00:28:20 +00003766 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003767
3768 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3769 // module?
3770 if (FileName != "-") {
3771 CurrentDir = llvm::sys::path::parent_path(FileName);
3772 if (CurrentDir.empty()) CurrentDir = ".";
3773 }
3774
3775 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003776 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003777 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003778 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003779 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3780
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003782 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003783 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3784 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 return Failure;
3786 }
3787
3788 // This is used for compatibility with older PCH formats.
3789 bool HaveReadControlBlock = false;
Chris Lattnerefa77172013-01-20 00:00:22 +00003790 while (1) {
3791 llvm::BitstreamEntry Entry = Stream.advance();
3792
3793 switch (Entry.Kind) {
3794 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003795 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003796 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 Error("invalid record at top-level of AST file");
3798 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003799
3800 case llvm::BitstreamEntry::SubBlock:
3801 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 }
3803
Chris Lattnerefa77172013-01-20 00:00:22 +00003804 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003805 case CONTROL_BLOCK_ID:
3806 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003807 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003809 // Check that we didn't try to load a non-module AST file as a module.
3810 //
3811 // FIXME: Should we also perform the converse check? Loading a module as
3812 // a PCH file sort of works, but it's a bit wonky.
3813 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3814 F.ModuleName.empty()) {
3815 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3816 if (Result != OutOfDate ||
3817 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3818 Diag(diag::err_module_file_not_module) << FileName;
3819 return Result;
3820 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 break;
3822
3823 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003824 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 case OutOfDate: return OutOfDate;
3826 case VersionMismatch: return VersionMismatch;
3827 case ConfigurationMismatch: return ConfigurationMismatch;
3828 case HadErrors: return HadErrors;
3829 }
3830 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003831
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 case AST_BLOCK_ID:
3833 if (!HaveReadControlBlock) {
3834 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003835 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 return VersionMismatch;
3837 }
3838
3839 // Record that we've loaded this module.
3840 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3841 return Success;
3842
3843 default:
3844 if (Stream.SkipBlock()) {
3845 Error("malformed block record in AST file");
3846 return Failure;
3847 }
3848 break;
3849 }
3850 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003851
3852 return Success;
3853}
3854
3855/// Parse a record and blob containing module file extension metadata.
3856static bool parseModuleFileExtensionMetadata(
3857 const SmallVectorImpl<uint64_t> &Record,
3858 StringRef Blob,
3859 ModuleFileExtensionMetadata &Metadata) {
3860 if (Record.size() < 4) return true;
3861
3862 Metadata.MajorVersion = Record[0];
3863 Metadata.MinorVersion = Record[1];
3864
3865 unsigned BlockNameLen = Record[2];
3866 unsigned UserInfoLen = Record[3];
3867
3868 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
3869
3870 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
3871 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
3872 Blob.data() + BlockNameLen + UserInfoLen);
3873 return false;
3874}
3875
3876ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
3877 BitstreamCursor &Stream = F.Stream;
3878
3879 RecordData Record;
3880 while (true) {
3881 llvm::BitstreamEntry Entry = Stream.advance();
3882 switch (Entry.Kind) {
3883 case llvm::BitstreamEntry::SubBlock:
3884 if (Stream.SkipBlock())
3885 return Failure;
3886
3887 continue;
3888
3889 case llvm::BitstreamEntry::EndBlock:
3890 return Success;
3891
3892 case llvm::BitstreamEntry::Error:
3893 return HadErrors;
3894
3895 case llvm::BitstreamEntry::Record:
3896 break;
3897 }
3898
3899 Record.clear();
3900 StringRef Blob;
3901 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3902 switch (RecCode) {
3903 case EXTENSION_METADATA: {
3904 ModuleFileExtensionMetadata Metadata;
3905 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
3906 return Failure;
3907
3908 // Find a module file extension with this block name.
3909 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
3910 if (Known == ModuleFileExtensions.end()) break;
3911
3912 // Form a reader.
3913 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
3914 F, Stream)) {
3915 F.ExtensionReaders.push_back(std::move(Reader));
3916 }
3917
3918 break;
3919 }
3920 }
3921 }
3922
3923 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924}
3925
Richard Smitha7e2cc62015-05-01 01:53:09 +00003926void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 // If there's a listener, notify them that we "read" the translation unit.
3928 if (DeserializationListener)
3929 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3930 Context.getTranslationUnitDecl());
3931
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 // FIXME: Find a better way to deal with collisions between these
3933 // built-in types. Right now, we just ignore the problem.
3934
3935 // Load the special types.
3936 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3937 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3938 if (!Context.CFConstantStringTypeDecl)
3939 Context.setCFConstantStringType(GetType(String));
3940 }
3941
3942 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3943 QualType FileType = GetType(File);
3944 if (FileType.isNull()) {
3945 Error("FILE type is NULL");
3946 return;
3947 }
3948
3949 if (!Context.FILEDecl) {
3950 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3951 Context.setFILEDecl(Typedef->getDecl());
3952 else {
3953 const TagType *Tag = FileType->getAs<TagType>();
3954 if (!Tag) {
3955 Error("Invalid FILE type in AST file");
3956 return;
3957 }
3958 Context.setFILEDecl(Tag->getDecl());
3959 }
3960 }
3961 }
3962
3963 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3964 QualType Jmp_bufType = GetType(Jmp_buf);
3965 if (Jmp_bufType.isNull()) {
3966 Error("jmp_buf type is NULL");
3967 return;
3968 }
3969
3970 if (!Context.jmp_bufDecl) {
3971 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3972 Context.setjmp_bufDecl(Typedef->getDecl());
3973 else {
3974 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3975 if (!Tag) {
3976 Error("Invalid jmp_buf type in AST file");
3977 return;
3978 }
3979 Context.setjmp_bufDecl(Tag->getDecl());
3980 }
3981 }
3982 }
3983
3984 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3985 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3986 if (Sigjmp_bufType.isNull()) {
3987 Error("sigjmp_buf type is NULL");
3988 return;
3989 }
3990
3991 if (!Context.sigjmp_bufDecl) {
3992 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3993 Context.setsigjmp_bufDecl(Typedef->getDecl());
3994 else {
3995 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3996 assert(Tag && "Invalid sigjmp_buf type in AST file");
3997 Context.setsigjmp_bufDecl(Tag->getDecl());
3998 }
3999 }
4000 }
4001
4002 if (unsigned ObjCIdRedef
4003 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4004 if (Context.ObjCIdRedefinitionType.isNull())
4005 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4006 }
4007
4008 if (unsigned ObjCClassRedef
4009 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4010 if (Context.ObjCClassRedefinitionType.isNull())
4011 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4012 }
4013
4014 if (unsigned ObjCSelRedef
4015 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4016 if (Context.ObjCSelRedefinitionType.isNull())
4017 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4018 }
4019
4020 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4021 QualType Ucontext_tType = GetType(Ucontext_t);
4022 if (Ucontext_tType.isNull()) {
4023 Error("ucontext_t type is NULL");
4024 return;
4025 }
4026
4027 if (!Context.ucontext_tDecl) {
4028 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4029 Context.setucontext_tDecl(Typedef->getDecl());
4030 else {
4031 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4032 assert(Tag && "Invalid ucontext_t type in AST file");
4033 Context.setucontext_tDecl(Tag->getDecl());
4034 }
4035 }
4036 }
4037 }
4038
4039 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4040
4041 // If there were any CUDA special declarations, deserialize them.
4042 if (!CUDASpecialDeclRefs.empty()) {
4043 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4044 Context.setcudaConfigureCallDecl(
4045 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4046 }
Richard Smith56be7542014-03-21 00:33:59 +00004047
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004049 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004050 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004051 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004052 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004053 /*ImportLoc=*/Import.ImportLoc);
4054 PP.makeModuleVisible(Imported, Import.ImportLoc);
4055 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 }
4057 ImportedModules.clear();
4058}
4059
4060void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004061 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004062}
4063
Ben Langmuir70a1b812015-03-24 04:43:52 +00004064/// \brief Reads and return the signature record from \p StreamFile's control
4065/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004066static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4067 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004068 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004069 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004070
4071 // Scan for the CONTROL_BLOCK_ID block.
4072 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4073 return 0;
4074
4075 // Scan for SIGNATURE inside the control block.
4076 ASTReader::RecordData Record;
4077 while (1) {
4078 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4079 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4080 Entry.Kind != llvm::BitstreamEntry::Record)
4081 return 0;
4082
4083 Record.clear();
4084 StringRef Blob;
4085 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4086 return Record[0];
4087 }
4088}
4089
Guy Benyei11169dd2012-12-18 14:30:41 +00004090/// \brief Retrieve the name of the original source file name
4091/// directly from the AST file, without actually loading the AST
4092/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004093std::string ASTReader::getOriginalSourceFile(
4094 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004095 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004097 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004099 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4100 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 return std::string();
4102 }
4103
4104 // Initialize the stream
4105 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004106 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004107 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
4109 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004110 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4112 return std::string();
4113 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114
Chris Lattnere7b154b2013-01-19 21:39:22 +00004115 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004116 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4118 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004119 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004120
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004121 // Scan for ORIGINAL_FILE inside the control block.
4122 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004123 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004124 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004125 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4126 return std::string();
4127
4128 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4129 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4130 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004131 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004132
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004134 StringRef Blob;
4135 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4136 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004138}
4139
4140namespace {
4141 class SimplePCHValidator : public ASTReaderListener {
4142 const LangOptions &ExistingLangOpts;
4143 const TargetOptions &ExistingTargetOpts;
4144 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004145 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004147
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 public:
4149 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4150 const TargetOptions &ExistingTargetOpts,
4151 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004152 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 FileManager &FileMgr)
4154 : ExistingLangOpts(ExistingLangOpts),
4155 ExistingTargetOpts(ExistingTargetOpts),
4156 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004157 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 FileMgr(FileMgr)
4159 {
4160 }
4161
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004162 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4163 bool AllowCompatibleDifferences) override {
4164 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4165 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004167 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4168 bool AllowCompatibleDifferences) override {
4169 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4170 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004172 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4173 StringRef SpecificModuleCachePath,
4174 bool Complain) override {
4175 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4176 ExistingModuleCachePath,
4177 nullptr, ExistingLangOpts);
4178 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004179 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4180 bool Complain,
4181 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004182 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004183 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 }
4185 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004186}
Guy Benyei11169dd2012-12-18 14:30:41 +00004187
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004188bool ASTReader::readASTFileControlBlock(
4189 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004190 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004191 bool FindModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004192 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004194 // FIXME: This allows use of the VFS; we do not allow use of the
4195 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004196 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 if (!Buffer) {
4198 return true;
4199 }
4200
4201 // Initialize the stream
4202 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004203 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004204 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004205
4206 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004207 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004209
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004211 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004212 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004213
4214 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004215 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004216 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004217 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004218
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004220 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004221 bool DoneWithControlBlock = false;
4222 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004223 llvm::BitstreamEntry Entry = Stream.advance();
4224
4225 switch (Entry.Kind) {
4226 case llvm::BitstreamEntry::SubBlock: {
4227 switch (Entry.ID) {
4228 case OPTIONS_BLOCK_ID: {
4229 std::string IgnoredSuggestedPredefines;
4230 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4231 /*AllowCompatibleConfigurationMismatch*/ false,
4232 Listener, IgnoredSuggestedPredefines) != Success)
4233 return true;
4234 break;
4235 }
4236
4237 case INPUT_FILES_BLOCK_ID:
4238 InputFilesCursor = Stream;
4239 if (Stream.SkipBlock() ||
4240 (NeedsInputFiles &&
4241 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4242 return true;
4243 break;
4244
4245 default:
4246 if (Stream.SkipBlock())
4247 return true;
4248 break;
4249 }
4250
4251 continue;
4252 }
4253
4254 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004255 DoneWithControlBlock = true;
4256 break;
Richard Smith0516b182015-09-08 19:40:14 +00004257
4258 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004260
4261 case llvm::BitstreamEntry::Record:
4262 break;
4263 }
4264
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004265 if (DoneWithControlBlock) break;
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004268 StringRef Blob;
4269 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 switch ((ControlRecordTypes)RecCode) {
4271 case METADATA: {
4272 if (Record[0] != VERSION_MAJOR)
4273 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004275 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004277
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 break;
4279 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004280 case MODULE_NAME:
4281 Listener.ReadModuleName(Blob);
4282 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004283 case MODULE_DIRECTORY:
4284 ModuleDir = Blob;
4285 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004286 case MODULE_MAP_FILE: {
4287 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004288 auto Path = ReadString(Record, Idx);
4289 ResolveImportedPath(Path, ModuleDir);
4290 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004291 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004292 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004293 case INPUT_FILE_OFFSETS: {
4294 if (!NeedsInputFiles)
4295 break;
4296
4297 unsigned NumInputFiles = Record[0];
4298 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004299 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004300 for (unsigned I = 0; I != NumInputFiles; ++I) {
4301 // Go find this input file.
4302 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004303
4304 if (isSystemFile && !NeedsSystemInputFiles)
4305 break; // the rest are system input files
4306
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004307 BitstreamCursor &Cursor = InputFilesCursor;
4308 SavedStreamPosition SavedPosition(Cursor);
4309 Cursor.JumpToBit(InputFileOffs[I]);
4310
4311 unsigned Code = Cursor.ReadCode();
4312 RecordData Record;
4313 StringRef Blob;
4314 bool shouldContinue = false;
4315 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4316 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004317 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004318 std::string Filename = Blob;
4319 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004320 shouldContinue = Listener.visitInputFile(
4321 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004322 break;
4323 }
4324 if (!shouldContinue)
4325 break;
4326 }
4327 break;
4328 }
4329
Richard Smithd4b230b2014-10-27 23:01:16 +00004330 case IMPORTS: {
4331 if (!NeedsImports)
4332 break;
4333
4334 unsigned Idx = 0, N = Record.size();
4335 while (Idx < N) {
4336 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004337 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004338 std::string Filename = ReadString(Record, Idx);
4339 ResolveImportedPath(Filename, ModuleDir);
4340 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004341 }
4342 break;
4343 }
4344
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004345 default:
4346 // No other validation to perform.
4347 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 }
4349 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004350
4351 // Look for module file extension blocks, if requested.
4352 if (FindModuleFileExtensions) {
4353 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4354 bool DoneWithExtensionBlock = false;
4355 while (!DoneWithExtensionBlock) {
4356 llvm::BitstreamEntry Entry = Stream.advance();
4357
4358 switch (Entry.Kind) {
4359 case llvm::BitstreamEntry::SubBlock:
4360 if (Stream.SkipBlock())
4361 return true;
4362
4363 continue;
4364
4365 case llvm::BitstreamEntry::EndBlock:
4366 DoneWithExtensionBlock = true;
4367 continue;
4368
4369 case llvm::BitstreamEntry::Error:
4370 return true;
4371
4372 case llvm::BitstreamEntry::Record:
4373 break;
4374 }
4375
4376 Record.clear();
4377 StringRef Blob;
4378 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4379 switch (RecCode) {
4380 case EXTENSION_METADATA: {
4381 ModuleFileExtensionMetadata Metadata;
4382 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4383 return true;
4384
4385 Listener.readModuleFileExtension(Metadata);
4386 break;
4387 }
4388 }
4389 }
4390 }
4391 }
4392
4393 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394}
4395
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004396bool ASTReader::isAcceptableASTFile(
4397 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004398 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004399 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4400 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004401 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4402 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004403 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004404 /*FindModuleFileExtensions=*/false,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004405 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004406}
4407
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408ASTReader::ASTReadResult
4409ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 // Enter the submodule block.
4411 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4412 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004413 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 }
4415
4416 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4417 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004418 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 RecordData Record;
4420 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004421 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4422
4423 switch (Entry.Kind) {
4424 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4425 case llvm::BitstreamEntry::Error:
4426 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004427 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004428 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004429 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004430 case llvm::BitstreamEntry::Record:
4431 // The interesting case.
4432 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004434
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004436 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004438 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4439
4440 if ((Kind == SUBMODULE_METADATA) != First) {
4441 Error("submodule metadata record should be at beginning of block");
4442 return Failure;
4443 }
4444 First = false;
4445
4446 // Submodule information is only valid if we have a current module.
4447 // FIXME: Should we error on these cases?
4448 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4449 Kind != SUBMODULE_DEFINITION)
4450 continue;
4451
4452 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 default: // Default behavior: ignore.
4454 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455
Richard Smith03478d92014-10-23 22:12:14 +00004456 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004457 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004459 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
Richard Smith03478d92014-10-23 22:12:14 +00004461
Chris Lattner0e6c9402013-01-20 02:38:54 +00004462 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004463 unsigned Idx = 0;
4464 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4465 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4466 bool IsFramework = Record[Idx++];
4467 bool IsExplicit = Record[Idx++];
4468 bool IsSystem = Record[Idx++];
4469 bool IsExternC = Record[Idx++];
4470 bool InferSubmodules = Record[Idx++];
4471 bool InferExplicitSubmodules = Record[Idx++];
4472 bool InferExportWildcard = Record[Idx++];
4473 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004474
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004475 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004476 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004478
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 // Retrieve this (sub)module from the module map, creating it if
4480 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004481 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004483
4484 // FIXME: set the definition loc for CurrentModule, or call
4485 // ModMap.setInferredModuleAllowedBy()
4486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4488 if (GlobalIndex >= SubmodulesLoaded.size() ||
4489 SubmodulesLoaded[GlobalIndex]) {
4490 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004491 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004493
Douglas Gregor7029ce12013-03-19 00:28:20 +00004494 if (!ParentModule) {
4495 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4496 if (CurFile != F.File) {
4497 if (!Diags.isDiagnosticInFlight()) {
4498 Diag(diag::err_module_file_conflict)
4499 << CurrentModule->getTopLevelModuleName()
4500 << CurFile->getName()
4501 << F.File->getName();
4502 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004503 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004504 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004505 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004506
4507 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004508 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004509
Adrian Prantl15bcf702015-06-30 17:39:43 +00004510 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 CurrentModule->IsFromModuleFile = true;
4512 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004513 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 CurrentModule->InferSubmodules = InferSubmodules;
4515 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4516 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004517 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 if (DeserializationListener)
4519 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4520
4521 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004522
Douglas Gregorfb912652013-03-20 21:10:35 +00004523 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004524 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004525 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004526 CurrentModule->UnresolvedConflicts.clear();
4527 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 break;
4529 }
4530
4531 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004532 std::string Filename = Blob;
4533 ResolveImportedPath(F, Filename);
4534 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004536 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4537 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004538 // This can be a spurious difference caused by changing the VFS to
4539 // point to a different copy of the file, and it is too late to
4540 // to rebuild safely.
4541 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4542 // after input file validation only real problems would remain and we
4543 // could just error. For now, assume it's okay.
4544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 }
4546 }
4547 break;
4548 }
4549
Richard Smith202210b2014-10-24 20:23:01 +00004550 case SUBMODULE_HEADER:
4551 case SUBMODULE_EXCLUDED_HEADER:
4552 case SUBMODULE_PRIVATE_HEADER:
4553 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004554 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4555 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004556 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004557
Richard Smith202210b2014-10-24 20:23:01 +00004558 case SUBMODULE_TEXTUAL_HEADER:
4559 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4560 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4561 // them here.
4562 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004563
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004565 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 break;
4567 }
4568
4569 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004570 std::string Dirname = Blob;
4571 ResolveImportedPath(F, Dirname);
4572 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004574 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4575 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004576 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4577 Error("mismatched umbrella directories in submodule");
4578 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580 }
4581 break;
4582 }
4583
4584 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 F.BaseSubmoduleID = getTotalNumSubmodules();
4586 F.LocalNumSubmodules = Record[0];
4587 unsigned LocalBaseSubmoduleID = Record[1];
4588 if (F.LocalNumSubmodules > 0) {
4589 // Introduce the global -> local mapping for submodules within this
4590 // module.
4591 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4592
4593 // Introduce the local -> global mapping for submodules within this
4594 // module.
4595 F.SubmoduleRemap.insertOrReplace(
4596 std::make_pair(LocalBaseSubmoduleID,
4597 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004598
Ben Langmuir52ca6782014-10-20 16:27:32 +00004599 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 break;
4602 }
4603
4604 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004606 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 Unresolved.File = &F;
4608 Unresolved.Mod = CurrentModule;
4609 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004610 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004612 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 }
4614 break;
4615 }
4616
4617 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004619 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 Unresolved.File = &F;
4621 Unresolved.Mod = CurrentModule;
4622 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004623 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004625 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627
4628 // Once we've loaded the set of exports, there's no reason to keep
4629 // the parsed, unresolved exports around.
4630 CurrentModule->UnresolvedExports.clear();
4631 break;
4632 }
4633 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004634 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 Context.getTargetInfo());
4636 break;
4637 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004638
4639 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004640 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004641 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004642 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004643
4644 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004645 CurrentModule->ConfigMacros.push_back(Blob.str());
4646 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004647
4648 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004649 UnresolvedModuleRef Unresolved;
4650 Unresolved.File = &F;
4651 Unresolved.Mod = CurrentModule;
4652 Unresolved.ID = Record[0];
4653 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4654 Unresolved.IsWildcard = false;
4655 Unresolved.String = Blob;
4656 UnresolvedModuleRefs.push_back(Unresolved);
4657 break;
4658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 }
4660 }
4661}
4662
4663/// \brief Parse the record that corresponds to a LangOptions data
4664/// structure.
4665///
4666/// This routine parses the language options from the AST file and then gives
4667/// them to the AST listener if one is set.
4668///
4669/// \returns true if the listener deems the file unacceptable, false otherwise.
4670bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4671 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004672 ASTReaderListener &Listener,
4673 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 LangOptions LangOpts;
4675 unsigned Idx = 0;
4676#define LANGOPT(Name, Bits, Default, Description) \
4677 LangOpts.Name = Record[Idx++];
4678#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4679 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4680#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004681#define SANITIZER(NAME, ID) \
4682 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004683#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004684
Ben Langmuircd98cb72015-06-23 18:20:18 +00004685 for (unsigned N = Record[Idx++]; N; --N)
4686 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4687
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4689 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4690 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004691
Ben Langmuird4a667a2015-06-23 18:20:23 +00004692 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004693
4694 // Comment options.
4695 for (unsigned N = Record[Idx++]; N; --N) {
4696 LangOpts.CommentOpts.BlockCommandNames.push_back(
4697 ReadString(Record, Idx));
4698 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004699 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004700
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004701 return Listener.ReadLanguageOptions(LangOpts, Complain,
4702 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703}
4704
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004705bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4706 ASTReaderListener &Listener,
4707 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 unsigned Idx = 0;
4709 TargetOptions TargetOpts;
4710 TargetOpts.Triple = ReadString(Record, Idx);
4711 TargetOpts.CPU = ReadString(Record, Idx);
4712 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 for (unsigned N = Record[Idx++]; N; --N) {
4714 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4715 }
4716 for (unsigned N = Record[Idx++]; N; --N) {
4717 TargetOpts.Features.push_back(ReadString(Record, Idx));
4718 }
4719
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004720 return Listener.ReadTargetOptions(TargetOpts, Complain,
4721 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004722}
4723
4724bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4725 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004726 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004728#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004729#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004730 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004731#include "clang/Basic/DiagnosticOptions.def"
4732
Richard Smith3be1cb22014-08-07 00:24:21 +00004733 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004734 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004735 for (unsigned N = Record[Idx++]; N; --N)
4736 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004737
4738 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4739}
4740
4741bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4742 ASTReaderListener &Listener) {
4743 FileSystemOptions FSOpts;
4744 unsigned Idx = 0;
4745 FSOpts.WorkingDir = ReadString(Record, Idx);
4746 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4747}
4748
4749bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4750 bool Complain,
4751 ASTReaderListener &Listener) {
4752 HeaderSearchOptions HSOpts;
4753 unsigned Idx = 0;
4754 HSOpts.Sysroot = ReadString(Record, Idx);
4755
4756 // Include entries.
4757 for (unsigned N = Record[Idx++]; N; --N) {
4758 std::string Path = ReadString(Record, Idx);
4759 frontend::IncludeDirGroup Group
4760 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 bool IsFramework = Record[Idx++];
4762 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004763 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4764 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 }
4766
4767 // System header prefixes.
4768 for (unsigned N = Record[Idx++]; N; --N) {
4769 std::string Prefix = ReadString(Record, Idx);
4770 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004771 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 }
4773
4774 HSOpts.ResourceDir = ReadString(Record, Idx);
4775 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004776 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 HSOpts.DisableModuleHash = Record[Idx++];
4778 HSOpts.UseBuiltinIncludes = Record[Idx++];
4779 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4780 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4781 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004782 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004783
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004784 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4785 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004786}
4787
4788bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4789 bool Complain,
4790 ASTReaderListener &Listener,
4791 std::string &SuggestedPredefines) {
4792 PreprocessorOptions PPOpts;
4793 unsigned Idx = 0;
4794
4795 // Macro definitions/undefs
4796 for (unsigned N = Record[Idx++]; N; --N) {
4797 std::string Macro = ReadString(Record, Idx);
4798 bool IsUndef = Record[Idx++];
4799 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4800 }
4801
4802 // Includes
4803 for (unsigned N = Record[Idx++]; N; --N) {
4804 PPOpts.Includes.push_back(ReadString(Record, Idx));
4805 }
4806
4807 // Macro Includes
4808 for (unsigned N = Record[Idx++]; N; --N) {
4809 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4810 }
4811
4812 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004813 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4815 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4816 PPOpts.ObjCXXARCStandardLibrary =
4817 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4818 SuggestedPredefines.clear();
4819 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4820 SuggestedPredefines);
4821}
4822
4823std::pair<ModuleFile *, unsigned>
4824ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4825 GlobalPreprocessedEntityMapType::iterator
4826 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4827 assert(I != GlobalPreprocessedEntityMap.end() &&
4828 "Corrupted global preprocessed entity map");
4829 ModuleFile *M = I->second;
4830 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4831 return std::make_pair(M, LocalIndex);
4832}
4833
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004834llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004835ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4836 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4837 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4838 Mod.NumPreprocessedEntities);
4839
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004840 return llvm::make_range(PreprocessingRecord::iterator(),
4841 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004842}
4843
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004844llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004845ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004846 return llvm::make_range(
4847 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4848 ModuleDeclIterator(this, &Mod,
4849 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004850}
4851
4852PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4853 PreprocessedEntityID PPID = Index+1;
4854 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4855 ModuleFile &M = *PPInfo.first;
4856 unsigned LocalIndex = PPInfo.second;
4857 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4858
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 if (!PP.getPreprocessingRecord()) {
4860 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004861 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 }
4863
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004864 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4865 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4866
4867 llvm::BitstreamEntry Entry =
4868 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4869 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004870 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004871
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 // Read the record.
4873 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4874 ReadSourceLocation(M, PPOffs.End));
4875 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004876 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 RecordData Record;
4878 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004879 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4880 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 switch (RecType) {
4882 case PPD_MACRO_EXPANSION: {
4883 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004884 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004885 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 if (isBuiltin)
4887 Name = getLocalIdentifier(M, Record[1]);
4888 else {
Richard Smith66a81862015-05-04 02:25:31 +00004889 PreprocessedEntityID GlobalID =
4890 getGlobalPreprocessedEntityID(M, Record[1]);
4891 Def = cast<MacroDefinitionRecord>(
4892 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 }
4894
4895 MacroExpansion *ME;
4896 if (isBuiltin)
4897 ME = new (PPRec) MacroExpansion(Name, Range);
4898 else
4899 ME = new (PPRec) MacroExpansion(Def, Range);
4900
4901 return ME;
4902 }
4903
4904 case PPD_MACRO_DEFINITION: {
4905 // Decode the identifier info and then check again; if the macro is
4906 // still defined and associated with the identifier,
4907 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004908 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004909
4910 if (DeserializationListener)
4911 DeserializationListener->MacroDefinitionRead(PPID, MD);
4912
4913 return MD;
4914 }
4915
4916 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004917 const char *FullFileNameStart = Blob.data() + Record[0];
4918 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004919 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 if (!FullFileName.empty())
4921 File = PP.getFileManager().getFile(FullFileName);
4922
4923 // FIXME: Stable encoding
4924 InclusionDirective::InclusionKind Kind
4925 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4926 InclusionDirective *ID
4927 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004928 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 Record[1], Record[3],
4930 File,
4931 Range);
4932 return ID;
4933 }
4934 }
4935
4936 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4937}
4938
4939/// \brief \arg SLocMapI points at a chunk of a module that contains no
4940/// preprocessed entities or the entities it contains are not the ones we are
4941/// looking for. Find the next module that contains entities and return the ID
4942/// of the first entry.
4943PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4944 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4945 ++SLocMapI;
4946 for (GlobalSLocOffsetMapType::const_iterator
4947 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4948 ModuleFile &M = *SLocMapI->second;
4949 if (M.NumPreprocessedEntities)
4950 return M.BasePreprocessedEntityID;
4951 }
4952
4953 return getTotalNumPreprocessedEntities();
4954}
4955
4956namespace {
4957
4958template <unsigned PPEntityOffset::*PPLoc>
4959struct PPEntityComp {
4960 const ASTReader &Reader;
4961 ModuleFile &M;
4962
4963 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4964
4965 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4966 SourceLocation LHS = getLoc(L);
4967 SourceLocation RHS = getLoc(R);
4968 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4969 }
4970
4971 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4972 SourceLocation LHS = getLoc(L);
4973 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4974 }
4975
4976 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4977 SourceLocation RHS = getLoc(R);
4978 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4979 }
4980
4981 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4982 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4983 }
4984};
4985
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004986}
Guy Benyei11169dd2012-12-18 14:30:41 +00004987
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004988PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4989 bool EndsAfter) const {
4990 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 return getTotalNumPreprocessedEntities();
4992
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004993 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4994 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4996 "Corrupted global sloc offset map");
4997
4998 if (SLocMapI->second->NumPreprocessedEntities == 0)
4999 return findNextPreprocessedEntity(SLocMapI);
5000
5001 ModuleFile &M = *SLocMapI->second;
5002 typedef const PPEntityOffset *pp_iterator;
5003 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5004 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5005
5006 size_t Count = M.NumPreprocessedEntities;
5007 size_t Half;
5008 pp_iterator First = pp_begin;
5009 pp_iterator PPI;
5010
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005011 if (EndsAfter) {
5012 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5013 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5014 } else {
5015 // Do a binary search manually instead of using std::lower_bound because
5016 // The end locations of entities may be unordered (when a macro expansion
5017 // is inside another macro argument), but for this case it is not important
5018 // whether we get the first macro expansion or its containing macro.
5019 while (Count > 0) {
5020 Half = Count / 2;
5021 PPI = First;
5022 std::advance(PPI, Half);
5023 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5024 Loc)) {
5025 First = PPI;
5026 ++First;
5027 Count = Count - Half - 1;
5028 } else
5029 Count = Half;
5030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005031 }
5032
5033 if (PPI == pp_end)
5034 return findNextPreprocessedEntity(SLocMapI);
5035
5036 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5037}
5038
Guy Benyei11169dd2012-12-18 14:30:41 +00005039/// \brief Returns a pair of [Begin, End) indices of preallocated
5040/// preprocessed entities that \arg Range encompasses.
5041std::pair<unsigned, unsigned>
5042 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5043 if (Range.isInvalid())
5044 return std::make_pair(0,0);
5045 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5046
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005047 PreprocessedEntityID BeginID =
5048 findPreprocessedEntity(Range.getBegin(), false);
5049 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 return std::make_pair(BeginID, EndID);
5051}
5052
5053/// \brief Optionally returns true or false if the preallocated preprocessed
5054/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005055Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 FileID FID) {
5057 if (FID.isInvalid())
5058 return false;
5059
5060 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5061 ModuleFile &M = *PPInfo.first;
5062 unsigned LocalIndex = PPInfo.second;
5063 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5064
5065 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5066 if (Loc.isInvalid())
5067 return false;
5068
5069 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5070 return true;
5071 else
5072 return false;
5073}
5074
5075namespace {
5076 /// \brief Visitor used to search for information about a header file.
5077 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 const FileEntry *FE;
5079
David Blaikie05785d12013-02-20 22:23:23 +00005080 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005081
5082 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005083 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5084 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005085
5086 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005087 HeaderFileInfoLookupTable *Table
5088 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5089 if (!Table)
5090 return false;
5091
5092 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005093 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 if (Pos == Table->end())
5095 return false;
5096
Richard Smithbdf2d932015-07-30 03:37:16 +00005097 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005098 return true;
5099 }
5100
David Blaikie05785d12013-02-20 22:23:23 +00005101 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005103}
Guy Benyei11169dd2012-12-18 14:30:41 +00005104
5105HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005106 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005107 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005108 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005110
5111 return HeaderFileInfo();
5112}
5113
5114void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5115 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005116 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5118 ModuleFile &F = *(*I);
5119 unsigned Idx = 0;
5120 DiagStates.clear();
5121 assert(!Diag.DiagStates.empty());
5122 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5123 while (Idx < F.PragmaDiagMappings.size()) {
5124 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5125 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5126 if (DiagStateID != 0) {
5127 Diag.DiagStatePoints.push_back(
5128 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5129 FullSourceLoc(Loc, SourceMgr)));
5130 continue;
5131 }
5132
5133 assert(DiagStateID == 0);
5134 // A new DiagState was created here.
5135 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5136 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5137 DiagStates.push_back(NewState);
5138 Diag.DiagStatePoints.push_back(
5139 DiagnosticsEngine::DiagStatePoint(NewState,
5140 FullSourceLoc(Loc, SourceMgr)));
5141 while (1) {
5142 assert(Idx < F.PragmaDiagMappings.size() &&
5143 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5144 if (Idx >= F.PragmaDiagMappings.size()) {
5145 break; // Something is messed up but at least avoid infinite loop in
5146 // release build.
5147 }
5148 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5149 if (DiagID == (unsigned)-1) {
5150 break; // no more diag/map pairs for this location.
5151 }
Alp Tokerc726c362014-06-10 09:31:37 +00005152 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5153 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5154 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 }
5156 }
5157 }
5158}
5159
5160/// \brief Get the correct cursor and offset for loading a type.
5161ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5162 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5163 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5164 ModuleFile *M = I->second;
5165 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5166}
5167
5168/// \brief Read and return the type with the given index..
5169///
5170/// The index is the type ID, shifted and minus the number of predefs. This
5171/// routine actually reads the record corresponding to the type at the given
5172/// location. It is a helper routine for GetType, which deals with reading type
5173/// IDs.
5174QualType ASTReader::readTypeRecord(unsigned Index) {
5175 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005176 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005177
5178 // Keep track of where we are in the stream, then jump back there
5179 // after reading this type.
5180 SavedStreamPosition SavedPosition(DeclsCursor);
5181
5182 ReadingKindTracker ReadingKind(Read_Type, *this);
5183
5184 // Note that we are loading a type record.
5185 Deserializing AType(this);
5186
5187 unsigned Idx = 0;
5188 DeclsCursor.JumpToBit(Loc.Offset);
5189 RecordData Record;
5190 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005191 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 case TYPE_EXT_QUAL: {
5193 if (Record.size() != 2) {
5194 Error("Incorrect encoding of extended qualifier type");
5195 return QualType();
5196 }
5197 QualType Base = readType(*Loc.F, Record, Idx);
5198 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5199 return Context.getQualifiedType(Base, Quals);
5200 }
5201
5202 case TYPE_COMPLEX: {
5203 if (Record.size() != 1) {
5204 Error("Incorrect encoding of complex type");
5205 return QualType();
5206 }
5207 QualType ElemType = readType(*Loc.F, Record, Idx);
5208 return Context.getComplexType(ElemType);
5209 }
5210
5211 case TYPE_POINTER: {
5212 if (Record.size() != 1) {
5213 Error("Incorrect encoding of pointer type");
5214 return QualType();
5215 }
5216 QualType PointeeType = readType(*Loc.F, Record, Idx);
5217 return Context.getPointerType(PointeeType);
5218 }
5219
Reid Kleckner8a365022013-06-24 17:51:48 +00005220 case TYPE_DECAYED: {
5221 if (Record.size() != 1) {
5222 Error("Incorrect encoding of decayed type");
5223 return QualType();
5224 }
5225 QualType OriginalType = readType(*Loc.F, Record, Idx);
5226 QualType DT = Context.getAdjustedParameterType(OriginalType);
5227 if (!isa<DecayedType>(DT))
5228 Error("Decayed type does not decay");
5229 return DT;
5230 }
5231
Reid Kleckner0503a872013-12-05 01:23:43 +00005232 case TYPE_ADJUSTED: {
5233 if (Record.size() != 2) {
5234 Error("Incorrect encoding of adjusted type");
5235 return QualType();
5236 }
5237 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5238 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5239 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5240 }
5241
Guy Benyei11169dd2012-12-18 14:30:41 +00005242 case TYPE_BLOCK_POINTER: {
5243 if (Record.size() != 1) {
5244 Error("Incorrect encoding of block pointer type");
5245 return QualType();
5246 }
5247 QualType PointeeType = readType(*Loc.F, Record, Idx);
5248 return Context.getBlockPointerType(PointeeType);
5249 }
5250
5251 case TYPE_LVALUE_REFERENCE: {
5252 if (Record.size() != 2) {
5253 Error("Incorrect encoding of lvalue reference type");
5254 return QualType();
5255 }
5256 QualType PointeeType = readType(*Loc.F, Record, Idx);
5257 return Context.getLValueReferenceType(PointeeType, Record[1]);
5258 }
5259
5260 case TYPE_RVALUE_REFERENCE: {
5261 if (Record.size() != 1) {
5262 Error("Incorrect encoding of rvalue reference type");
5263 return QualType();
5264 }
5265 QualType PointeeType = readType(*Loc.F, Record, Idx);
5266 return Context.getRValueReferenceType(PointeeType);
5267 }
5268
5269 case TYPE_MEMBER_POINTER: {
5270 if (Record.size() != 2) {
5271 Error("Incorrect encoding of member pointer type");
5272 return QualType();
5273 }
5274 QualType PointeeType = readType(*Loc.F, Record, Idx);
5275 QualType ClassType = readType(*Loc.F, Record, Idx);
5276 if (PointeeType.isNull() || ClassType.isNull())
5277 return QualType();
5278
5279 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5280 }
5281
5282 case TYPE_CONSTANT_ARRAY: {
5283 QualType ElementType = readType(*Loc.F, Record, Idx);
5284 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5285 unsigned IndexTypeQuals = Record[2];
5286 unsigned Idx = 3;
5287 llvm::APInt Size = ReadAPInt(Record, Idx);
5288 return Context.getConstantArrayType(ElementType, Size,
5289 ASM, IndexTypeQuals);
5290 }
5291
5292 case TYPE_INCOMPLETE_ARRAY: {
5293 QualType ElementType = readType(*Loc.F, Record, Idx);
5294 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5295 unsigned IndexTypeQuals = Record[2];
5296 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5297 }
5298
5299 case TYPE_VARIABLE_ARRAY: {
5300 QualType ElementType = readType(*Loc.F, Record, Idx);
5301 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5302 unsigned IndexTypeQuals = Record[2];
5303 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5304 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5305 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5306 ASM, IndexTypeQuals,
5307 SourceRange(LBLoc, RBLoc));
5308 }
5309
5310 case TYPE_VECTOR: {
5311 if (Record.size() != 3) {
5312 Error("incorrect encoding of vector type in AST file");
5313 return QualType();
5314 }
5315
5316 QualType ElementType = readType(*Loc.F, Record, Idx);
5317 unsigned NumElements = Record[1];
5318 unsigned VecKind = Record[2];
5319 return Context.getVectorType(ElementType, NumElements,
5320 (VectorType::VectorKind)VecKind);
5321 }
5322
5323 case TYPE_EXT_VECTOR: {
5324 if (Record.size() != 3) {
5325 Error("incorrect encoding of extended vector type in AST file");
5326 return QualType();
5327 }
5328
5329 QualType ElementType = readType(*Loc.F, Record, Idx);
5330 unsigned NumElements = Record[1];
5331 return Context.getExtVectorType(ElementType, NumElements);
5332 }
5333
5334 case TYPE_FUNCTION_NO_PROTO: {
5335 if (Record.size() != 6) {
5336 Error("incorrect encoding of no-proto function type");
5337 return QualType();
5338 }
5339 QualType ResultType = readType(*Loc.F, Record, Idx);
5340 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5341 (CallingConv)Record[4], Record[5]);
5342 return Context.getFunctionNoProtoType(ResultType, Info);
5343 }
5344
5345 case TYPE_FUNCTION_PROTO: {
5346 QualType ResultType = readType(*Loc.F, Record, Idx);
5347
5348 FunctionProtoType::ExtProtoInfo EPI;
5349 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5350 /*hasregparm*/ Record[2],
5351 /*regparm*/ Record[3],
5352 static_cast<CallingConv>(Record[4]),
5353 /*produces*/ Record[5]);
5354
5355 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005356
5357 EPI.Variadic = Record[Idx++];
5358 EPI.HasTrailingReturn = Record[Idx++];
5359 EPI.TypeQuals = Record[Idx++];
5360 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005361 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005362 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005363
5364 unsigned NumParams = Record[Idx++];
5365 SmallVector<QualType, 16> ParamTypes;
5366 for (unsigned I = 0; I != NumParams; ++I)
5367 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5368
Jordan Rose5c382722013-03-08 21:51:21 +00005369 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 }
5371
5372 case TYPE_UNRESOLVED_USING: {
5373 unsigned Idx = 0;
5374 return Context.getTypeDeclType(
5375 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5376 }
5377
5378 case TYPE_TYPEDEF: {
5379 if (Record.size() != 2) {
5380 Error("incorrect encoding of typedef type");
5381 return QualType();
5382 }
5383 unsigned Idx = 0;
5384 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5385 QualType Canonical = readType(*Loc.F, Record, Idx);
5386 if (!Canonical.isNull())
5387 Canonical = Context.getCanonicalType(Canonical);
5388 return Context.getTypedefType(Decl, Canonical);
5389 }
5390
5391 case TYPE_TYPEOF_EXPR:
5392 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5393
5394 case TYPE_TYPEOF: {
5395 if (Record.size() != 1) {
5396 Error("incorrect encoding of typeof(type) in AST file");
5397 return QualType();
5398 }
5399 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5400 return Context.getTypeOfType(UnderlyingType);
5401 }
5402
5403 case TYPE_DECLTYPE: {
5404 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5405 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5406 }
5407
5408 case TYPE_UNARY_TRANSFORM: {
5409 QualType BaseType = readType(*Loc.F, Record, Idx);
5410 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5411 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5412 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5413 }
5414
Richard Smith74aeef52013-04-26 16:15:35 +00005415 case TYPE_AUTO: {
5416 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005417 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005418 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005419 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005421
5422 case TYPE_RECORD: {
5423 if (Record.size() != 2) {
5424 Error("incorrect encoding of record type");
5425 return QualType();
5426 }
5427 unsigned Idx = 0;
5428 bool IsDependent = Record[Idx++];
5429 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5430 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5431 QualType T = Context.getRecordType(RD);
5432 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5433 return T;
5434 }
5435
5436 case TYPE_ENUM: {
5437 if (Record.size() != 2) {
5438 Error("incorrect encoding of enum type");
5439 return QualType();
5440 }
5441 unsigned Idx = 0;
5442 bool IsDependent = Record[Idx++];
5443 QualType T
5444 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5445 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5446 return T;
5447 }
5448
5449 case TYPE_ATTRIBUTED: {
5450 if (Record.size() != 3) {
5451 Error("incorrect encoding of attributed type");
5452 return QualType();
5453 }
5454 QualType modifiedType = readType(*Loc.F, Record, Idx);
5455 QualType equivalentType = readType(*Loc.F, Record, Idx);
5456 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5457 return Context.getAttributedType(kind, modifiedType, equivalentType);
5458 }
5459
5460 case TYPE_PAREN: {
5461 if (Record.size() != 1) {
5462 Error("incorrect encoding of paren type");
5463 return QualType();
5464 }
5465 QualType InnerType = readType(*Loc.F, Record, Idx);
5466 return Context.getParenType(InnerType);
5467 }
5468
5469 case TYPE_PACK_EXPANSION: {
5470 if (Record.size() != 2) {
5471 Error("incorrect encoding of pack expansion type");
5472 return QualType();
5473 }
5474 QualType Pattern = readType(*Loc.F, Record, Idx);
5475 if (Pattern.isNull())
5476 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005477 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005478 if (Record[1])
5479 NumExpansions = Record[1] - 1;
5480 return Context.getPackExpansionType(Pattern, NumExpansions);
5481 }
5482
5483 case TYPE_ELABORATED: {
5484 unsigned Idx = 0;
5485 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5486 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5487 QualType NamedType = readType(*Loc.F, Record, Idx);
5488 return Context.getElaboratedType(Keyword, NNS, NamedType);
5489 }
5490
5491 case TYPE_OBJC_INTERFACE: {
5492 unsigned Idx = 0;
5493 ObjCInterfaceDecl *ItfD
5494 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5495 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5496 }
5497
5498 case TYPE_OBJC_OBJECT: {
5499 unsigned Idx = 0;
5500 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005501 unsigned NumTypeArgs = Record[Idx++];
5502 SmallVector<QualType, 4> TypeArgs;
5503 for (unsigned I = 0; I != NumTypeArgs; ++I)
5504 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005505 unsigned NumProtos = Record[Idx++];
5506 SmallVector<ObjCProtocolDecl*, 4> Protos;
5507 for (unsigned I = 0; I != NumProtos; ++I)
5508 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005509 bool IsKindOf = Record[Idx++];
5510 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 }
5512
5513 case TYPE_OBJC_OBJECT_POINTER: {
5514 unsigned Idx = 0;
5515 QualType Pointee = readType(*Loc.F, Record, Idx);
5516 return Context.getObjCObjectPointerType(Pointee);
5517 }
5518
5519 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5520 unsigned Idx = 0;
5521 QualType Parm = readType(*Loc.F, Record, Idx);
5522 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005523 return Context.getSubstTemplateTypeParmType(
5524 cast<TemplateTypeParmType>(Parm),
5525 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 }
5527
5528 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5529 unsigned Idx = 0;
5530 QualType Parm = readType(*Loc.F, Record, Idx);
5531 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5532 return Context.getSubstTemplateTypeParmPackType(
5533 cast<TemplateTypeParmType>(Parm),
5534 ArgPack);
5535 }
5536
5537 case TYPE_INJECTED_CLASS_NAME: {
5538 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5539 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5540 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5541 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005542 const Type *T = nullptr;
5543 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5544 if (const Type *Existing = DI->getTypeForDecl()) {
5545 T = Existing;
5546 break;
5547 }
5548 }
5549 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005550 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005551 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5552 DI->setTypeForDecl(T);
5553 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005554 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005555 }
5556
5557 case TYPE_TEMPLATE_TYPE_PARM: {
5558 unsigned Idx = 0;
5559 unsigned Depth = Record[Idx++];
5560 unsigned Index = Record[Idx++];
5561 bool Pack = Record[Idx++];
5562 TemplateTypeParmDecl *D
5563 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5564 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5565 }
5566
5567 case TYPE_DEPENDENT_NAME: {
5568 unsigned Idx = 0;
5569 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5570 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005571 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005572 QualType Canon = readType(*Loc.F, Record, Idx);
5573 if (!Canon.isNull())
5574 Canon = Context.getCanonicalType(Canon);
5575 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5576 }
5577
5578 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5579 unsigned Idx = 0;
5580 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5581 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005582 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 unsigned NumArgs = Record[Idx++];
5584 SmallVector<TemplateArgument, 8> Args;
5585 Args.reserve(NumArgs);
5586 while (NumArgs--)
5587 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5588 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5589 Args.size(), Args.data());
5590 }
5591
5592 case TYPE_DEPENDENT_SIZED_ARRAY: {
5593 unsigned Idx = 0;
5594
5595 // ArrayType
5596 QualType ElementType = readType(*Loc.F, Record, Idx);
5597 ArrayType::ArraySizeModifier ASM
5598 = (ArrayType::ArraySizeModifier)Record[Idx++];
5599 unsigned IndexTypeQuals = Record[Idx++];
5600
5601 // DependentSizedArrayType
5602 Expr *NumElts = ReadExpr(*Loc.F);
5603 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5604
5605 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5606 IndexTypeQuals, Brackets);
5607 }
5608
5609 case TYPE_TEMPLATE_SPECIALIZATION: {
5610 unsigned Idx = 0;
5611 bool IsDependent = Record[Idx++];
5612 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5613 SmallVector<TemplateArgument, 8> Args;
5614 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5615 QualType Underlying = readType(*Loc.F, Record, Idx);
5616 QualType T;
5617 if (Underlying.isNull())
5618 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5619 Args.size());
5620 else
5621 T = Context.getTemplateSpecializationType(Name, Args.data(),
5622 Args.size(), Underlying);
5623 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5624 return T;
5625 }
5626
5627 case TYPE_ATOMIC: {
5628 if (Record.size() != 1) {
5629 Error("Incorrect encoding of atomic type");
5630 return QualType();
5631 }
5632 QualType ValueType = readType(*Loc.F, Record, Idx);
5633 return Context.getAtomicType(ValueType);
5634 }
5635 }
5636 llvm_unreachable("Invalid TypeCode!");
5637}
5638
Richard Smith564417a2014-03-20 21:47:22 +00005639void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5640 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005641 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005642 const RecordData &Record, unsigned &Idx) {
5643 ExceptionSpecificationType EST =
5644 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005645 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005646 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005647 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005648 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005649 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005650 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005651 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005652 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005653 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5654 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005655 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005656 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005657 }
5658}
5659
Guy Benyei11169dd2012-12-18 14:30:41 +00005660class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5661 ASTReader &Reader;
5662 ModuleFile &F;
5663 const ASTReader::RecordData &Record;
5664 unsigned &Idx;
5665
5666 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5667 unsigned &I) {
5668 return Reader.ReadSourceLocation(F, R, I);
5669 }
5670
5671 template<typename T>
5672 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5673 return Reader.ReadDeclAs<T>(F, Record, Idx);
5674 }
5675
5676public:
5677 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5678 const ASTReader::RecordData &Record, unsigned &Idx)
5679 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5680 { }
5681
5682 // We want compile-time assurance that we've enumerated all of
5683 // these, so unfortunately we have to declare them first, then
5684 // define them out-of-line.
5685#define ABSTRACT_TYPELOC(CLASS, PARENT)
5686#define TYPELOC(CLASS, PARENT) \
5687 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5688#include "clang/AST/TypeLocNodes.def"
5689
5690 void VisitFunctionTypeLoc(FunctionTypeLoc);
5691 void VisitArrayTypeLoc(ArrayTypeLoc);
5692};
5693
5694void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5695 // nothing to do
5696}
5697void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5698 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5699 if (TL.needsExtraLocalData()) {
5700 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5701 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5702 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5703 TL.setModeAttr(Record[Idx++]);
5704 }
5705}
5706void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5708}
5709void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5710 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5711}
Reid Kleckner8a365022013-06-24 17:51:48 +00005712void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5713 // nothing to do
5714}
Reid Kleckner0503a872013-12-05 01:23:43 +00005715void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5716 // nothing to do
5717}
Guy Benyei11169dd2012-12-18 14:30:41 +00005718void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5719 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5720}
5721void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5722 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5723}
5724void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5725 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5728 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5729 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5730}
5731void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5732 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5733 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5734 if (Record[Idx++])
5735 TL.setSizeExpr(Reader.ReadExpr(F));
5736 else
Craig Toppera13603a2014-05-22 05:54:18 +00005737 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005738}
5739void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5740 VisitArrayTypeLoc(TL);
5741}
5742void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5743 VisitArrayTypeLoc(TL);
5744}
5745void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5746 VisitArrayTypeLoc(TL);
5747}
5748void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5749 DependentSizedArrayTypeLoc TL) {
5750 VisitArrayTypeLoc(TL);
5751}
5752void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5753 DependentSizedExtVectorTypeLoc TL) {
5754 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5755}
5756void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5757 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5758}
5759void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5761}
5762void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5763 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5764 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5765 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5766 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005767 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5768 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005769 }
5770}
5771void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5772 VisitFunctionTypeLoc(TL);
5773}
5774void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5775 VisitFunctionTypeLoc(TL);
5776}
5777void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5778 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5781 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5782}
5783void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5784 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5785 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5786 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5787}
5788void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5789 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5790 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5791 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5792 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5793}
5794void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5795 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5796}
5797void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5798 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5799 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5800 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5801 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5802}
5803void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5804 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5805}
5806void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5807 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5808}
5809void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5810 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5811}
5812void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5813 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5814 if (TL.hasAttrOperand()) {
5815 SourceRange range;
5816 range.setBegin(ReadSourceLocation(Record, Idx));
5817 range.setEnd(ReadSourceLocation(Record, Idx));
5818 TL.setAttrOperandParensRange(range);
5819 }
5820 if (TL.hasAttrExprOperand()) {
5821 if (Record[Idx++])
5822 TL.setAttrExprOperand(Reader.ReadExpr(F));
5823 else
Craig Toppera13603a2014-05-22 05:54:18 +00005824 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 } else if (TL.hasAttrEnumOperand())
5826 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5829 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5830}
5831void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5832 SubstTemplateTypeParmTypeLoc TL) {
5833 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5834}
5835void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5836 SubstTemplateTypeParmPackTypeLoc TL) {
5837 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5838}
5839void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5840 TemplateSpecializationTypeLoc TL) {
5841 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5842 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5843 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5844 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5845 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5846 TL.setArgLocInfo(i,
5847 Reader.GetTemplateArgumentLocInfo(F,
5848 TL.getTypePtr()->getArg(i).getKind(),
5849 Record, Idx));
5850}
5851void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5852 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5853 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5854}
5855void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5856 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5857 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5858}
5859void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5860 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5861}
5862void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5863 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5864 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5865 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5866}
5867void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5868 DependentTemplateSpecializationTypeLoc TL) {
5869 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5870 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5871 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5872 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5873 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5874 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5875 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5876 TL.setArgLocInfo(I,
5877 Reader.GetTemplateArgumentLocInfo(F,
5878 TL.getTypePtr()->getArg(I).getKind(),
5879 Record, Idx));
5880}
5881void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5882 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5883}
5884void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5885 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5886}
5887void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5888 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005889 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5890 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5891 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5892 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5893 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5894 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005895 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5896 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5899 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5900}
5901void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5902 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5903 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5904 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5905}
5906
5907TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5908 const RecordData &Record,
5909 unsigned &Idx) {
5910 QualType InfoTy = readType(F, Record, Idx);
5911 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005912 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005913
5914 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5915 TypeLocReader TLR(*this, F, Record, Idx);
5916 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5917 TLR.Visit(TL);
5918 return TInfo;
5919}
5920
5921QualType ASTReader::GetType(TypeID ID) {
5922 unsigned FastQuals = ID & Qualifiers::FastMask;
5923 unsigned Index = ID >> Qualifiers::FastWidth;
5924
5925 if (Index < NUM_PREDEF_TYPE_IDS) {
5926 QualType T;
5927 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00005928 case PREDEF_TYPE_NULL_ID:
5929 return QualType();
5930 case PREDEF_TYPE_VOID_ID:
5931 T = Context.VoidTy;
5932 break;
5933 case PREDEF_TYPE_BOOL_ID:
5934 T = Context.BoolTy;
5935 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005936
5937 case PREDEF_TYPE_CHAR_U_ID:
5938 case PREDEF_TYPE_CHAR_S_ID:
5939 // FIXME: Check that the signedness of CharTy is correct!
5940 T = Context.CharTy;
5941 break;
5942
Alexey Baderbdf7c842015-09-15 12:18:29 +00005943 case PREDEF_TYPE_UCHAR_ID:
5944 T = Context.UnsignedCharTy;
5945 break;
5946 case PREDEF_TYPE_USHORT_ID:
5947 T = Context.UnsignedShortTy;
5948 break;
5949 case PREDEF_TYPE_UINT_ID:
5950 T = Context.UnsignedIntTy;
5951 break;
5952 case PREDEF_TYPE_ULONG_ID:
5953 T = Context.UnsignedLongTy;
5954 break;
5955 case PREDEF_TYPE_ULONGLONG_ID:
5956 T = Context.UnsignedLongLongTy;
5957 break;
5958 case PREDEF_TYPE_UINT128_ID:
5959 T = Context.UnsignedInt128Ty;
5960 break;
5961 case PREDEF_TYPE_SCHAR_ID:
5962 T = Context.SignedCharTy;
5963 break;
5964 case PREDEF_TYPE_WCHAR_ID:
5965 T = Context.WCharTy;
5966 break;
5967 case PREDEF_TYPE_SHORT_ID:
5968 T = Context.ShortTy;
5969 break;
5970 case PREDEF_TYPE_INT_ID:
5971 T = Context.IntTy;
5972 break;
5973 case PREDEF_TYPE_LONG_ID:
5974 T = Context.LongTy;
5975 break;
5976 case PREDEF_TYPE_LONGLONG_ID:
5977 T = Context.LongLongTy;
5978 break;
5979 case PREDEF_TYPE_INT128_ID:
5980 T = Context.Int128Ty;
5981 break;
5982 case PREDEF_TYPE_HALF_ID:
5983 T = Context.HalfTy;
5984 break;
5985 case PREDEF_TYPE_FLOAT_ID:
5986 T = Context.FloatTy;
5987 break;
5988 case PREDEF_TYPE_DOUBLE_ID:
5989 T = Context.DoubleTy;
5990 break;
5991 case PREDEF_TYPE_LONGDOUBLE_ID:
5992 T = Context.LongDoubleTy;
5993 break;
5994 case PREDEF_TYPE_OVERLOAD_ID:
5995 T = Context.OverloadTy;
5996 break;
5997 case PREDEF_TYPE_BOUND_MEMBER:
5998 T = Context.BoundMemberTy;
5999 break;
6000 case PREDEF_TYPE_PSEUDO_OBJECT:
6001 T = Context.PseudoObjectTy;
6002 break;
6003 case PREDEF_TYPE_DEPENDENT_ID:
6004 T = Context.DependentTy;
6005 break;
6006 case PREDEF_TYPE_UNKNOWN_ANY:
6007 T = Context.UnknownAnyTy;
6008 break;
6009 case PREDEF_TYPE_NULLPTR_ID:
6010 T = Context.NullPtrTy;
6011 break;
6012 case PREDEF_TYPE_CHAR16_ID:
6013 T = Context.Char16Ty;
6014 break;
6015 case PREDEF_TYPE_CHAR32_ID:
6016 T = Context.Char32Ty;
6017 break;
6018 case PREDEF_TYPE_OBJC_ID:
6019 T = Context.ObjCBuiltinIdTy;
6020 break;
6021 case PREDEF_TYPE_OBJC_CLASS:
6022 T = Context.ObjCBuiltinClassTy;
6023 break;
6024 case PREDEF_TYPE_OBJC_SEL:
6025 T = Context.ObjCBuiltinSelTy;
6026 break;
6027 case PREDEF_TYPE_IMAGE1D_ID:
6028 T = Context.OCLImage1dTy;
6029 break;
6030 case PREDEF_TYPE_IMAGE1D_ARR_ID:
6031 T = Context.OCLImage1dArrayTy;
6032 break;
6033 case PREDEF_TYPE_IMAGE1D_BUFF_ID:
6034 T = Context.OCLImage1dBufferTy;
6035 break;
6036 case PREDEF_TYPE_IMAGE2D_ID:
6037 T = Context.OCLImage2dTy;
6038 break;
6039 case PREDEF_TYPE_IMAGE2D_ARR_ID:
6040 T = Context.OCLImage2dArrayTy;
6041 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006042 case PREDEF_TYPE_IMAGE2D_DEP_ID:
6043 T = Context.OCLImage2dDepthTy;
6044 break;
6045 case PREDEF_TYPE_IMAGE2D_ARR_DEP_ID:
6046 T = Context.OCLImage2dArrayDepthTy;
6047 break;
6048 case PREDEF_TYPE_IMAGE2D_MSAA_ID:
6049 T = Context.OCLImage2dMSAATy;
6050 break;
6051 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_ID:
6052 T = Context.OCLImage2dArrayMSAATy;
6053 break;
6054 case PREDEF_TYPE_IMAGE2D_MSAA_DEP_ID:
6055 T = Context.OCLImage2dMSAADepthTy;
6056 break;
6057 case PREDEF_TYPE_IMAGE2D_ARR_MSAA_DEPTH_ID:
6058 T = Context.OCLImage2dArrayMSAADepthTy;
6059 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006060 case PREDEF_TYPE_IMAGE3D_ID:
6061 T = Context.OCLImage3dTy;
6062 break;
6063 case PREDEF_TYPE_SAMPLER_ID:
6064 T = Context.OCLSamplerTy;
6065 break;
6066 case PREDEF_TYPE_EVENT_ID:
6067 T = Context.OCLEventTy;
6068 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006069 case PREDEF_TYPE_CLK_EVENT_ID:
6070 T = Context.OCLClkEventTy;
6071 break;
6072 case PREDEF_TYPE_QUEUE_ID:
6073 T = Context.OCLQueueTy;
6074 break;
6075 case PREDEF_TYPE_NDRANGE_ID:
6076 T = Context.OCLNDRangeTy;
6077 break;
6078 case PREDEF_TYPE_RESERVE_ID_ID:
6079 T = Context.OCLReserveIDTy;
6080 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006081 case PREDEF_TYPE_AUTO_DEDUCT:
6082 T = Context.getAutoDeductType();
6083 break;
6084
6085 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6086 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 break;
6088
6089 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6090 T = Context.ARCUnbridgedCastTy;
6091 break;
6092
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 case PREDEF_TYPE_BUILTIN_FN:
6094 T = Context.BuiltinFnTy;
6095 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006096
6097 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6098 T = Context.OMPArraySectionTy;
6099 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 }
6101
6102 assert(!T.isNull() && "Unknown predefined type");
6103 return T.withFastQualifiers(FastQuals);
6104 }
6105
6106 Index -= NUM_PREDEF_TYPE_IDS;
6107 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6108 if (TypesLoaded[Index].isNull()) {
6109 TypesLoaded[Index] = readTypeRecord(Index);
6110 if (TypesLoaded[Index].isNull())
6111 return QualType();
6112
6113 TypesLoaded[Index]->setFromAST();
6114 if (DeserializationListener)
6115 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6116 TypesLoaded[Index]);
6117 }
6118
6119 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6120}
6121
6122QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6123 return GetType(getGlobalTypeID(F, LocalID));
6124}
6125
6126serialization::TypeID
6127ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6128 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6129 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6130
6131 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6132 return LocalID;
6133
6134 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6135 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6136 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6137
6138 unsigned GlobalIndex = LocalIndex + I->second;
6139 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6140}
6141
6142TemplateArgumentLocInfo
6143ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6144 TemplateArgument::ArgKind Kind,
6145 const RecordData &Record,
6146 unsigned &Index) {
6147 switch (Kind) {
6148 case TemplateArgument::Expression:
6149 return ReadExpr(F);
6150 case TemplateArgument::Type:
6151 return GetTypeSourceInfo(F, Record, Index);
6152 case TemplateArgument::Template: {
6153 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6154 Index);
6155 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6156 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6157 SourceLocation());
6158 }
6159 case TemplateArgument::TemplateExpansion: {
6160 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6161 Index);
6162 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6163 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6164 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6165 EllipsisLoc);
6166 }
6167 case TemplateArgument::Null:
6168 case TemplateArgument::Integral:
6169 case TemplateArgument::Declaration:
6170 case TemplateArgument::NullPtr:
6171 case TemplateArgument::Pack:
6172 // FIXME: Is this right?
6173 return TemplateArgumentLocInfo();
6174 }
6175 llvm_unreachable("unexpected template argument loc");
6176}
6177
6178TemplateArgumentLoc
6179ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6180 const RecordData &Record, unsigned &Index) {
6181 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6182
6183 if (Arg.getKind() == TemplateArgument::Expression) {
6184 if (Record[Index++]) // bool InfoHasSameExpr.
6185 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6186 }
6187 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6188 Record, Index));
6189}
6190
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006191const ASTTemplateArgumentListInfo*
6192ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6193 const RecordData &Record,
6194 unsigned &Index) {
6195 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6196 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6197 unsigned NumArgsAsWritten = Record[Index++];
6198 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6199 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6200 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6201 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6202}
6203
Guy Benyei11169dd2012-12-18 14:30:41 +00006204Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6205 return GetDecl(ID);
6206}
6207
Richard Smith50895422015-01-31 03:04:55 +00006208template<typename TemplateSpecializationDecl>
6209static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6210 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6211 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6212}
6213
Richard Smith053f6c62014-05-16 23:01:30 +00006214void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006215 if (NumCurrentElementsDeserializing) {
6216 // We arrange to not care about the complete redeclaration chain while we're
6217 // deserializing. Just remember that the AST has marked this one as complete
6218 // but that it's not actually complete yet, so we know we still need to
6219 // complete it later.
6220 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6221 return;
6222 }
6223
Richard Smith053f6c62014-05-16 23:01:30 +00006224 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6225
Richard Smith053f6c62014-05-16 23:01:30 +00006226 // If this is a named declaration, complete it by looking it up
6227 // within its context.
6228 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006229 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006230 // all mergeable entities within it.
6231 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6232 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6233 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006234 if (!getContext().getLangOpts().CPlusPlus &&
6235 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006236 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006237 // the identifier instead. (For C++ modules, we don't store decls
6238 // in the serialized identifier table, so we do the lookup in the TU.)
6239 auto *II = Name.getAsIdentifierInfo();
6240 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006241 if (II->isOutOfDate())
6242 updateOutOfDateIdentifier(*II);
6243 } else
6244 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006245 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006246 // Find all declarations of this kind from the relevant context.
6247 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6248 auto *DC = cast<DeclContext>(DCDecl);
6249 SmallVector<Decl*, 8> Decls;
6250 FindExternalLexicalDecls(
6251 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6252 }
Richard Smith053f6c62014-05-16 23:01:30 +00006253 }
6254 }
Richard Smith50895422015-01-31 03:04:55 +00006255
6256 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6257 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6258 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6259 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6260 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6261 if (auto *Template = FD->getPrimaryTemplate())
6262 Template->LoadLazySpecializations();
6263 }
Richard Smith053f6c62014-05-16 23:01:30 +00006264}
6265
Richard Smithc2bb8182015-03-24 06:36:48 +00006266uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6267 const RecordData &Record,
6268 unsigned &Idx) {
6269 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6270 Error("malformed AST file: missing C++ ctor initializers");
6271 return 0;
6272 }
6273
6274 unsigned LocalID = Record[Idx++];
6275 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6276}
6277
6278CXXCtorInitializer **
6279ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6280 RecordLocation Loc = getLocalBitOffset(Offset);
6281 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6282 SavedStreamPosition SavedPosition(Cursor);
6283 Cursor.JumpToBit(Loc.Offset);
6284 ReadingKindTracker ReadingKind(Read_Decl, *this);
6285
6286 RecordData Record;
6287 unsigned Code = Cursor.ReadCode();
6288 unsigned RecCode = Cursor.readRecord(Code, Record);
6289 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6290 Error("malformed AST file: missing C++ ctor initializers");
6291 return nullptr;
6292 }
6293
6294 unsigned Idx = 0;
6295 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6296}
6297
Richard Smithcd45dbc2014-04-19 03:48:30 +00006298uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6299 const RecordData &Record,
6300 unsigned &Idx) {
6301 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6302 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006304 }
6305
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 unsigned LocalID = Record[Idx++];
6307 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6308}
6309
6310CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6311 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006312 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006313 SavedStreamPosition SavedPosition(Cursor);
6314 Cursor.JumpToBit(Loc.Offset);
6315 ReadingKindTracker ReadingKind(Read_Decl, *this);
6316 RecordData Record;
6317 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006318 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006320 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006321 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006322 }
6323
6324 unsigned Idx = 0;
6325 unsigned NumBases = Record[Idx++];
6326 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6327 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6328 for (unsigned I = 0; I != NumBases; ++I)
6329 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6330 return Bases;
6331}
6332
6333serialization::DeclID
6334ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6335 if (LocalID < NUM_PREDEF_DECL_IDS)
6336 return LocalID;
6337
6338 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6339 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6340 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6341
6342 return LocalID + I->second;
6343}
6344
6345bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6346 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006347 // Predefined decls aren't from any module.
6348 if (ID < NUM_PREDEF_DECL_IDS)
6349 return false;
6350
Richard Smithbcda1a92015-07-12 23:51:20 +00006351 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6352 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006353}
6354
Douglas Gregor9f782892013-01-21 15:25:38 +00006355ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006357 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6359 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6360 return I->second;
6361}
6362
6363SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6364 if (ID < NUM_PREDEF_DECL_IDS)
6365 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006366
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6368
6369 if (Index > DeclsLoaded.size()) {
6370 Error("declaration ID out-of-range for AST file");
6371 return SourceLocation();
6372 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006373
Guy Benyei11169dd2012-12-18 14:30:41 +00006374 if (Decl *D = DeclsLoaded[Index])
6375 return D->getLocation();
6376
6377 unsigned RawLocation = 0;
6378 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6379 return ReadSourceLocation(*Rec.F, RawLocation);
6380}
6381
Richard Smithfe620d22015-03-05 23:24:12 +00006382static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6383 switch (ID) {
6384 case PREDEF_DECL_NULL_ID:
6385 return nullptr;
6386
6387 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6388 return Context.getTranslationUnitDecl();
6389
6390 case PREDEF_DECL_OBJC_ID_ID:
6391 return Context.getObjCIdDecl();
6392
6393 case PREDEF_DECL_OBJC_SEL_ID:
6394 return Context.getObjCSelDecl();
6395
6396 case PREDEF_DECL_OBJC_CLASS_ID:
6397 return Context.getObjCClassDecl();
6398
6399 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6400 return Context.getObjCProtocolDecl();
6401
6402 case PREDEF_DECL_INT_128_ID:
6403 return Context.getInt128Decl();
6404
6405 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6406 return Context.getUInt128Decl();
6407
6408 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6409 return Context.getObjCInstanceTypeDecl();
6410
6411 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6412 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006413
Richard Smith9b88a4c2015-07-27 05:40:23 +00006414 case PREDEF_DECL_VA_LIST_TAG:
6415 return Context.getVaListTagDecl();
6416
Charles Davisc7d5c942015-09-17 20:55:33 +00006417 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6418 return Context.getBuiltinMSVaListDecl();
6419
Richard Smithf19e1272015-03-07 00:04:49 +00006420 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6421 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006422
6423 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6424 return Context.getMakeIntegerSeqDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006425 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006426 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006427}
6428
Richard Smithcd45dbc2014-04-19 03:48:30 +00006429Decl *ASTReader::GetExistingDecl(DeclID ID) {
6430 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006431 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6432 if (D) {
6433 // Track that we have merged the declaration with ID \p ID into the
6434 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006435 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006436 if (Merged.empty())
6437 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 }
Richard Smithfe620d22015-03-05 23:24:12 +00006439 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006441
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6443
6444 if (Index >= DeclsLoaded.size()) {
6445 assert(0 && "declaration ID out-of-range for AST file");
6446 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006447 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006449
6450 return DeclsLoaded[Index];
6451}
6452
6453Decl *ASTReader::GetDecl(DeclID ID) {
6454 if (ID < NUM_PREDEF_DECL_IDS)
6455 return GetExistingDecl(ID);
6456
6457 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6458
6459 if (Index >= DeclsLoaded.size()) {
6460 assert(0 && "declaration ID out-of-range for AST file");
6461 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006462 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006463 }
6464
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 if (!DeclsLoaded[Index]) {
6466 ReadDeclRecord(ID);
6467 if (DeserializationListener)
6468 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6469 }
6470
6471 return DeclsLoaded[Index];
6472}
6473
6474DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6475 DeclID GlobalID) {
6476 if (GlobalID < NUM_PREDEF_DECL_IDS)
6477 return GlobalID;
6478
6479 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6480 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6481 ModuleFile *Owner = I->second;
6482
6483 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6484 = M.GlobalToLocalDeclIDs.find(Owner);
6485 if (Pos == M.GlobalToLocalDeclIDs.end())
6486 return 0;
6487
6488 return GlobalID - Owner->BaseDeclID + Pos->second;
6489}
6490
6491serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6492 const RecordData &Record,
6493 unsigned &Idx) {
6494 if (Idx >= Record.size()) {
6495 Error("Corrupted AST file");
6496 return 0;
6497 }
6498
6499 return getGlobalDeclID(F, Record[Idx++]);
6500}
6501
6502/// \brief Resolve the offset of a statement into a statement.
6503///
6504/// This operation will read a new statement from the external
6505/// source each time it is called, and is meant to be used via a
6506/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6507Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6508 // Switch case IDs are per Decl.
6509 ClearSwitchCaseIDs();
6510
6511 // Offset here is a global offset across the entire chain.
6512 RecordLocation Loc = getLocalBitOffset(Offset);
6513 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6514 return ReadStmtFromStream(*Loc.F);
6515}
6516
Richard Smith3cb15722015-08-05 22:41:45 +00006517void ASTReader::FindExternalLexicalDecls(
6518 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6519 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006520 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6521
Richard Smith9ccdd932015-08-06 22:14:12 +00006522 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006523 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6524 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6525 auto K = (Decl::Kind)+LexicalDecls[I];
6526 if (!IsKindWeWant(K))
6527 continue;
6528
6529 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6530
6531 // Don't add predefined declarations to the lexical context more
6532 // than once.
6533 if (ID < NUM_PREDEF_DECL_IDS) {
6534 if (PredefsVisited[ID])
6535 continue;
6536
6537 PredefsVisited[ID] = true;
6538 }
6539
6540 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006541 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006542 if (!DC->isDeclInLexicalTraversal(D))
6543 Decls.push_back(D);
6544 }
6545 }
6546 };
6547
6548 if (isa<TranslationUnitDecl>(DC)) {
6549 for (auto Lexical : TULexicalDecls)
6550 Visit(Lexical.first, Lexical.second);
6551 } else {
6552 auto I = LexicalDecls.find(DC);
6553 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006554 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006555 }
6556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006558}
6559
6560namespace {
6561
6562class DeclIDComp {
6563 ASTReader &Reader;
6564 ModuleFile &Mod;
6565
6566public:
6567 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6568
6569 bool operator()(LocalDeclID L, LocalDeclID R) const {
6570 SourceLocation LHS = getLocation(L);
6571 SourceLocation RHS = getLocation(R);
6572 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6573 }
6574
6575 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6576 SourceLocation RHS = getLocation(R);
6577 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6578 }
6579
6580 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6581 SourceLocation LHS = getLocation(L);
6582 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6583 }
6584
6585 SourceLocation getLocation(LocalDeclID ID) const {
6586 return Reader.getSourceManager().getFileLoc(
6587 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6588 }
6589};
6590
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006591}
Guy Benyei11169dd2012-12-18 14:30:41 +00006592
6593void ASTReader::FindFileRegionDecls(FileID File,
6594 unsigned Offset, unsigned Length,
6595 SmallVectorImpl<Decl *> &Decls) {
6596 SourceManager &SM = getSourceManager();
6597
6598 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6599 if (I == FileDeclIDs.end())
6600 return;
6601
6602 FileDeclsInfo &DInfo = I->second;
6603 if (DInfo.Decls.empty())
6604 return;
6605
6606 SourceLocation
6607 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6608 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6609
6610 DeclIDComp DIDComp(*this, *DInfo.Mod);
6611 ArrayRef<serialization::LocalDeclID>::iterator
6612 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6613 BeginLoc, DIDComp);
6614 if (BeginIt != DInfo.Decls.begin())
6615 --BeginIt;
6616
6617 // If we are pointing at a top-level decl inside an objc container, we need
6618 // to backtrack until we find it otherwise we will fail to report that the
6619 // region overlaps with an objc container.
6620 while (BeginIt != DInfo.Decls.begin() &&
6621 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6622 ->isTopLevelDeclInObjCContainer())
6623 --BeginIt;
6624
6625 ArrayRef<serialization::LocalDeclID>::iterator
6626 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6627 EndLoc, DIDComp);
6628 if (EndIt != DInfo.Decls.end())
6629 ++EndIt;
6630
6631 for (ArrayRef<serialization::LocalDeclID>::iterator
6632 DIt = BeginIt; DIt != EndIt; ++DIt)
6633 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6634}
6635
Richard Smith9ce12e32013-02-07 03:30:24 +00006636bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006637ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6638 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006639 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 "DeclContext has no visible decls in storage");
6641 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006642 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006643
Richard Smithd88a7f12015-09-01 20:35:42 +00006644 auto It = Lookups.find(DC);
6645 if (It == Lookups.end())
6646 return false;
6647
Richard Smith8c913ec2014-08-14 02:21:01 +00006648 Deserializing LookupResults(this);
6649
Richard Smithd88a7f12015-09-01 20:35:42 +00006650 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006652 for (DeclID ID : It->second.Table.find(Name)) {
6653 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6654 if (ND->getDeclName() == Name)
6655 Decls.push_back(ND);
6656 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006657
Guy Benyei11169dd2012-12-18 14:30:41 +00006658 ++NumVisibleDeclContextsRead;
6659 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006660 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006661}
6662
Guy Benyei11169dd2012-12-18 14:30:41 +00006663void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6664 if (!DC->hasExternalVisibleStorage())
6665 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006666
6667 auto It = Lookups.find(DC);
6668 assert(It != Lookups.end() &&
6669 "have external visible storage but no lookup tables");
6670
Craig Topper79be4cd2013-07-05 04:33:53 +00006671 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006672
Richard Smithd88a7f12015-09-01 20:35:42 +00006673 for (DeclID ID : It->second.Table.findAll()) {
6674 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6675 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006676 }
6677
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 ++NumVisibleDeclContextsRead;
6679
Craig Topper79be4cd2013-07-05 04:33:53 +00006680 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6682 }
6683 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6684}
6685
Richard Smithd88a7f12015-09-01 20:35:42 +00006686const serialization::reader::DeclContextLookupTable *
6687ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6688 auto I = Lookups.find(Primary);
6689 return I == Lookups.end() ? nullptr : &I->second;
6690}
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692/// \brief Under non-PCH compilation the consumer receives the objc methods
6693/// before receiving the implementation, and codegen depends on this.
6694/// We simulate this by deserializing and passing to consumer the methods of the
6695/// implementation before passing the deserialized implementation decl.
6696static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6697 ASTConsumer *Consumer) {
6698 assert(ImplD && Consumer);
6699
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006700 for (auto *I : ImplD->methods())
6701 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006702
6703 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6704}
6705
6706void ASTReader::PassInterestingDeclsToConsumer() {
6707 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006708
6709 if (PassingDeclsToConsumer)
6710 return;
6711
6712 // Guard variable to avoid recursively redoing the process of passing
6713 // decls to consumer.
6714 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6715 true);
6716
Richard Smith9e2341d2015-03-23 03:25:59 +00006717 // Ensure that we've loaded all potentially-interesting declarations
6718 // that need to be eagerly loaded.
6719 for (auto ID : EagerlyDeserializedDecls)
6720 GetDecl(ID);
6721 EagerlyDeserializedDecls.clear();
6722
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 while (!InterestingDecls.empty()) {
6724 Decl *D = InterestingDecls.front();
6725 InterestingDecls.pop_front();
6726
6727 PassInterestingDeclToConsumer(D);
6728 }
6729}
6730
6731void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6732 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6733 PassObjCImplDeclToConsumer(ImplD, Consumer);
6734 else
6735 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6736}
6737
6738void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6739 this->Consumer = Consumer;
6740
Richard Smith9e2341d2015-03-23 03:25:59 +00006741 if (Consumer)
6742 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006743
6744 if (DeserializationListener)
6745 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006746}
6747
6748void ASTReader::PrintStats() {
6749 std::fprintf(stderr, "*** AST File Statistics:\n");
6750
6751 unsigned NumTypesLoaded
6752 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6753 QualType());
6754 unsigned NumDeclsLoaded
6755 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006756 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006757 unsigned NumIdentifiersLoaded
6758 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6759 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006760 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 unsigned NumMacrosLoaded
6762 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6763 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006764 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 unsigned NumSelectorsLoaded
6766 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6767 SelectorsLoaded.end(),
6768 Selector());
6769
6770 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6771 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6772 NumSLocEntriesRead, TotalNumSLocEntries,
6773 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6774 if (!TypesLoaded.empty())
6775 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6776 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6777 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6778 if (!DeclsLoaded.empty())
6779 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6780 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6781 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6782 if (!IdentifiersLoaded.empty())
6783 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6784 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6785 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6786 if (!MacrosLoaded.empty())
6787 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6788 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6789 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6790 if (!SelectorsLoaded.empty())
6791 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6792 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6793 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6794 if (TotalNumStatements)
6795 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6796 NumStatementsRead, TotalNumStatements,
6797 ((float)NumStatementsRead/TotalNumStatements * 100));
6798 if (TotalNumMacros)
6799 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6800 NumMacrosRead, TotalNumMacros,
6801 ((float)NumMacrosRead/TotalNumMacros * 100));
6802 if (TotalLexicalDeclContexts)
6803 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6804 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6805 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6806 * 100));
6807 if (TotalVisibleDeclContexts)
6808 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6809 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6810 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6811 * 100));
6812 if (TotalNumMethodPoolEntries) {
6813 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6814 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6815 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6816 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006817 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006818 if (NumMethodPoolLookups) {
6819 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6820 NumMethodPoolHits, NumMethodPoolLookups,
6821 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6822 }
6823 if (NumMethodPoolTableLookups) {
6824 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6825 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6826 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6827 * 100.0));
6828 }
6829
Douglas Gregor00a50f72013-01-25 00:38:33 +00006830 if (NumIdentifierLookupHits) {
6831 std::fprintf(stderr,
6832 " %u / %u identifier table lookups succeeded (%f%%)\n",
6833 NumIdentifierLookupHits, NumIdentifierLookups,
6834 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6835 }
6836
Douglas Gregore060e572013-01-25 01:03:03 +00006837 if (GlobalIndex) {
6838 std::fprintf(stderr, "\n");
6839 GlobalIndex->printStats();
6840 }
6841
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 std::fprintf(stderr, "\n");
6843 dump();
6844 std::fprintf(stderr, "\n");
6845}
6846
6847template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6848static void
6849dumpModuleIDMap(StringRef Name,
6850 const ContinuousRangeMap<Key, ModuleFile *,
6851 InitialCapacity> &Map) {
6852 if (Map.begin() == Map.end())
6853 return;
6854
6855 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6856 llvm::errs() << Name << ":\n";
6857 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6858 I != IEnd; ++I) {
6859 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6860 << "\n";
6861 }
6862}
6863
6864void ASTReader::dump() {
6865 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6866 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6867 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6868 dumpModuleIDMap("Global type map", GlobalTypeMap);
6869 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6870 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6871 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6872 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6873 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6874 dumpModuleIDMap("Global preprocessed entity map",
6875 GlobalPreprocessedEntityMap);
6876
6877 llvm::errs() << "\n*** PCH/Modules Loaded:";
6878 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6879 MEnd = ModuleMgr.end();
6880 M != MEnd; ++M)
6881 (*M)->dump();
6882}
6883
6884/// Return the amount of memory used by memory buffers, breaking down
6885/// by heap-backed versus mmap'ed memory.
6886void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6887 for (ModuleConstIterator I = ModuleMgr.begin(),
6888 E = ModuleMgr.end(); I != E; ++I) {
6889 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6890 size_t bytes = buf->getBufferSize();
6891 switch (buf->getBufferKind()) {
6892 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6893 sizes.malloc_bytes += bytes;
6894 break;
6895 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6896 sizes.mmap_bytes += bytes;
6897 break;
6898 }
6899 }
6900 }
6901}
6902
6903void ASTReader::InitializeSema(Sema &S) {
6904 SemaObj = &S;
6905 S.addExternalSource(this);
6906
6907 // Makes sure any declarations that were deserialized "too early"
6908 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006909 for (uint64_t ID : PreloadedDeclIDs) {
6910 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6911 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006912 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006913 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006914
Richard Smith3d8e97e2013-10-18 06:54:39 +00006915 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 if (!FPPragmaOptions.empty()) {
6917 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6918 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6919 }
6920
Richard Smith3d8e97e2013-10-18 06:54:39 +00006921 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 if (!OpenCLExtensions.empty()) {
6923 unsigned I = 0;
6924#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6925#include "clang/Basic/OpenCLExtensions.def"
6926
6927 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6928 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006929
6930 UpdateSema();
6931}
6932
6933void ASTReader::UpdateSema() {
6934 assert(SemaObj && "no Sema to update");
6935
6936 // Load the offsets of the declarations that Sema references.
6937 // They will be lazily deserialized when needed.
6938 if (!SemaDeclRefs.empty()) {
6939 assert(SemaDeclRefs.size() % 2 == 0);
6940 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6941 if (!SemaObj->StdNamespace)
6942 SemaObj->StdNamespace = SemaDeclRefs[I];
6943 if (!SemaObj->StdBadAlloc)
6944 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6945 }
6946 SemaDeclRefs.clear();
6947 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006948
6949 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6950 // encountered the pragma in the source.
6951 if(OptimizeOffPragmaLocation.isValid())
6952 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006953}
6954
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006955IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 // Note that we are loading an identifier.
6957 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006958
Douglas Gregor7211ac12013-01-25 23:32:03 +00006959 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006960 NumIdentifierLookups,
6961 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006962
6963 // We don't need to do identifier table lookups in C++ modules (we preload
6964 // all interesting declarations, and don't need to use the scope for name
6965 // lookups). Perform the lookup in PCH files, though, since we don't build
6966 // a complete initial identifier table if we're carrying on from a PCH.
6967 if (Context.getLangOpts().CPlusPlus) {
6968 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006969 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006970 break;
6971 } else {
6972 // If there is a global index, look there first to determine which modules
6973 // provably do not have any results for this identifier.
6974 GlobalModuleIndex::HitSet Hits;
6975 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6976 if (!loadGlobalIndex()) {
6977 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6978 HitsPtr = &Hits;
6979 }
6980 }
6981
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006982 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006983 }
6984
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 IdentifierInfo *II = Visitor.getIdentifierInfo();
6986 markIdentifierUpToDate(II);
6987 return II;
6988}
6989
6990namespace clang {
6991 /// \brief An identifier-lookup iterator that enumerates all of the
6992 /// identifiers stored within a set of AST files.
6993 class ASTIdentifierIterator : public IdentifierIterator {
6994 /// \brief The AST reader whose identifiers are being enumerated.
6995 const ASTReader &Reader;
6996
6997 /// \brief The current index into the chain of AST files stored in
6998 /// the AST reader.
6999 unsigned Index;
7000
7001 /// \brief The current position within the identifier lookup table
7002 /// of the current AST file.
7003 ASTIdentifierLookupTable::key_iterator Current;
7004
7005 /// \brief The end position within the identifier lookup table of
7006 /// the current AST file.
7007 ASTIdentifierLookupTable::key_iterator End;
7008
7009 public:
7010 explicit ASTIdentifierIterator(const ASTReader &Reader);
7011
Craig Topper3e89dfe2014-03-13 02:13:41 +00007012 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007013 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007014}
Guy Benyei11169dd2012-12-18 14:30:41 +00007015
7016ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7017 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7018 ASTIdentifierLookupTable *IdTable
7019 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7020 Current = IdTable->key_begin();
7021 End = IdTable->key_end();
7022}
7023
7024StringRef ASTIdentifierIterator::Next() {
7025 while (Current == End) {
7026 // If we have exhausted all of our AST files, we're done.
7027 if (Index == 0)
7028 return StringRef();
7029
7030 --Index;
7031 ASTIdentifierLookupTable *IdTable
7032 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7033 IdentifierLookupTable;
7034 Current = IdTable->key_begin();
7035 End = IdTable->key_end();
7036 }
7037
7038 // We have any identifiers remaining in the current AST file; return
7039 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007040 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007041 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007042 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007043}
7044
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007045IdentifierIterator *ASTReader::getIdentifiers() {
7046 if (!loadGlobalIndex())
7047 return GlobalIndex->createIdentifierIterator();
7048
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 return new ASTIdentifierIterator(*this);
7050}
7051
7052namespace clang { namespace serialization {
7053 class ReadMethodPoolVisitor {
7054 ASTReader &Reader;
7055 Selector Sel;
7056 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007057 unsigned InstanceBits;
7058 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007059 bool InstanceHasMoreThanOneDecl;
7060 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007061 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7062 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007063
7064 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007065 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007067 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007068 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7069 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007070
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007071 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007072 if (!M.SelectorLookupTable)
7073 return false;
7074
7075 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007076 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 return true;
7078
Richard Smithbdf2d932015-07-30 03:37:16 +00007079 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 ASTSelectorLookupTable *PoolTable
7081 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007082 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007083 if (Pos == PoolTable->end())
7084 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007085
Richard Smithbdf2d932015-07-30 03:37:16 +00007086 ++Reader.NumMethodPoolTableHits;
7087 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 // FIXME: Not quite happy with the statistics here. We probably should
7089 // disable this tracking when called via LoadSelector.
7090 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007091 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007093 if (Reader.DeserializationListener)
7094 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007095
Richard Smithbdf2d932015-07-30 03:37:16 +00007096 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7097 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7098 InstanceBits = Data.InstanceBits;
7099 FactoryBits = Data.FactoryBits;
7100 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7101 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 return true;
7103 }
7104
7105 /// \brief Retrieve the instance methods found by this visitor.
7106 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7107 return InstanceMethods;
7108 }
7109
7110 /// \brief Retrieve the instance methods found by this visitor.
7111 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7112 return FactoryMethods;
7113 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007114
7115 unsigned getInstanceBits() const { return InstanceBits; }
7116 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007117 bool instanceHasMoreThanOneDecl() const {
7118 return InstanceHasMoreThanOneDecl;
7119 }
7120 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007121 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007122} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00007123
7124/// \brief Add the given set of methods to the method list.
7125static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7126 ObjCMethodList &List) {
7127 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7128 S.addMethodToGlobalList(&List, Methods[I]);
7129 }
7130}
7131
7132void ASTReader::ReadMethodPool(Selector Sel) {
7133 // Get the selector generation and update it to the current generation.
7134 unsigned &Generation = SelectorGeneration[Sel];
7135 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007136 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007137
7138 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007139 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007141 ModuleMgr.visit(Visitor);
7142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007144 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007145 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007146
7147 ++NumMethodPoolHits;
7148
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 if (!getSema())
7150 return;
7151
7152 Sema &S = *getSema();
7153 Sema::GlobalMethodPool::iterator Pos
7154 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007155
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007156 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007157 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007158 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007159 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007160
7161 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7162 // when building a module we keep every method individually and may need to
7163 // update hasMoreThanOneDecl as we add the methods.
7164 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7165 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007166}
7167
7168void ASTReader::ReadKnownNamespaces(
7169 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7170 Namespaces.clear();
7171
7172 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7173 if (NamespaceDecl *Namespace
7174 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7175 Namespaces.push_back(Namespace);
7176 }
7177}
7178
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007179void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007180 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007181 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7182 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007183 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007184 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007185 Undefined.insert(std::make_pair(D, Loc));
7186 }
7187}
Nick Lewycky8334af82013-01-26 00:35:08 +00007188
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007189void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7190 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7191 Exprs) {
7192 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7193 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7194 uint64_t Count = DelayedDeleteExprs[Idx++];
7195 for (uint64_t C = 0; C < Count; ++C) {
7196 SourceLocation DeleteLoc =
7197 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7198 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7199 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7200 }
7201 }
7202}
7203
Guy Benyei11169dd2012-12-18 14:30:41 +00007204void ASTReader::ReadTentativeDefinitions(
7205 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7206 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7207 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7208 if (Var)
7209 TentativeDefs.push_back(Var);
7210 }
7211 TentativeDefinitions.clear();
7212}
7213
7214void ASTReader::ReadUnusedFileScopedDecls(
7215 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7216 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7217 DeclaratorDecl *D
7218 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7219 if (D)
7220 Decls.push_back(D);
7221 }
7222 UnusedFileScopedDecls.clear();
7223}
7224
7225void ASTReader::ReadDelegatingConstructors(
7226 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7227 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7228 CXXConstructorDecl *D
7229 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7230 if (D)
7231 Decls.push_back(D);
7232 }
7233 DelegatingCtorDecls.clear();
7234}
7235
7236void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7237 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7238 TypedefNameDecl *D
7239 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7240 if (D)
7241 Decls.push_back(D);
7242 }
7243 ExtVectorDecls.clear();
7244}
7245
Nico Weber72889432014-09-06 01:25:55 +00007246void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7247 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7248 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7249 ++I) {
7250 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7251 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7252 if (D)
7253 Decls.insert(D);
7254 }
7255 UnusedLocalTypedefNameCandidates.clear();
7256}
7257
Guy Benyei11169dd2012-12-18 14:30:41 +00007258void ASTReader::ReadReferencedSelectors(
7259 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7260 if (ReferencedSelectorsData.empty())
7261 return;
7262
7263 // If there are @selector references added them to its pool. This is for
7264 // implementation of -Wselector.
7265 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7266 unsigned I = 0;
7267 while (I < DataSize) {
7268 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7269 SourceLocation SelLoc
7270 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7271 Sels.push_back(std::make_pair(Sel, SelLoc));
7272 }
7273 ReferencedSelectorsData.clear();
7274}
7275
7276void ASTReader::ReadWeakUndeclaredIdentifiers(
7277 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7278 if (WeakUndeclaredIdentifiers.empty())
7279 return;
7280
7281 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7282 IdentifierInfo *WeakId
7283 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7284 IdentifierInfo *AliasId
7285 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7286 SourceLocation Loc
7287 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7288 bool Used = WeakUndeclaredIdentifiers[I++];
7289 WeakInfo WI(AliasId, Loc);
7290 WI.setUsed(Used);
7291 WeakIDs.push_back(std::make_pair(WeakId, WI));
7292 }
7293 WeakUndeclaredIdentifiers.clear();
7294}
7295
7296void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7297 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7298 ExternalVTableUse VT;
7299 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7300 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7301 VT.DefinitionRequired = VTableUses[Idx++];
7302 VTables.push_back(VT);
7303 }
7304
7305 VTableUses.clear();
7306}
7307
7308void ASTReader::ReadPendingInstantiations(
7309 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7310 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7311 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7312 SourceLocation Loc
7313 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7314
7315 Pending.push_back(std::make_pair(D, Loc));
7316 }
7317 PendingInstantiations.clear();
7318}
7319
Richard Smithe40f2ba2013-08-07 21:41:30 +00007320void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007321 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007322 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7323 /* In loop */) {
7324 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7325
7326 LateParsedTemplate *LT = new LateParsedTemplate;
7327 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7328
7329 ModuleFile *F = getOwningModuleFile(LT->D);
7330 assert(F && "No module");
7331
7332 unsigned TokN = LateParsedTemplates[Idx++];
7333 LT->Toks.reserve(TokN);
7334 for (unsigned T = 0; T < TokN; ++T)
7335 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7336
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007337 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007338 }
7339
7340 LateParsedTemplates.clear();
7341}
7342
Guy Benyei11169dd2012-12-18 14:30:41 +00007343void ASTReader::LoadSelector(Selector Sel) {
7344 // It would be complicated to avoid reading the methods anyway. So don't.
7345 ReadMethodPool(Sel);
7346}
7347
7348void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7349 assert(ID && "Non-zero identifier ID required");
7350 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7351 IdentifiersLoaded[ID - 1] = II;
7352 if (DeserializationListener)
7353 DeserializationListener->IdentifierRead(ID, II);
7354}
7355
7356/// \brief Set the globally-visible declarations associated with the given
7357/// identifier.
7358///
7359/// If the AST reader is currently in a state where the given declaration IDs
7360/// cannot safely be resolved, they are queued until it is safe to resolve
7361/// them.
7362///
7363/// \param II an IdentifierInfo that refers to one or more globally-visible
7364/// declarations.
7365///
7366/// \param DeclIDs the set of declaration IDs with the name @p II that are
7367/// visible at global scope.
7368///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007369/// \param Decls if non-null, this vector will be populated with the set of
7370/// deserialized declarations. These declarations will not be pushed into
7371/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007372void
7373ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7374 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007375 SmallVectorImpl<Decl *> *Decls) {
7376 if (NumCurrentElementsDeserializing && !Decls) {
7377 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 return;
7379 }
7380
7381 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007382 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 // Queue this declaration so that it will be added to the
7384 // translation unit scope and identifier's declaration chain
7385 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007386 PreloadedDeclIDs.push_back(DeclIDs[I]);
7387 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007389
7390 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7391
7392 // If we're simply supposed to record the declarations, do so now.
7393 if (Decls) {
7394 Decls->push_back(D);
7395 continue;
7396 }
7397
7398 // Introduce this declaration into the translation-unit scope
7399 // and add it to the declaration chain for this identifier, so
7400 // that (unqualified) name lookup will find it.
7401 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007402 }
7403}
7404
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007405IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007407 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007408
7409 if (IdentifiersLoaded.empty()) {
7410 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007411 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007412 }
7413
7414 ID -= 1;
7415 if (!IdentifiersLoaded[ID]) {
7416 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7417 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7418 ModuleFile *M = I->second;
7419 unsigned Index = ID - M->BaseIdentifierID;
7420 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7421
7422 // All of the strings in the AST file are preceded by a 16-bit length.
7423 // Extract that 16-bit length to avoid having to execute strlen().
7424 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7425 // unsigned integers. This is important to avoid integer overflow when
7426 // we cast them to 'unsigned'.
7427 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7428 unsigned StrLen = (((unsigned) StrLenPtr[0])
7429 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007430 IdentifiersLoaded[ID]
7431 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 if (DeserializationListener)
7433 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7434 }
7435
7436 return IdentifiersLoaded[ID];
7437}
7438
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007439IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7440 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007441}
7442
7443IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7444 if (LocalID < NUM_PREDEF_IDENT_IDS)
7445 return LocalID;
7446
7447 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7448 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7449 assert(I != M.IdentifierRemap.end()
7450 && "Invalid index into identifier index remap");
7451
7452 return LocalID + I->second;
7453}
7454
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007455MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007456 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007457 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007458
7459 if (MacrosLoaded.empty()) {
7460 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007461 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007462 }
7463
7464 ID -= NUM_PREDEF_MACRO_IDS;
7465 if (!MacrosLoaded[ID]) {
7466 GlobalMacroMapType::iterator I
7467 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7468 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7469 ModuleFile *M = I->second;
7470 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007471 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7472
7473 if (DeserializationListener)
7474 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7475 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007476 }
7477
7478 return MacrosLoaded[ID];
7479}
7480
7481MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7482 if (LocalID < NUM_PREDEF_MACRO_IDS)
7483 return LocalID;
7484
7485 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7486 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7487 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7488
7489 return LocalID + I->second;
7490}
7491
7492serialization::SubmoduleID
7493ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7494 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7495 return LocalID;
7496
7497 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7498 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7499 assert(I != M.SubmoduleRemap.end()
7500 && "Invalid index into submodule index remap");
7501
7502 return LocalID + I->second;
7503}
7504
7505Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7506 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7507 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007508 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007509 }
7510
7511 if (GlobalID > SubmodulesLoaded.size()) {
7512 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007513 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 }
7515
7516 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7517}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007518
7519Module *ASTReader::getModule(unsigned ID) {
7520 return getSubmodule(ID);
7521}
7522
Richard Smithd88a7f12015-09-01 20:35:42 +00007523ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7524 if (ID & 1) {
7525 // It's a module, look it up by submodule ID.
7526 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7527 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7528 } else {
7529 // It's a prefix (preamble, PCH, ...). Look it up by index.
7530 unsigned IndexFromEnd = ID >> 1;
7531 assert(IndexFromEnd && "got reference to unknown module file");
7532 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7533 }
7534}
7535
7536unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7537 if (!F)
7538 return 1;
7539
7540 // For a file representing a module, use the submodule ID of the top-level
7541 // module as the file ID. For any other kind of file, the number of such
7542 // files loaded beforehand will be the same on reload.
7543 // FIXME: Is this true even if we have an explicit module file and a PCH?
7544 if (F->isModule())
7545 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7546
7547 auto PCHModules = getModuleManager().pch_modules();
7548 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7549 assert(I != PCHModules.end() && "emitting reference to unknown file");
7550 return (I - PCHModules.end()) << 1;
7551}
7552
Adrian Prantl15bcf702015-06-30 17:39:43 +00007553llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7554ASTReader::getSourceDescriptor(unsigned ID) {
7555 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007556 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007557
7558 // If there is only a single PCH, return it instead.
7559 // Chained PCH are not suported.
7560 if (ModuleMgr.size() == 1) {
7561 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantlc6458d62015-09-19 00:10:32 +00007562 return ASTReader::ASTSourceDescriptor(
7563 MF.OriginalSourceFileName, MF.OriginalDir, MF.FileName, MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007564 }
7565 return None;
7566}
7567
Guy Benyei11169dd2012-12-18 14:30:41 +00007568Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7569 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7570}
7571
7572Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7573 if (ID == 0)
7574 return Selector();
7575
7576 if (ID > SelectorsLoaded.size()) {
7577 Error("selector ID out of range in AST file");
7578 return Selector();
7579 }
7580
Craig Toppera13603a2014-05-22 05:54:18 +00007581 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007582 // Load this selector from the selector table.
7583 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7584 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7585 ModuleFile &M = *I->second;
7586 ASTSelectorLookupTrait Trait(*this, M);
7587 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7588 SelectorsLoaded[ID - 1] =
7589 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7590 if (DeserializationListener)
7591 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7592 }
7593
7594 return SelectorsLoaded[ID - 1];
7595}
7596
7597Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7598 return DecodeSelector(ID);
7599}
7600
7601uint32_t ASTReader::GetNumExternalSelectors() {
7602 // ID 0 (the null selector) is considered an external selector.
7603 return getTotalNumSelectors() + 1;
7604}
7605
7606serialization::SelectorID
7607ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7608 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7609 return LocalID;
7610
7611 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7612 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7613 assert(I != M.SelectorRemap.end()
7614 && "Invalid index into selector index remap");
7615
7616 return LocalID + I->second;
7617}
7618
7619DeclarationName
7620ASTReader::ReadDeclarationName(ModuleFile &F,
7621 const RecordData &Record, unsigned &Idx) {
7622 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7623 switch (Kind) {
7624 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007625 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007626
7627 case DeclarationName::ObjCZeroArgSelector:
7628 case DeclarationName::ObjCOneArgSelector:
7629 case DeclarationName::ObjCMultiArgSelector:
7630 return DeclarationName(ReadSelector(F, Record, Idx));
7631
7632 case DeclarationName::CXXConstructorName:
7633 return Context.DeclarationNames.getCXXConstructorName(
7634 Context.getCanonicalType(readType(F, Record, Idx)));
7635
7636 case DeclarationName::CXXDestructorName:
7637 return Context.DeclarationNames.getCXXDestructorName(
7638 Context.getCanonicalType(readType(F, Record, Idx)));
7639
7640 case DeclarationName::CXXConversionFunctionName:
7641 return Context.DeclarationNames.getCXXConversionFunctionName(
7642 Context.getCanonicalType(readType(F, Record, Idx)));
7643
7644 case DeclarationName::CXXOperatorName:
7645 return Context.DeclarationNames.getCXXOperatorName(
7646 (OverloadedOperatorKind)Record[Idx++]);
7647
7648 case DeclarationName::CXXLiteralOperatorName:
7649 return Context.DeclarationNames.getCXXLiteralOperatorName(
7650 GetIdentifierInfo(F, Record, Idx));
7651
7652 case DeclarationName::CXXUsingDirective:
7653 return DeclarationName::getUsingDirectiveName();
7654 }
7655
7656 llvm_unreachable("Invalid NameKind!");
7657}
7658
7659void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7660 DeclarationNameLoc &DNLoc,
7661 DeclarationName Name,
7662 const RecordData &Record, unsigned &Idx) {
7663 switch (Name.getNameKind()) {
7664 case DeclarationName::CXXConstructorName:
7665 case DeclarationName::CXXDestructorName:
7666 case DeclarationName::CXXConversionFunctionName:
7667 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7668 break;
7669
7670 case DeclarationName::CXXOperatorName:
7671 DNLoc.CXXOperatorName.BeginOpNameLoc
7672 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7673 DNLoc.CXXOperatorName.EndOpNameLoc
7674 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7675 break;
7676
7677 case DeclarationName::CXXLiteralOperatorName:
7678 DNLoc.CXXLiteralOperatorName.OpNameLoc
7679 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7680 break;
7681
7682 case DeclarationName::Identifier:
7683 case DeclarationName::ObjCZeroArgSelector:
7684 case DeclarationName::ObjCOneArgSelector:
7685 case DeclarationName::ObjCMultiArgSelector:
7686 case DeclarationName::CXXUsingDirective:
7687 break;
7688 }
7689}
7690
7691void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7692 DeclarationNameInfo &NameInfo,
7693 const RecordData &Record, unsigned &Idx) {
7694 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7695 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7696 DeclarationNameLoc DNLoc;
7697 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7698 NameInfo.setInfo(DNLoc);
7699}
7700
7701void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7702 const RecordData &Record, unsigned &Idx) {
7703 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7704 unsigned NumTPLists = Record[Idx++];
7705 Info.NumTemplParamLists = NumTPLists;
7706 if (NumTPLists) {
7707 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7708 for (unsigned i=0; i != NumTPLists; ++i)
7709 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7710 }
7711}
7712
7713TemplateName
7714ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7715 unsigned &Idx) {
7716 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7717 switch (Kind) {
7718 case TemplateName::Template:
7719 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7720
7721 case TemplateName::OverloadedTemplate: {
7722 unsigned size = Record[Idx++];
7723 UnresolvedSet<8> Decls;
7724 while (size--)
7725 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7726
7727 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7728 }
7729
7730 case TemplateName::QualifiedTemplate: {
7731 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7732 bool hasTemplKeyword = Record[Idx++];
7733 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7734 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7735 }
7736
7737 case TemplateName::DependentTemplate: {
7738 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7739 if (Record[Idx++]) // isIdentifier
7740 return Context.getDependentTemplateName(NNS,
7741 GetIdentifierInfo(F, Record,
7742 Idx));
7743 return Context.getDependentTemplateName(NNS,
7744 (OverloadedOperatorKind)Record[Idx++]);
7745 }
7746
7747 case TemplateName::SubstTemplateTemplateParm: {
7748 TemplateTemplateParmDecl *param
7749 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7750 if (!param) return TemplateName();
7751 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7752 return Context.getSubstTemplateTemplateParm(param, replacement);
7753 }
7754
7755 case TemplateName::SubstTemplateTemplateParmPack: {
7756 TemplateTemplateParmDecl *Param
7757 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7758 if (!Param)
7759 return TemplateName();
7760
7761 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7762 if (ArgPack.getKind() != TemplateArgument::Pack)
7763 return TemplateName();
7764
7765 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7766 }
7767 }
7768
7769 llvm_unreachable("Unhandled template name kind!");
7770}
7771
Richard Smith2bb3c342015-08-09 01:05:31 +00007772TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7773 const RecordData &Record,
7774 unsigned &Idx,
7775 bool Canonicalize) {
7776 if (Canonicalize) {
7777 // The caller wants a canonical template argument. Sometimes the AST only
7778 // wants template arguments in canonical form (particularly as the template
7779 // argument lists of template specializations) so ensure we preserve that
7780 // canonical form across serialization.
7781 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7782 return Context.getCanonicalTemplateArgument(Arg);
7783 }
7784
Guy Benyei11169dd2012-12-18 14:30:41 +00007785 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7786 switch (Kind) {
7787 case TemplateArgument::Null:
7788 return TemplateArgument();
7789 case TemplateArgument::Type:
7790 return TemplateArgument(readType(F, Record, Idx));
7791 case TemplateArgument::Declaration: {
7792 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007793 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 }
7795 case TemplateArgument::NullPtr:
7796 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7797 case TemplateArgument::Integral: {
7798 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7799 QualType T = readType(F, Record, Idx);
7800 return TemplateArgument(Context, Value, T);
7801 }
7802 case TemplateArgument::Template:
7803 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7804 case TemplateArgument::TemplateExpansion: {
7805 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007806 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007807 if (unsigned NumExpansions = Record[Idx++])
7808 NumTemplateExpansions = NumExpansions - 1;
7809 return TemplateArgument(Name, NumTemplateExpansions);
7810 }
7811 case TemplateArgument::Expression:
7812 return TemplateArgument(ReadExpr(F));
7813 case TemplateArgument::Pack: {
7814 unsigned NumArgs = Record[Idx++];
7815 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7816 for (unsigned I = 0; I != NumArgs; ++I)
7817 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007818 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 }
7820 }
7821
7822 llvm_unreachable("Unhandled template argument kind!");
7823}
7824
7825TemplateParameterList *
7826ASTReader::ReadTemplateParameterList(ModuleFile &F,
7827 const RecordData &Record, unsigned &Idx) {
7828 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7829 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7830 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7831
7832 unsigned NumParams = Record[Idx++];
7833 SmallVector<NamedDecl *, 16> Params;
7834 Params.reserve(NumParams);
7835 while (NumParams--)
7836 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7837
7838 TemplateParameterList* TemplateParams =
7839 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7840 Params.data(), Params.size(), RAngleLoc);
7841 return TemplateParams;
7842}
7843
7844void
7845ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007846ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007848 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 unsigned NumTemplateArgs = Record[Idx++];
7850 TemplArgs.reserve(NumTemplateArgs);
7851 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007852 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007853}
7854
7855/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007856void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 const RecordData &Record, unsigned &Idx) {
7858 unsigned NumDecls = Record[Idx++];
7859 Set.reserve(Context, NumDecls);
7860 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007861 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007862 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007863 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 }
7865}
7866
7867CXXBaseSpecifier
7868ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7869 const RecordData &Record, unsigned &Idx) {
7870 bool isVirtual = static_cast<bool>(Record[Idx++]);
7871 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7872 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7873 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7874 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7875 SourceRange Range = ReadSourceRange(F, Record, Idx);
7876 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7877 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7878 EllipsisLoc);
7879 Result.setInheritConstructors(inheritConstructors);
7880 return Result;
7881}
7882
Richard Smithc2bb8182015-03-24 06:36:48 +00007883CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007884ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7885 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007887 assert(NumInitializers && "wrote ctor initializers but have no inits");
7888 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7889 for (unsigned i = 0; i != NumInitializers; ++i) {
7890 TypeSourceInfo *TInfo = nullptr;
7891 bool IsBaseVirtual = false;
7892 FieldDecl *Member = nullptr;
7893 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007894
Richard Smithc2bb8182015-03-24 06:36:48 +00007895 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7896 switch (Type) {
7897 case CTOR_INITIALIZER_BASE:
7898 TInfo = GetTypeSourceInfo(F, Record, Idx);
7899 IsBaseVirtual = Record[Idx++];
7900 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007901
Richard Smithc2bb8182015-03-24 06:36:48 +00007902 case CTOR_INITIALIZER_DELEGATING:
7903 TInfo = GetTypeSourceInfo(F, Record, Idx);
7904 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007905
Richard Smithc2bb8182015-03-24 06:36:48 +00007906 case CTOR_INITIALIZER_MEMBER:
7907 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7908 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007909
Richard Smithc2bb8182015-03-24 06:36:48 +00007910 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7911 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7912 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007913 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007914
7915 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7916 Expr *Init = ReadExpr(F);
7917 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7918 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7919 bool IsWritten = Record[Idx++];
7920 unsigned SourceOrderOrNumArrayIndices;
7921 SmallVector<VarDecl *, 8> Indices;
7922 if (IsWritten) {
7923 SourceOrderOrNumArrayIndices = Record[Idx++];
7924 } else {
7925 SourceOrderOrNumArrayIndices = Record[Idx++];
7926 Indices.reserve(SourceOrderOrNumArrayIndices);
7927 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7928 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7929 }
7930
7931 CXXCtorInitializer *BOMInit;
7932 if (Type == CTOR_INITIALIZER_BASE) {
7933 BOMInit = new (Context)
7934 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7935 RParenLoc, MemberOrEllipsisLoc);
7936 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7937 BOMInit = new (Context)
7938 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7939 } else if (IsWritten) {
7940 if (Member)
7941 BOMInit = new (Context) CXXCtorInitializer(
7942 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7943 else
7944 BOMInit = new (Context)
7945 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7946 LParenLoc, Init, RParenLoc);
7947 } else {
7948 if (IndirectMember) {
7949 assert(Indices.empty() && "Indirect field improperly initialized");
7950 BOMInit = new (Context)
7951 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7952 LParenLoc, Init, RParenLoc);
7953 } else {
7954 BOMInit = CXXCtorInitializer::Create(
7955 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7956 Indices.data(), Indices.size());
7957 }
7958 }
7959
7960 if (IsWritten)
7961 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7962 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 }
7964
Richard Smithc2bb8182015-03-24 06:36:48 +00007965 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007966}
7967
7968NestedNameSpecifier *
7969ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7970 const RecordData &Record, unsigned &Idx) {
7971 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007972 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007973 for (unsigned I = 0; I != N; ++I) {
7974 NestedNameSpecifier::SpecifierKind Kind
7975 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7976 switch (Kind) {
7977 case NestedNameSpecifier::Identifier: {
7978 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7979 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7980 break;
7981 }
7982
7983 case NestedNameSpecifier::Namespace: {
7984 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7985 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7986 break;
7987 }
7988
7989 case NestedNameSpecifier::NamespaceAlias: {
7990 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7991 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7992 break;
7993 }
7994
7995 case NestedNameSpecifier::TypeSpec:
7996 case NestedNameSpecifier::TypeSpecWithTemplate: {
7997 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7998 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007999 return nullptr;
8000
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 bool Template = Record[Idx++];
8002 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8003 break;
8004 }
8005
8006 case NestedNameSpecifier::Global: {
8007 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8008 // No associated value, and there can't be a prefix.
8009 break;
8010 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008011
8012 case NestedNameSpecifier::Super: {
8013 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8014 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8015 break;
8016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 }
8018 Prev = NNS;
8019 }
8020 return NNS;
8021}
8022
8023NestedNameSpecifierLoc
8024ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8025 unsigned &Idx) {
8026 unsigned N = Record[Idx++];
8027 NestedNameSpecifierLocBuilder Builder;
8028 for (unsigned I = 0; I != N; ++I) {
8029 NestedNameSpecifier::SpecifierKind Kind
8030 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8031 switch (Kind) {
8032 case NestedNameSpecifier::Identifier: {
8033 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8034 SourceRange Range = ReadSourceRange(F, Record, Idx);
8035 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8036 break;
8037 }
8038
8039 case NestedNameSpecifier::Namespace: {
8040 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8041 SourceRange Range = ReadSourceRange(F, Record, Idx);
8042 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8043 break;
8044 }
8045
8046 case NestedNameSpecifier::NamespaceAlias: {
8047 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8048 SourceRange Range = ReadSourceRange(F, Record, Idx);
8049 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8050 break;
8051 }
8052
8053 case NestedNameSpecifier::TypeSpec:
8054 case NestedNameSpecifier::TypeSpecWithTemplate: {
8055 bool Template = Record[Idx++];
8056 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8057 if (!T)
8058 return NestedNameSpecifierLoc();
8059 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8060
8061 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8062 Builder.Extend(Context,
8063 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8064 T->getTypeLoc(), ColonColonLoc);
8065 break;
8066 }
8067
8068 case NestedNameSpecifier::Global: {
8069 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8070 Builder.MakeGlobal(Context, ColonColonLoc);
8071 break;
8072 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008073
8074 case NestedNameSpecifier::Super: {
8075 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8076 SourceRange Range = ReadSourceRange(F, Record, Idx);
8077 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8078 break;
8079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 }
8081 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008082
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 return Builder.getWithLocInContext(Context);
8084}
8085
8086SourceRange
8087ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8088 unsigned &Idx) {
8089 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8090 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8091 return SourceRange(beg, end);
8092}
8093
8094/// \brief Read an integral value
8095llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8096 unsigned BitWidth = Record[Idx++];
8097 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8098 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8099 Idx += NumWords;
8100 return Result;
8101}
8102
8103/// \brief Read a signed integral value
8104llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8105 bool isUnsigned = Record[Idx++];
8106 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8107}
8108
8109/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008110llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8111 const llvm::fltSemantics &Sem,
8112 unsigned &Idx) {
8113 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008114}
8115
8116// \brief Read a string
8117std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8118 unsigned Len = Record[Idx++];
8119 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8120 Idx += Len;
8121 return Result;
8122}
8123
Richard Smith7ed1bc92014-12-05 22:42:13 +00008124std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8125 unsigned &Idx) {
8126 std::string Filename = ReadString(Record, Idx);
8127 ResolveImportedPath(F, Filename);
8128 return Filename;
8129}
8130
Guy Benyei11169dd2012-12-18 14:30:41 +00008131VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8132 unsigned &Idx) {
8133 unsigned Major = Record[Idx++];
8134 unsigned Minor = Record[Idx++];
8135 unsigned Subminor = Record[Idx++];
8136 if (Minor == 0)
8137 return VersionTuple(Major);
8138 if (Subminor == 0)
8139 return VersionTuple(Major, Minor - 1);
8140 return VersionTuple(Major, Minor - 1, Subminor - 1);
8141}
8142
8143CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8144 const RecordData &Record,
8145 unsigned &Idx) {
8146 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8147 return CXXTemporary::Create(Context, Decl);
8148}
8149
8150DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008151 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008152}
8153
8154DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8155 return Diags.Report(Loc, DiagID);
8156}
8157
8158/// \brief Retrieve the identifier table associated with the
8159/// preprocessor.
8160IdentifierTable &ASTReader::getIdentifierTable() {
8161 return PP.getIdentifierTable();
8162}
8163
8164/// \brief Record that the given ID maps to the given switch-case
8165/// statement.
8166void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008167 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 "Already have a SwitchCase with this ID");
8169 (*CurrSwitchCaseStmts)[ID] = SC;
8170}
8171
8172/// \brief Retrieve the switch-case statement with the given ID.
8173SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008174 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 return (*CurrSwitchCaseStmts)[ID];
8176}
8177
8178void ASTReader::ClearSwitchCaseIDs() {
8179 CurrSwitchCaseStmts->clear();
8180}
8181
8182void ASTReader::ReadComments() {
8183 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008184 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 serialization::ModuleFile *> >::iterator
8186 I = CommentsCursors.begin(),
8187 E = CommentsCursors.end();
8188 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008189 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008190 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 serialization::ModuleFile &F = *I->second;
8192 SavedStreamPosition SavedPosition(Cursor);
8193
8194 RecordData Record;
8195 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008196 llvm::BitstreamEntry Entry =
8197 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008198
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008199 switch (Entry.Kind) {
8200 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8201 case llvm::BitstreamEntry::Error:
8202 Error("malformed block record in AST file");
8203 return;
8204 case llvm::BitstreamEntry::EndBlock:
8205 goto NextCursor;
8206 case llvm::BitstreamEntry::Record:
8207 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 }
8210
8211 // Read a record.
8212 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008213 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 case COMMENTS_RAW_COMMENT: {
8215 unsigned Idx = 0;
8216 SourceRange SR = ReadSourceRange(F, Record, Idx);
8217 RawComment::CommentKind Kind =
8218 (RawComment::CommentKind) Record[Idx++];
8219 bool IsTrailingComment = Record[Idx++];
8220 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008221 Comments.push_back(new (Context) RawComment(
8222 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8223 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 break;
8225 }
8226 }
8227 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008228 NextCursor:
8229 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008231}
8232
Richard Smithcd45dbc2014-04-19 03:48:30 +00008233std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8234 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008235 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008236 return M->getFullModuleName();
8237
8238 // Otherwise, use the name of the top-level module the decl is within.
8239 if (ModuleFile *M = getOwningModuleFile(D))
8240 return M->ModuleName;
8241
8242 // Not from a module.
8243 return "";
8244}
8245
Guy Benyei11169dd2012-12-18 14:30:41 +00008246void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008247 while (!PendingIdentifierInfos.empty() ||
8248 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008249 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008250 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 // If any identifiers with corresponding top-level declarations have
8252 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008253 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8254 TopLevelDeclsMap;
8255 TopLevelDeclsMap TopLevelDecls;
8256
Guy Benyei11169dd2012-12-18 14:30:41 +00008257 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008258 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008259 SmallVector<uint32_t, 4> DeclIDs =
8260 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008261 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008262
8263 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008265
Richard Smith851072e2014-05-19 20:59:20 +00008266 // For each decl chain that we wanted to complete while deserializing, mark
8267 // it as "still needs to be completed".
8268 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8269 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8270 }
8271 PendingIncompleteDeclChains.clear();
8272
Guy Benyei11169dd2012-12-18 14:30:41 +00008273 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008274 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008275 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 PendingDeclChains.clear();
8277
Douglas Gregor6168bd22013-02-18 15:53:43 +00008278 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008279 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8280 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008281 IdentifierInfo *II = TLD->first;
8282 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008283 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008284 }
8285 }
8286
Guy Benyei11169dd2012-12-18 14:30:41 +00008287 // Load any pending macro definitions.
8288 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008289 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8290 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8291 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8292 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008293 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008294 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008295 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008296 if (Info.M->Kind != MK_ImplicitModule &&
8297 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008298 resolvePendingMacro(II, Info);
8299 }
8300 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008301 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008302 ++IDIdx) {
8303 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008304 if (Info.M->Kind == MK_ImplicitModule ||
8305 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008306 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 }
8308 }
8309 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008310
8311 // Wire up the DeclContexts for Decls that we delayed setting until
8312 // recursive loading is completed.
8313 while (!PendingDeclContextInfos.empty()) {
8314 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8315 PendingDeclContextInfos.pop_front();
8316 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8317 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8318 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8319 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008320
Richard Smithd1c46742014-04-30 02:24:17 +00008321 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008322 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008323 auto Update = PendingUpdateRecords.pop_back_val();
8324 ReadingKindTracker ReadingKind(Read_Decl, *this);
8325 loadDeclUpdateRecords(Update.first, Update.second);
8326 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008327 }
Richard Smith8a639892015-01-24 01:07:20 +00008328
8329 // At this point, all update records for loaded decls are in place, so any
8330 // fake class definitions should have become real.
8331 assert(PendingFakeDefinitionData.empty() &&
8332 "faked up a class definition but never saw the real one");
8333
Guy Benyei11169dd2012-12-18 14:30:41 +00008334 // If we deserialized any C++ or Objective-C class definitions, any
8335 // Objective-C protocol definitions, or any redeclarable templates, make sure
8336 // that all redeclarations point to the definitions. Note that this can only
8337 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008338 for (Decl *D : PendingDefinitions) {
8339 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008340 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 // Make sure that the TagType points at the definition.
8342 const_cast<TagType*>(TagT)->decl = TD;
8343 }
Richard Smith8ce51082015-03-11 01:44:51 +00008344
Craig Topperc6914d02014-08-25 04:15:02 +00008345 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008346 for (auto *R = getMostRecentExistingDecl(RD); R;
8347 R = R->getPreviousDecl()) {
8348 assert((R == D) ==
8349 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008350 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008351 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 }
8354
8355 continue;
8356 }
Richard Smith8ce51082015-03-11 01:44:51 +00008357
Craig Topperc6914d02014-08-25 04:15:02 +00008358 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008359 // Make sure that the ObjCInterfaceType points at the definition.
8360 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8361 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008362
8363 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8364 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8365
Guy Benyei11169dd2012-12-18 14:30:41 +00008366 continue;
8367 }
Richard Smith8ce51082015-03-11 01:44:51 +00008368
Craig Topperc6914d02014-08-25 04:15:02 +00008369 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008370 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8371 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8372
Guy Benyei11169dd2012-12-18 14:30:41 +00008373 continue;
8374 }
Richard Smith8ce51082015-03-11 01:44:51 +00008375
Craig Topperc6914d02014-08-25 04:15:02 +00008376 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008377 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8378 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 }
8380 PendingDefinitions.clear();
8381
8382 // Load the bodies of any functions or methods we've encountered. We do
8383 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008384 // have been fully wired up (hasBody relies on this).
8385 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008386 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8387 PBEnd = PendingBodies.end();
8388 PB != PBEnd; ++PB) {
8389 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8390 // FIXME: Check for =delete/=default?
8391 // FIXME: Complain about ODR violations here?
8392 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8393 FD->setLazyBody(PB->second);
8394 continue;
8395 }
8396
8397 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8398 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8399 MD->setLazyBody(PB->second);
8400 }
8401 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008402
8403 // Do some cleanup.
8404 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8405 getContext().deduplicateMergedDefinitonsFor(ND);
8406 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008407}
8408
8409void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008410 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8411 return;
8412
Richard Smitha0ce9c42014-07-29 23:23:27 +00008413 // Trigger the import of the full definition of each class that had any
8414 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008415 // These updates may in turn find and diagnose some ODR failures, so take
8416 // ownership of the set first.
8417 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8418 PendingOdrMergeFailures.clear();
8419 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008420 Merge.first->buildLookup();
8421 Merge.first->decls_begin();
8422 Merge.first->bases_begin();
8423 Merge.first->vbases_begin();
8424 for (auto *RD : Merge.second) {
8425 RD->decls_begin();
8426 RD->bases_begin();
8427 RD->vbases_begin();
8428 }
8429 }
8430
8431 // For each declaration from a merged context, check that the canonical
8432 // definition of that context also contains a declaration of the same
8433 // entity.
8434 //
8435 // Caution: this loop does things that might invalidate iterators into
8436 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8437 while (!PendingOdrMergeChecks.empty()) {
8438 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8439
8440 // FIXME: Skip over implicit declarations for now. This matters for things
8441 // like implicitly-declared special member functions. This isn't entirely
8442 // correct; we can end up with multiple unmerged declarations of the same
8443 // implicit entity.
8444 if (D->isImplicit())
8445 continue;
8446
8447 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008448
8449 bool Found = false;
8450 const Decl *DCanon = D->getCanonicalDecl();
8451
Richard Smith01bdb7a2014-08-28 05:44:07 +00008452 for (auto RI : D->redecls()) {
8453 if (RI->getLexicalDeclContext() == CanonDef) {
8454 Found = true;
8455 break;
8456 }
8457 }
8458 if (Found)
8459 continue;
8460
Richard Smith0f4e2c42015-08-06 04:23:48 +00008461 // Quick check failed, time to do the slow thing. Note, we can't just
8462 // look up the name of D in CanonDef here, because the member that is
8463 // in CanonDef might not be found by name lookup (it might have been
8464 // replaced by a more recent declaration in the lookup table), and we
8465 // can't necessarily find it in the redeclaration chain because it might
8466 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008467 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008468 for (auto *CanonMember : CanonDef->decls()) {
8469 if (CanonMember->getCanonicalDecl() == DCanon) {
8470 // This can happen if the declaration is merely mergeable and not
8471 // actually redeclarable (we looked for redeclarations earlier).
8472 //
8473 // FIXME: We should be able to detect this more efficiently, without
8474 // pulling in all of the members of CanonDef.
8475 Found = true;
8476 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008477 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008478 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8479 if (ND->getDeclName() == D->getDeclName())
8480 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008481 }
8482
8483 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008484 // The AST doesn't like TagDecls becoming invalid after they've been
8485 // completed. We only really need to mark FieldDecls as invalid here.
8486 if (!isa<TagDecl>(D))
8487 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008488
8489 // Ensure we don't accidentally recursively enter deserialization while
8490 // we're producing our diagnostic.
8491 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008492
8493 std::string CanonDefModule =
8494 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8495 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8496 << D << getOwningModuleNameForDiagnostic(D)
8497 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8498
8499 if (Candidates.empty())
8500 Diag(cast<Decl>(CanonDef)->getLocation(),
8501 diag::note_module_odr_violation_no_possible_decls) << D;
8502 else {
8503 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8504 Diag(Candidates[I]->getLocation(),
8505 diag::note_module_odr_violation_possible_decl)
8506 << Candidates[I];
8507 }
8508
8509 DiagnosedOdrMergeFailures.insert(CanonDef);
8510 }
8511 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008512
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008513 if (OdrMergeFailures.empty())
8514 return;
8515
8516 // Ensure we don't accidentally recursively enter deserialization while
8517 // we're producing our diagnostics.
8518 Deserializing RecursionGuard(this);
8519
Richard Smithcd45dbc2014-04-19 03:48:30 +00008520 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008521 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008522 // If we've already pointed out a specific problem with this class, don't
8523 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008524 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008525 continue;
8526
8527 bool Diagnosed = false;
8528 for (auto *RD : Merge.second) {
8529 // Multiple different declarations got merged together; tell the user
8530 // where they came from.
8531 if (Merge.first != RD) {
8532 // FIXME: Walk the definition, figure out what's different,
8533 // and diagnose that.
8534 if (!Diagnosed) {
8535 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8536 Diag(Merge.first->getLocation(),
8537 diag::err_module_odr_violation_different_definitions)
8538 << Merge.first << Module.empty() << Module;
8539 Diagnosed = true;
8540 }
8541
8542 Diag(RD->getLocation(),
8543 diag::note_module_odr_violation_different_definitions)
8544 << getOwningModuleNameForDiagnostic(RD);
8545 }
8546 }
8547
8548 if (!Diagnosed) {
8549 // All definitions are updates to the same declaration. This happens if a
8550 // module instantiates the declaration of a class template specialization
8551 // and two or more other modules instantiate its definition.
8552 //
8553 // FIXME: Indicate which modules had instantiations of this definition.
8554 // FIXME: How can this even happen?
8555 Diag(Merge.first->getLocation(),
8556 diag::err_module_odr_violation_different_instantiations)
8557 << Merge.first;
8558 }
8559 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008560}
8561
Richard Smithce18a182015-07-14 00:26:00 +00008562void ASTReader::StartedDeserializing() {
8563 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8564 ReadTimer->startTimer();
8565}
8566
Guy Benyei11169dd2012-12-18 14:30:41 +00008567void ASTReader::FinishedDeserializing() {
8568 assert(NumCurrentElementsDeserializing &&
8569 "FinishedDeserializing not paired with StartedDeserializing");
8570 if (NumCurrentElementsDeserializing == 1) {
8571 // We decrease NumCurrentElementsDeserializing only after pending actions
8572 // are finished, to avoid recursively re-calling finishPendingActions().
8573 finishPendingActions();
8574 }
8575 --NumCurrentElementsDeserializing;
8576
Richard Smitha0ce9c42014-07-29 23:23:27 +00008577 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008578 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008579 while (!PendingExceptionSpecUpdates.empty()) {
8580 auto Updates = std::move(PendingExceptionSpecUpdates);
8581 PendingExceptionSpecUpdates.clear();
8582 for (auto Update : Updates) {
8583 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008584 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008585 if (auto *Listener = Context.getASTMutationListener())
8586 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008587 for (auto *Redecl : Update.second->redecls())
8588 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008589 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008590 }
8591
Richard Smithce18a182015-07-14 00:26:00 +00008592 if (ReadTimer)
8593 ReadTimer->stopTimer();
8594
Richard Smith0f4e2c42015-08-06 04:23:48 +00008595 diagnoseOdrViolations();
8596
Richard Smith04d05b52014-03-23 00:27:18 +00008597 // We are not in recursive loading, so it's safe to pass the "interesting"
8598 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008599 if (Consumer)
8600 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008601 }
8602}
8603
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008604void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008605 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8606 // Remove any fake results before adding any real ones.
8607 auto It = PendingFakeLookupResults.find(II);
8608 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008609 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008610 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008611 // FIXME: this works around module+PCH performance issue.
8612 // Rather than erase the result from the map, which is O(n), just clear
8613 // the vector of NamedDecls.
8614 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008615 }
8616 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008617
8618 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8619 SemaObj->TUScope->AddDecl(D);
8620 } else if (SemaObj->TUScope) {
8621 // Adding the decl to IdResolver may have failed because it was already in
8622 // (even though it was not added in scope). If it is already in, make sure
8623 // it gets in the scope as well.
8624 if (std::find(SemaObj->IdResolver.begin(Name),
8625 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8626 SemaObj->TUScope->AddDecl(D);
8627 }
8628}
8629
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008630ASTReader::ASTReader(
8631 Preprocessor &PP, ASTContext &Context,
8632 const PCHContainerReader &PCHContainerRdr,
8633 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
8634 StringRef isysroot, bool DisableValidation,
8635 bool AllowASTWithCompilerErrors,
8636 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8637 bool UseGlobalIndex,
8638 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008639 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008640 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008641 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008642 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008643 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008644 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008645 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008646 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8647 AllowConfigurationMismatch(AllowConfigurationMismatch),
8648 ValidateSystemInputs(ValidateSystemInputs),
8649 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008650 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8651 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8652 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8653 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008654 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8655 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8656 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8657 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8658 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8659 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008660 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008661 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00008662
8663 for (const auto &Ext : Extensions) {
8664 auto BlockName = Ext->getExtensionMetadata().BlockName;
8665 auto Known = ModuleFileExtensions.find(BlockName);
8666 if (Known != ModuleFileExtensions.end()) {
8667 Diags.Report(diag::warn_duplicate_module_file_extension)
8668 << BlockName;
8669 continue;
8670 }
8671
8672 ModuleFileExtensions.insert({BlockName, Ext});
8673 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008674}
8675
8676ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008677 if (OwnsDeserializationListener)
8678 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008679}