blob: 08fd923f47db240b7809b542b9a198795466cc42 [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"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000092bool ChainedASTReaderListener::ReadTargetOptions(
93 const TargetOptions &TargetOpts, bool Complain,
94 bool AllowCompatibleDifferences) {
95 return First->ReadTargetOptions(TargetOpts, Complain,
96 AllowCompatibleDifferences) ||
97 Second->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000099}
100bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000101 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000102 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
103 Second->ReadDiagnosticOptions(DiagOpts, Complain);
104}
105bool
106ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
107 bool Complain) {
108 return First->ReadFileSystemOptions(FSOpts, Complain) ||
109 Second->ReadFileSystemOptions(FSOpts, Complain);
110}
111
112bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000113 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
114 bool Complain) {
115 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain) ||
117 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000119}
120bool ChainedASTReaderListener::ReadPreprocessorOptions(
121 const PreprocessorOptions &PPOpts, bool Complain,
122 std::string &SuggestedPredefines) {
123 return First->ReadPreprocessorOptions(PPOpts, Complain,
124 SuggestedPredefines) ||
125 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
126}
127void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
128 unsigned Value) {
129 First->ReadCounter(M, Value);
130 Second->ReadCounter(M, Value);
131}
132bool ChainedASTReaderListener::needsInputFileVisitation() {
133 return First->needsInputFileVisitation() ||
134 Second->needsInputFileVisitation();
135}
136bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
137 return First->needsSystemInputFileVisitation() ||
138 Second->needsSystemInputFileVisitation();
139}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000140void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
141 First->visitModuleFile(Filename);
142 Second->visitModuleFile(Filename);
143}
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000145 bool isSystem,
146 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000147 bool Continue = false;
148 if (First->needsInputFileVisitation() &&
149 (!isSystem || First->needsSystemInputFileVisitation()))
150 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
151 if (Second->needsInputFileVisitation() &&
152 (!isSystem || Second->needsSystemInputFileVisitation()))
153 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
154 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000155}
156
Guy Benyei11169dd2012-12-18 14:30:41 +0000157//===----------------------------------------------------------------------===//
158// PCH validator implementation
159//===----------------------------------------------------------------------===//
160
161ASTReaderListener::~ASTReaderListener() {}
162
163/// \brief Compare the given set of language options against an existing set of
164/// language options.
165///
166/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000167/// \param AllowCompatibleDifferences If true, differences between compatible
168/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000169///
170/// \returns true if the languagae options mis-match, false otherwise.
171static bool checkLanguageOptions(const LangOptions &LangOpts,
172 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173 DiagnosticsEngine *Diags,
174 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000175#define LANGOPT(Name, Bits, Default, Description) \
176 if (ExistingLangOpts.Name != LangOpts.Name) { \
177 if (Diags) \
178 Diags->Report(diag::err_pch_langopt_mismatch) \
179 << Description << LangOpts.Name << ExistingLangOpts.Name; \
180 return true; \
181 }
182
183#define VALUE_LANGOPT(Name, Bits, Default, Description) \
184 if (ExistingLangOpts.Name != LangOpts.Name) { \
185 if (Diags) \
186 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 << Description; \
188 return true; \
189 }
190
191#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
192 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
193 if (Diags) \
194 Diags->Report(diag::err_pch_langopt_value_mismatch) \
195 << Description; \
196 return true; \
197 }
198
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000199#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
200 if (!AllowCompatibleDifferences) \
201 LANGOPT(Name, Bits, Default, Description)
202
203#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
204 if (!AllowCompatibleDifferences) \
205 ENUM_LANGOPT(Name, Bits, Default, Description)
206
Guy Benyei11169dd2012-12-18 14:30:41 +0000207#define BENIGN_LANGOPT(Name, Bits, Default, Description)
208#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
209#include "clang/Basic/LangOptions.def"
210
211 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
212 if (Diags)
213 Diags->Report(diag::err_pch_langopt_value_mismatch)
214 << "target Objective-C runtime";
215 return true;
216 }
217
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000218 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
219 LangOpts.CommentOpts.BlockCommandNames) {
220 if (Diags)
221 Diags->Report(diag::err_pch_langopt_value_mismatch)
222 << "block command names";
223 return true;
224 }
225
Guy Benyei11169dd2012-12-18 14:30:41 +0000226 return false;
227}
228
229/// \brief Compare the given set of target options against an existing set of
230/// target options.
231///
232/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
233///
234/// \returns true if the target options mis-match, false otherwise.
235static bool checkTargetOptions(const TargetOptions &TargetOpts,
236 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000237 DiagnosticsEngine *Diags,
238 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000239#define CHECK_TARGET_OPT(Field, Name) \
240 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_targetopt_mismatch) \
243 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
244 return true; \
245 }
246
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000247 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000250
251 // We can tolerate different CPUs in many cases, notably when one CPU
252 // supports a strict superset of another. When allowing compatible
253 // differences skip this check.
254 if (!AllowCompatibleDifferences)
255 CHECK_TARGET_OPT(CPU, "target CPU");
256
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#undef CHECK_TARGET_OPT
258
259 // Compare feature sets.
260 SmallVector<StringRef, 4> ExistingFeatures(
261 ExistingTargetOpts.FeaturesAsWritten.begin(),
262 ExistingTargetOpts.FeaturesAsWritten.end());
263 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
264 TargetOpts.FeaturesAsWritten.end());
265 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
266 std::sort(ReadFeatures.begin(), ReadFeatures.end());
267
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268 // We compute the set difference in both directions explicitly so that we can
269 // diagnose the differences differently.
270 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
271 std::set_difference(
272 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
273 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
274 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
275 ExistingFeatures.begin(), ExistingFeatures.end(),
276 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000278 // If we are allowing compatible differences and the read feature set is
279 // a strict subset of the existing feature set, there is nothing to diagnose.
280 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
281 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000283 if (Diags) {
284 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000285 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 << /* is-existing-feature */ false << Feature;
287 for (StringRef Feature : UnmatchedExistingFeatures)
288 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
289 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290 }
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
295bool
296PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000297 bool Complain,
298 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 const LangOptions &ExistingLangOpts = PP.getLangOpts();
300 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 Complain ? &Reader.Diags : nullptr,
302 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000303}
304
305bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 bool Complain,
307 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
309 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 Complain ? &Reader.Diags : nullptr,
311 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314namespace {
315 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
316 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000317 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
318 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
Ben Langmuirb92de022014-04-29 16:25:26 +0000321static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
322 DiagnosticsEngine &Diags,
323 bool Complain) {
324 typedef DiagnosticsEngine::Level Level;
325
326 // Check current mappings for new -Werror mappings, and the stored mappings
327 // for cases that were explicitly mapped to *not* be errors that are now
328 // errors because of options like -Werror.
329 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
330
331 for (DiagnosticsEngine *MappingSource : MappingSources) {
332 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
333 diag::kind DiagID = DiagIDMappingPair.first;
334 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
335 if (CurLevel < DiagnosticsEngine::Error)
336 continue; // not significant
337 Level StoredLevel =
338 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
339 if (StoredLevel < DiagnosticsEngine::Error) {
340 if (Complain)
341 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
342 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
343 return true;
344 }
345 }
346 }
347
348 return false;
349}
350
Alp Tokerac4e8e52014-06-22 21:58:33 +0000351static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
352 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
353 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
354 return true;
355 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000356}
357
358static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
359 DiagnosticsEngine &Diags,
360 bool IsSystem, bool Complain) {
361 // Top-level options
362 if (IsSystem) {
363 if (Diags.getSuppressSystemWarnings())
364 return false;
365 // If -Wsystem-headers was not enabled before, be conservative
366 if (StoredDiags.getSuppressSystemWarnings()) {
367 if (Complain)
368 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
369 return true;
370 }
371 }
372
373 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
376 return true;
377 }
378
379 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
380 !StoredDiags.getEnableAllWarnings()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
383 return true;
384 }
385
386 if (isExtHandlingFromDiagsError(Diags) &&
387 !isExtHandlingFromDiagsError(StoredDiags)) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
390 return true;
391 }
392
393 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
394}
395
396bool PCHValidator::ReadDiagnosticOptions(
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
398 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
399 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000401 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000402 // This should never fail, because we would have processed these options
403 // before writing them to an ASTFile.
404 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
405
406 ModuleManager &ModuleMgr = Reader.getModuleManager();
407 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
408
409 // If the original import came from a file explicitly generated by the user,
410 // don't check the diagnostic mappings.
411 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000412 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
414 // the transitive closure of its imports, since unrelated modules cannot be
415 // imported until after this module finishes validation.
416 ModuleFile *TopImport = *ModuleMgr.rbegin();
417 while (!TopImport->ImportedBy.empty())
418 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000419 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 return false;
421
422 StringRef ModuleName = TopImport->ModuleName;
423 assert(!ModuleName.empty() && "diagnostic options read before module name");
424
425 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
426 assert(M && "missing module");
427
428 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
429 // contains the union of their flags.
430 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
431}
432
Guy Benyei11169dd2012-12-18 14:30:41 +0000433/// \brief Collect the macro definitions provided by the given preprocessor
434/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000435static void
436collectMacroDefinitions(const PreprocessorOptions &PPOpts,
437 MacroDefinitionsMap &Macros,
438 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
440 StringRef Macro = PPOpts.Macros[I].first;
441 bool IsUndef = PPOpts.Macros[I].second;
442
443 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
444 StringRef MacroName = MacroPair.first;
445 StringRef MacroBody = MacroPair.second;
446
447 // For an #undef'd macro, we only care about the name.
448 if (IsUndef) {
449 if (MacroNames && !Macros.count(MacroName))
450 MacroNames->push_back(MacroName);
451
452 Macros[MacroName] = std::make_pair("", true);
453 continue;
454 }
455
456 // For a #define'd macro, figure out the actual definition.
457 if (MacroName.size() == Macro.size())
458 MacroBody = "1";
459 else {
460 // Note: GCC drops anything following an end-of-line character.
461 StringRef::size_type End = MacroBody.find_first_of("\n\r");
462 MacroBody = MacroBody.substr(0, End);
463 }
464
465 if (MacroNames && !Macros.count(MacroName))
466 MacroNames->push_back(MacroName);
467 Macros[MacroName] = std::make_pair(MacroBody, false);
468 }
469}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471/// \brief Check the preprocessor options deserialized from the control block
472/// against the preprocessor options in an existing preprocessor.
473///
474/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
475static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
476 const PreprocessorOptions &ExistingPPOpts,
477 DiagnosticsEngine *Diags,
478 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000479 std::string &SuggestedPredefines,
480 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 // Check macro definitions.
482 MacroDefinitionsMap ASTFileMacros;
483 collectMacroDefinitions(PPOpts, ASTFileMacros);
484 MacroDefinitionsMap ExistingMacros;
485 SmallVector<StringRef, 4> ExistingMacroNames;
486 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
487
488 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
489 // Dig out the macro definition in the existing preprocessor options.
490 StringRef MacroName = ExistingMacroNames[I];
491 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
492
493 // Check whether we know anything about this macro name or not.
494 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
495 = ASTFileMacros.find(MacroName);
496 if (Known == ASTFileMacros.end()) {
497 // FIXME: Check whether this identifier was referenced anywhere in the
498 // AST file. If so, we should reject the AST file. Unfortunately, this
499 // information isn't in the control block. What shall we do about it?
500
501 if (Existing.second) {
502 SuggestedPredefines += "#undef ";
503 SuggestedPredefines += MacroName.str();
504 SuggestedPredefines += '\n';
505 } else {
506 SuggestedPredefines += "#define ";
507 SuggestedPredefines += MacroName.str();
508 SuggestedPredefines += ' ';
509 SuggestedPredefines += Existing.first.str();
510 SuggestedPredefines += '\n';
511 }
512 continue;
513 }
514
515 // If the macro was defined in one but undef'd in the other, we have a
516 // conflict.
517 if (Existing.second != Known->second.second) {
518 if (Diags) {
519 Diags->Report(diag::err_pch_macro_def_undef)
520 << MacroName << Known->second.second;
521 }
522 return true;
523 }
524
525 // If the macro was #undef'd in both, or if the macro bodies are identical,
526 // it's fine.
527 if (Existing.second || Existing.first == Known->second.first)
528 continue;
529
530 // The macro bodies differ; complain.
531 if (Diags) {
532 Diags->Report(diag::err_pch_macro_def_conflict)
533 << MacroName << Known->second.first << Existing.first;
534 }
535 return true;
536 }
537
538 // Check whether we're using predefines.
539 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
540 if (Diags) {
541 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
542 }
543 return true;
544 }
545
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000546 // Detailed record is important since it is used for the module cache hash.
547 if (LangOpts.Modules &&
548 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
549 if (Diags) {
550 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
551 }
552 return true;
553 }
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Compute the #include and #include_macros lines we need.
556 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
557 StringRef File = ExistingPPOpts.Includes[I];
558 if (File == ExistingPPOpts.ImplicitPCHInclude)
559 continue;
560
561 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
562 != PPOpts.Includes.end())
563 continue;
564
565 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000566 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 SuggestedPredefines += "\"\n";
568 }
569
570 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
571 StringRef File = ExistingPPOpts.MacroIncludes[I];
572 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
573 File)
574 != PPOpts.MacroIncludes.end())
575 continue;
576
577 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n##\n";
580 }
581
582 return false;
583}
584
585bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
586 bool Complain,
587 std::string &SuggestedPredefines) {
588 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
589
590 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000591 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000593 SuggestedPredefines,
594 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595}
596
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000597/// Check the header search options deserialized from the control block
598/// against the header search options in an existing preprocessor.
599///
600/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
601static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
602 StringRef SpecificModuleCachePath,
603 StringRef ExistingModuleCachePath,
604 DiagnosticsEngine *Diags,
605 const LangOptions &LangOpts) {
606 if (LangOpts.Modules) {
607 if (SpecificModuleCachePath != ExistingModuleCachePath) {
608 if (Diags)
609 Diags->Report(diag::err_pch_modulecache_mismatch)
610 << SpecificModuleCachePath << ExistingModuleCachePath;
611 return true;
612 }
613 }
614
615 return false;
616}
617
618bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
619 StringRef SpecificModuleCachePath,
620 bool Complain) {
621 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
622 PP.getHeaderSearchInfo().getModuleCachePath(),
623 Complain ? &Reader.Diags : nullptr,
624 PP.getLangOpts());
625}
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
628 PP.setCounterValue(Value);
629}
630
631//===----------------------------------------------------------------------===//
632// AST reader implementation
633//===----------------------------------------------------------------------===//
634
Nico Weber824285e2014-05-08 04:26:47 +0000635void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
636 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000638 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639}
640
641
642
643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
646
647
648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 using namespace llvm::support;
651 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
652 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000660 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
661 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
662 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 Args.push_back(Reader.getLocalIdentifier(
672 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
674 return SelTable.getSelector(N, Args.data());
675}
676
677ASTSelectorLookupTrait::data_type
678ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
679 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000680 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000681
682 data_type Result;
683
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 Result.ID = Reader.getGlobalSelectorID(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000686 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
688 Result.InstanceBits = FullInstanceBits & 0x3;
689 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
690 Result.FactoryBits = FullFactoryBits & 0x3;
691 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
692 unsigned NumInstanceMethods = FullInstanceBits >> 3;
693 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000694
695 // Load instance methods
696 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
698 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Result.Instance.push_back(Method);
700 }
701
702 // Load factory methods
703 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Factory.push_back(Method);
707 }
708
709 return Result;
710}
711
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000712unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
713 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714}
715
716std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000717ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 using namespace llvm::support;
719 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
720 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return std::make_pair(KeyLen, DataLen);
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::internal_key_type
725ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000727 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728}
729
Douglas Gregordcf25082013-02-11 18:16:18 +0000730/// \brief Whether the given identifier is "interesting".
731static bool isInterestingIdentifier(IdentifierInfo &II) {
732 return II.isPoisoned() ||
733 II.isExtensionToken() ||
734 II.getObjCOrBuiltinID() ||
735 II.hasRevertedTokenIDToIdentifier() ||
736 II.hadMacroDefinition() ||
737 II.getFETokenInfo<void>();
738}
739
Guy Benyei11169dd2012-12-18 14:30:41 +0000740IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
741 const unsigned char* d,
742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 using namespace llvm::support;
744 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 bool IsInteresting = RawID & 0x01;
746
747 // Wipe out the "is interesting" bit.
748 RawID = RawID >> 1;
749
750 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
751 if (!IsInteresting) {
752 // For uninteresting identifiers, just build the IdentifierInfo
753 // and associate it with the persistent ID.
754 IdentifierInfo *II = KnownII;
755 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000756 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 KnownII = II;
758 }
759 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 if (!II->isFromAST()) {
761 bool WasInteresting = isInterestingIdentifier(*II);
762 II->setIsFromAST();
763 if (WasInteresting)
764 II->setChangedSinceDeserialization();
765 }
766 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 return II;
768 }
769
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 bool CPlusPlusOperatorKeyword = Bits & 0x01;
773 Bits >>= 1;
774 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
775 Bits >>= 1;
776 bool Poisoned = Bits & 0x01;
777 Bits >>= 1;
778 bool ExtensionToken = Bits & 0x01;
779 Bits >>= 1;
780 bool hadMacroDefinition = Bits & 0x01;
781 Bits >>= 1;
782
783 assert(Bits == 0 && "Extra bits in the identifier?");
784 DataLen -= 8;
785
786 // Build the IdentifierInfo itself and link the identifier ID with
787 // the new IdentifierInfo.
788 IdentifierInfo *II = KnownII;
789 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000790 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 KnownII = II;
792 }
793 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000794 if (!II->isFromAST()) {
795 bool WasInteresting = isInterestingIdentifier(*II);
796 II->setIsFromAST();
797 if (WasInteresting)
798 II->setChangedSinceDeserialization();
799 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000800
801 // Set or check the various bits in the IdentifierInfo structure.
802 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000803 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 II->RevertTokenIDToIdentifier();
805 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
806 assert(II->isExtensionToken() == ExtensionToken &&
807 "Incorrect extension token flag");
808 (void)ExtensionToken;
809 if (Poisoned)
810 II->setIsPoisoned(true);
811 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
812 "Incorrect C++ operator keyword flag");
813 (void)CPlusPlusOperatorKeyword;
814
815 // If this identifier is a macro, deserialize the macro
816 // definition.
817 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 uint32_t MacroDirectivesOffset =
819 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000820 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821
Richard Smithd7329392015-04-21 21:46:32 +0000822 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 }
824
825 Reader.SetIdentifierInfo(ID, II);
826
827 // Read all of the declarations visible at global scope with this
828 // name.
829 if (DataLen > 0) {
830 SmallVector<uint32_t, 4> DeclIDs;
831 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 DeclIDs.push_back(Reader.getGlobalDeclID(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 Reader.SetGloballyVisibleDecls(II, DeclIDs);
835 }
836
837 return II;
838}
839
840unsigned
841ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
842 llvm::FoldingSetNodeID ID;
843 ID.AddInteger(Key.Kind);
844
845 switch (Key.Kind) {
846 case DeclarationName::Identifier:
847 case DeclarationName::CXXLiteralOperatorName:
848 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
849 break;
850 case DeclarationName::ObjCZeroArgSelector:
851 case DeclarationName::ObjCOneArgSelector:
852 case DeclarationName::ObjCMultiArgSelector:
853 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
854 break;
855 case DeclarationName::CXXOperatorName:
856 ID.AddInteger((OverloadedOperatorKind)Key.Data);
857 break;
858 case DeclarationName::CXXConstructorName:
859 case DeclarationName::CXXDestructorName:
860 case DeclarationName::CXXConversionFunctionName:
861 case DeclarationName::CXXUsingDirective:
862 break;
863 }
864
865 return ID.ComputeHash();
866}
867
868ASTDeclContextNameLookupTrait::internal_key_type
869ASTDeclContextNameLookupTrait::GetInternalKey(
870 const external_key_type& Name) const {
871 DeclNameKey Key;
872 Key.Kind = Name.getNameKind();
873 switch (Name.getNameKind()) {
874 case DeclarationName::Identifier:
875 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
876 break;
877 case DeclarationName::ObjCZeroArgSelector:
878 case DeclarationName::ObjCOneArgSelector:
879 case DeclarationName::ObjCMultiArgSelector:
880 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
881 break;
882 case DeclarationName::CXXOperatorName:
883 Key.Data = Name.getCXXOverloadedOperator();
884 break;
885 case DeclarationName::CXXLiteralOperatorName:
886 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
887 break;
888 case DeclarationName::CXXConstructorName:
889 case DeclarationName::CXXDestructorName:
890 case DeclarationName::CXXConversionFunctionName:
891 case DeclarationName::CXXUsingDirective:
892 Key.Data = 0;
893 break;
894 }
895
896 return Key;
897}
898
899std::pair<unsigned, unsigned>
900ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000901 using namespace llvm::support;
902 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
903 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 return std::make_pair(KeyLen, DataLen);
905}
906
907ASTDeclContextNameLookupTrait::internal_key_type
908ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000910
911 DeclNameKey Key;
912 Key.Kind = (DeclarationName::NameKind)*d++;
913 switch (Key.Kind) {
914 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 Key.Data = (uint64_t)Reader.getLocalIdentifier(
916 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 break;
918 case DeclarationName::ObjCZeroArgSelector:
919 case DeclarationName::ObjCOneArgSelector:
920 case DeclarationName::ObjCMultiArgSelector:
921 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 (uint64_t)Reader.getLocalSelector(
923 F, endian::readNext<uint32_t, little, unaligned>(
924 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXOperatorName:
927 Key.Data = *d++; // OverloadedOperatorKind
928 break;
929 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 Key.Data = (uint64_t)Reader.getLocalIdentifier(
931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXConstructorName:
934 case DeclarationName::CXXDestructorName:
935 case DeclarationName::CXXConversionFunctionName:
936 case DeclarationName::CXXUsingDirective:
937 Key.Data = 0;
938 break;
939 }
940
941 return Key;
942}
943
944ASTDeclContextNameLookupTrait::data_type
945ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
946 const unsigned char* d,
947 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 using namespace llvm::support;
949 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000950 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
951 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 return std::make_pair(Start, Start + NumDecls);
953}
954
955bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000956 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 const std::pair<uint64_t, uint64_t> &Offsets,
958 DeclContextInfo &Info) {
959 SavedStreamPosition SavedPosition(Cursor);
960 // First the lexical decls.
961 if (Offsets.first != 0) {
962 Cursor.JumpToBit(Offsets.first);
963
964 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000965 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000967 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 if (RecCode != DECL_CONTEXT_LEXICAL) {
969 Error("Expected lexical block");
970 return true;
971 }
972
Chris Lattner0e6c9402013-01-20 02:38:54 +0000973 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
974 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 }
976
977 // Now the lookup table.
978 if (Offsets.second != 0) {
979 Cursor.JumpToBit(Offsets.second);
980
981 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000982 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000984 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 if (RecCode != DECL_CONTEXT_VISIBLE) {
986 Error("Expected visible lookup table block");
987 return true;
988 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000989 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
990 (const unsigned char *)Blob.data() + Record[0],
991 (const unsigned char *)Blob.data() + sizeof(uint32_t),
992 (const unsigned char *)Blob.data(),
993 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 return false;
997}
998
999void ASTReader::Error(StringRef Msg) {
1000 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001001 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1002 Diag(diag::note_module_cache_path)
1003 << PP.getHeaderSearchInfo().getModuleCachePath();
1004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001005}
1006
1007void ASTReader::Error(unsigned DiagID,
1008 StringRef Arg1, StringRef Arg2) {
1009 if (Diags.isDiagnosticInFlight())
1010 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1011 else
1012 Diag(DiagID) << Arg1 << Arg2;
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// Source Manager Deserialization
1017//===----------------------------------------------------------------------===//
1018
1019/// \brief Read the line table in the source manager block.
1020/// \returns true if there was an error.
1021bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001022 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 unsigned Idx = 0;
1024 LineTableInfo &LineTable = SourceMgr.getLineTable();
1025
1026 // Parse the file names
1027 std::map<int, int> FileIDs;
1028 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1029 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001030 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1032 }
1033
1034 // Parse the line entries
1035 std::vector<LineEntry> Entries;
1036 while (Idx < Record.size()) {
1037 int FID = Record[Idx++];
1038 assert(FID >= 0 && "Serialized line entries for non-local file.");
1039 // Remap FileID from 1-based old view.
1040 FID += F.SLocEntryBaseID - 1;
1041
1042 // Extract the line entries
1043 unsigned NumEntries = Record[Idx++];
1044 assert(NumEntries && "Numentries is 00000");
1045 Entries.clear();
1046 Entries.reserve(NumEntries);
1047 for (unsigned I = 0; I != NumEntries; ++I) {
1048 unsigned FileOffset = Record[Idx++];
1049 unsigned LineNo = Record[Idx++];
1050 int FilenameID = FileIDs[Record[Idx++]];
1051 SrcMgr::CharacteristicKind FileKind
1052 = (SrcMgr::CharacteristicKind)Record[Idx++];
1053 unsigned IncludeOffset = Record[Idx++];
1054 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1055 FileKind, IncludeOffset));
1056 }
1057 LineTable.AddEntry(FileID::get(FID), Entries);
1058 }
1059
1060 return false;
1061}
1062
1063/// \brief Read a source manager block
1064bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1065 using namespace SrcMgr;
1066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001067 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Set the source-location entry cursor to the current position in
1070 // the stream. This cursor will be used to read the contents of the
1071 // source manager block initially, and then lazily read
1072 // source-location entries as needed.
1073 SLocEntryCursor = F.Stream;
1074
1075 // The stream itself is going to skip over the source manager block.
1076 if (F.Stream.SkipBlock()) {
1077 Error("malformed block record in AST file");
1078 return true;
1079 }
1080
1081 // Enter the source manager block.
1082 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1083 Error("malformed source manager block record in AST file");
1084 return true;
1085 }
1086
1087 RecordData Record;
1088 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1090
1091 switch (E.Kind) {
1092 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1093 case llvm::BitstreamEntry::Error:
1094 Error("malformed block record in AST file");
1095 return true;
1096 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098 case llvm::BitstreamEntry::Record:
1099 // The interesting case.
1100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001105 StringRef Blob;
1106 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 default: // Default behavior: ignore.
1108 break;
1109
1110 case SM_SLOC_FILE_ENTRY:
1111 case SM_SLOC_BUFFER_ENTRY:
1112 case SM_SLOC_EXPANSION_ENTRY:
1113 // Once we hit one of the source location entries, we're done.
1114 return false;
1115 }
1116 }
1117}
1118
1119/// \brief If a header file is not found at the path that we expect it to be
1120/// and the PCH file was moved from its original location, try to resolve the
1121/// file by assuming that header+PCH were moved together and the header is in
1122/// the same place relative to the PCH.
1123static std::string
1124resolveFileRelativeToOriginalDir(const std::string &Filename,
1125 const std::string &OriginalDir,
1126 const std::string &CurrDir) {
1127 assert(OriginalDir != CurrDir &&
1128 "No point trying to resolve the file if the PCH dir didn't change");
1129 using namespace llvm::sys;
1130 SmallString<128> filePath(Filename);
1131 fs::make_absolute(filePath);
1132 assert(path::is_absolute(OriginalDir));
1133 SmallString<128> currPCHPath(CurrDir);
1134
1135 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1136 fileDirE = path::end(path::parent_path(filePath));
1137 path::const_iterator origDirI = path::begin(OriginalDir),
1138 origDirE = path::end(OriginalDir);
1139 // Skip the common path components from filePath and OriginalDir.
1140 while (fileDirI != fileDirE && origDirI != origDirE &&
1141 *fileDirI == *origDirI) {
1142 ++fileDirI;
1143 ++origDirI;
1144 }
1145 for (; origDirI != origDirE; ++origDirI)
1146 path::append(currPCHPath, "..");
1147 path::append(currPCHPath, fileDirI, fileDirE);
1148 path::append(currPCHPath, path::filename(Filename));
1149 return currPCHPath.str();
1150}
1151
1152bool ASTReader::ReadSLocEntry(int ID) {
1153 if (ID == 0)
1154 return false;
1155
1156 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1157 Error("source location entry ID out-of-range for AST file");
1158 return true;
1159 }
1160
1161 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1162 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001163 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 unsigned BaseOffset = F->SLocEntryBaseOffset;
1165
1166 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001167 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1168 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 Error("incorrectly-formatted source location entry in AST file");
1170 return true;
1171 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001174 StringRef Blob;
1175 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 default:
1177 Error("incorrectly-formatted source location entry in AST file");
1178 return true;
1179
1180 case SM_SLOC_FILE_ENTRY: {
1181 // We will detect whether a file changed and return 'Failure' for it, but
1182 // we will also try to fail gracefully by setting up the SLocEntry.
1183 unsigned InputID = Record[4];
1184 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001185 const FileEntry *File = IF.getFile();
1186 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001187
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001188 // Note that we only check if a File was returned. If it was out-of-date
1189 // we have complained but we will continue creating a FileID to recover
1190 // gracefully.
1191 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 return true;
1193
1194 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1195 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1196 // This is the module's main file.
1197 IncludeLoc = getImportLocation(F);
1198 }
1199 SrcMgr::CharacteristicKind
1200 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1201 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1202 ID, BaseOffset + Record[0]);
1203 SrcMgr::FileInfo &FileInfo =
1204 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1205 FileInfo.NumCreatedFIDs = Record[5];
1206 if (Record[3])
1207 FileInfo.setHasLineDirectives();
1208
1209 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1210 unsigned NumFileDecls = Record[7];
1211 if (NumFileDecls) {
1212 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1213 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1214 NumFileDecls));
1215 }
1216
1217 const SrcMgr::ContentCache *ContentCache
1218 = SourceMgr.getOrCreateContentCache(File,
1219 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1220 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1221 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1222 unsigned Code = SLocEntryCursor.ReadCode();
1223 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001224 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001225
1226 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1227 Error("AST record has invalid code");
1228 return true;
1229 }
1230
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001231 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001232 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001233 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 }
1235
1236 break;
1237 }
1238
1239 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 unsigned Offset = Record[0];
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001245 if (IncludeLoc.isInvalid() &&
1246 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 IncludeLoc = getImportLocation(F);
1248 }
1249 unsigned Code = SLocEntryCursor.ReadCode();
1250 Record.clear();
1251 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001252 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
1254 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1255 Error("AST record has invalid code");
1256 return true;
1257 }
1258
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001259 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1260 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001261 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001262 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 break;
1264 }
1265
1266 case SM_SLOC_EXPANSION_ENTRY: {
1267 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1268 SourceMgr.createExpansionLoc(SpellingLoc,
1269 ReadSourceLocation(*F, Record[2]),
1270 ReadSourceLocation(*F, Record[3]),
1271 Record[4],
1272 ID,
1273 BaseOffset + Record[0]);
1274 break;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1282 if (ID == 0)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1286 Error("source location entry ID out-of-range for AST file");
1287 return std::make_pair(SourceLocation(), "");
1288 }
1289
1290 // Find which module file this entry lands in.
1291 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001292 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 return std::make_pair(SourceLocation(), "");
1294
1295 // FIXME: Can we map this down to a particular submodule? That would be
1296 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001297 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001298}
1299
1300/// \brief Find the location where the module F is imported.
1301SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1302 if (F->ImportLoc.isValid())
1303 return F->ImportLoc;
1304
1305 // Otherwise we have a PCH. It's considered to be "imported" at the first
1306 // location of its includer.
1307 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001308 // Main file is the importer.
1309 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1310 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 return F->ImportedBy[0]->FirstLoc;
1313}
1314
1315/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1316/// specified cursor. Read the abbreviations that are at the top of the block
1317/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001318bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 if (Cursor.EnterSubBlock(BlockID)) {
1320 Error("malformed block record in AST file");
1321 return Failure;
1322 }
1323
1324 while (true) {
1325 uint64_t Offset = Cursor.GetCurrentBitNo();
1326 unsigned Code = Cursor.ReadCode();
1327
1328 // We expect all abbrevs to be at the start of the block.
1329 if (Code != llvm::bitc::DEFINE_ABBREV) {
1330 Cursor.JumpToBit(Offset);
1331 return false;
1332 }
1333 Cursor.ReadAbbrevRecord();
1334 }
1335}
1336
Richard Smithe40f2ba2013-08-07 21:41:30 +00001337Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001338 unsigned &Idx) {
1339 Token Tok;
1340 Tok.startToken();
1341 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1342 Tok.setLength(Record[Idx++]);
1343 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1344 Tok.setIdentifierInfo(II);
1345 Tok.setKind((tok::TokenKind)Record[Idx++]);
1346 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1347 return Tok;
1348}
1349
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001350MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001351 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001352
1353 // Keep track of where we are in the stream, then jump back there
1354 // after reading this macro.
1355 SavedStreamPosition SavedPosition(Stream);
1356
1357 Stream.JumpToBit(Offset);
1358 RecordData Record;
1359 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001360 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 // Advance to the next record, but if we get to the end of the block, don't
1364 // pop it (removing all the abbreviations from the cursor) since we want to
1365 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001366 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1368
1369 switch (Entry.Kind) {
1370 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1371 case llvm::BitstreamEntry::Error:
1372 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001373 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001375 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 case llvm::BitstreamEntry::Record:
1377 // The interesting case.
1378 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 }
1380
1381 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 Record.clear();
1383 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001384 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001386 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 case PP_MACRO_DIRECTIVE_HISTORY:
1388 return Macro;
1389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 case PP_MACRO_OBJECT_LIKE:
1391 case PP_MACRO_FUNCTION_LIKE: {
1392 // If we already have a macro, that means that we've hit the end
1393 // of the definition of the macro we were looking for. We're
1394 // done.
1395 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 unsigned NextIndex = 1; // Skip identifier ID.
1399 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001402 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001404 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1407 // Decode function-like macro info.
1408 bool isC99VarArgs = Record[NextIndex++];
1409 bool isGNUVarArgs = Record[NextIndex++];
1410 bool hasCommaPasting = Record[NextIndex++];
1411 MacroArgs.clear();
1412 unsigned NumArgs = Record[NextIndex++];
1413 for (unsigned i = 0; i != NumArgs; ++i)
1414 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1415
1416 // Install function-like macro info.
1417 MI->setIsFunctionLike();
1418 if (isC99VarArgs) MI->setIsC99Varargs();
1419 if (isGNUVarArgs) MI->setIsGNUVarargs();
1420 if (hasCommaPasting) MI->setHasCommaPasting();
1421 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1422 PP.getPreprocessorAllocator());
1423 }
1424
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 // Remember that we saw this macro last so that we add the tokens that
1426 // form its body to it.
1427 Macro = MI;
1428
1429 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1430 Record[NextIndex]) {
1431 // We have a macro definition. Register the association
1432 PreprocessedEntityID
1433 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1434 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001435 PreprocessingRecord::PPEntityID PPID =
1436 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1437 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1438 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001439 if (PPDef)
1440 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 }
1442
1443 ++NumMacrosRead;
1444 break;
1445 }
1446
1447 case PP_TOKEN: {
1448 // If we see a TOKEN before a PP_MACRO_*, then the file is
1449 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001450 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451
John McCallf413f5e2013-05-03 00:10:13 +00001452 unsigned Idx = 0;
1453 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 Macro->AddTokenToBody(Tok);
1455 break;
1456 }
1457 }
1458 }
1459}
1460
1461PreprocessedEntityID
1462ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1463 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1464 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1465 assert(I != M.PreprocessedEntityRemap.end()
1466 && "Invalid index into preprocessed entity index remap");
1467
1468 return LocalID + I->second;
1469}
1470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1472 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1477 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479 return ikey;
1480}
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1483 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 return false;
1485
Richard Smith7ed1bc92014-12-05 22:42:13 +00001486 if (llvm::sys::path::is_absolute(a.Filename) &&
1487 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return true;
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001491 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1493 if (!Key.Imported)
1494 return FileMgr.getFile(Key.Filename);
1495
1496 std::string Resolved = Key.Filename;
1497 Reader.ResolveImportedPath(M, Resolved);
1498 return FileMgr.getFile(Resolved);
1499 };
1500
1501 const FileEntry *FEA = GetFile(a);
1502 const FileEntry *FEB = GetFile(b);
1503 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001504}
1505
1506std::pair<unsigned, unsigned>
1507HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001508 using namespace llvm::support;
1509 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001511 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513
1514HeaderFileInfoTrait::internal_key_type
1515HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001516 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1519 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001521 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 return ikey;
1523}
1524
Guy Benyei11169dd2012-12-18 14:30:41 +00001525HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001526HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 unsigned DataLen) {
1528 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 HeaderFileInfo HFI;
1531 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001532 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1533 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HFI.isImport = (Flags >> 5) & 0x01;
1535 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1536 HFI.DirInfo = (Flags >> 2) & 0x03;
1537 HFI.Resolved = (Flags >> 1) & 0x01;
1538 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1540 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1541 M, endian::readNext<uint32_t, little, unaligned>(d));
1542 if (unsigned FrameworkOffset =
1543 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // The framework offset is 1 greater than the actual offset,
1545 // since 0 is used as an indicator for "no framework name".
1546 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1547 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1548 }
1549
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001550 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001552 if (LocalSMID) {
1553 // This header is part of a module. Associate it with the module to enable
1554 // implicit module import.
1555 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1556 Module *Mod = Reader.getSubmodule(GlobalSMID);
1557 HFI.isModuleHeader = true;
1558 FileManager &FileMgr = Reader.getFileManager();
1559 ModuleMap &ModMap =
1560 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001561 // FIXME: This information should be propagated through the
1562 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001563 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001564 std::string Filename = key.Filename;
1565 if (key.Imported)
1566 Reader.ResolveImportedPath(M, Filename);
1567 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001568 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001569 }
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1573 (void)End;
1574
1575 // This HeaderFileInfo was externally loaded.
1576 HFI.External = true;
1577 return HFI;
1578}
1579
Richard Smithd7329392015-04-21 21:46:32 +00001580void ASTReader::addPendingMacro(IdentifierInfo *II,
1581 ModuleFile *M,
1582 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001583 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1584 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
1587void ASTReader::ReadDefinedMacros() {
1588 // Note that we are loading defined macros.
1589 Deserializing Macros(this);
1590
1591 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1592 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001593 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594
1595 // If there was no preprocessor block, skip this file.
1596 if (!MacroCursor.getBitStreamReader())
1597 continue;
1598
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001599 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 Cursor.JumpToBit((*I)->MacroStartOffset);
1601
1602 RecordData Record;
1603 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001604 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1605
1606 switch (E.Kind) {
1607 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1608 case llvm::BitstreamEntry::Error:
1609 Error("malformed block record in AST file");
1610 return;
1611 case llvm::BitstreamEntry::EndBlock:
1612 goto NextCursor;
1613
1614 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001615 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001616 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 default: // Default behavior: ignore.
1618 break;
1619
1620 case PP_MACRO_OBJECT_LIKE:
1621 case PP_MACRO_FUNCTION_LIKE:
1622 getLocalIdentifier(**I, Record[0]);
1623 break;
1624
1625 case PP_TOKEN:
1626 // Ignore tokens.
1627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 break;
1630 }
1631 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001632 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 }
1634}
1635
1636namespace {
1637 /// \brief Visitor class used to look up identifirs in an AST file.
1638 class IdentifierLookupVisitor {
1639 StringRef Name;
1640 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 unsigned &NumIdentifierLookups;
1642 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001644
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001646 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1647 unsigned &NumIdentifierLookups,
1648 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001649 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 NumIdentifierLookups(NumIdentifierLookups),
1651 NumIdentifierLookupHits(NumIdentifierLookupHits),
1652 Found()
1653 {
1654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655
1656 static bool visit(ModuleFile &M, void *UserData) {
1657 IdentifierLookupVisitor *This
1658 = static_cast<IdentifierLookupVisitor *>(UserData);
1659
1660 // If we've already searched this module file, skip it now.
1661 if (M.Generation <= This->PriorGeneration)
1662 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 ASTIdentifierLookupTable *IdTable
1665 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1666 if (!IdTable)
1667 return false;
1668
1669 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1670 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001671 ++This->NumIdentifierLookups;
1672 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 if (Pos == IdTable->end())
1674 return false;
1675
1676 // Dereferencing the iterator has the effect of building the
1677 // IdentifierInfo node and populating it with the various
1678 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 This->Found = *Pos;
1681 return true;
1682 }
1683
1684 // \brief Retrieve the identifier info found within the module
1685 // files.
1686 IdentifierInfo *getIdentifierInfo() const { return Found; }
1687 };
1688}
1689
1690void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1691 // Note that we are loading an identifier.
1692 Deserializing AnIdentifier(this);
1693
1694 unsigned PriorGeneration = 0;
1695 if (getContext().getLangOpts().Modules)
1696 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001697
1698 // If there is a global index, look there first to determine which modules
1699 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001700 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001701 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001702 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1704 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 }
1706 }
1707
Douglas Gregor7211ac12013-01-25 23:32:03 +00001708 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 NumIdentifierLookups,
1710 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 markIdentifierUpToDate(&II);
1713}
1714
1715void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1716 if (!II)
1717 return;
1718
1719 II->setOutOfDate(false);
1720
1721 // Update the generation for this identifier.
1722 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001723 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001726void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1727 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001728 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729
1730 BitstreamCursor &Cursor = M.MacroCursor;
1731 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001732 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001733
Richard Smith713369b2015-04-23 20:40:50 +00001734 struct ModuleMacroRecord {
1735 SubmoduleID SubModID;
1736 MacroInfo *MI;
1737 SmallVector<SubmoduleID, 8> Overrides;
1738 };
1739 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001740
Richard Smithd7329392015-04-21 21:46:32 +00001741 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1742 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1743 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001744 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001745 while (true) {
1746 llvm::BitstreamEntry Entry =
1747 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1748 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1749 Error("malformed block record in AST file");
1750 return;
1751 }
1752
1753 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001754 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001755 case PP_MACRO_DIRECTIVE_HISTORY:
1756 break;
1757
1758 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001759 ModuleMacros.push_back(ModuleMacroRecord());
1760 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001761 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1762 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001763 for (int I = 2, N = Record.size(); I != N; ++I)
1764 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001765 continue;
1766 }
1767
1768 default:
1769 Error("malformed block record in AST file");
1770 return;
1771 }
1772
1773 // We found the macro directive history; that's the last record
1774 // for this macro.
1775 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001776 }
1777
Richard Smithd7329392015-04-21 21:46:32 +00001778 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001779 {
1780 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001781 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001782 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001783 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001784 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001785 Module *Mod = getSubmodule(ModID);
1786 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001787 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001788 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001789 }
1790
1791 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001792 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001793 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001794 }
1795 }
1796
1797 // Don't read the directive history for a module; we don't have anywhere
1798 // to put it.
1799 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1800 return;
1801
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001803 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001804 unsigned Idx = 0, N = Record.size();
1805 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001806 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001808 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1809 switch (K) {
1810 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001811 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001812 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001813 break;
1814 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001815 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001816 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001817 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001818 }
1819 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 bool isPublic = Record[Idx++];
1821 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1822 break;
1823 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001824
1825 if (!Latest)
1826 Latest = MD;
1827 if (Earliest)
1828 Earliest->setPrevious(MD);
1829 Earliest = MD;
1830 }
1831
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001832 if (Latest)
1833 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834}
1835
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001836ASTReader::InputFileInfo
1837ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001838 // Go find this input file.
1839 BitstreamCursor &Cursor = F.InputFilesCursor;
1840 SavedStreamPosition SavedPosition(Cursor);
1841 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1842
1843 unsigned Code = Cursor.ReadCode();
1844 RecordData Record;
1845 StringRef Blob;
1846
1847 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1848 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1849 "invalid record type for input file");
1850 (void)Result;
1851
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001852 std::string Filename;
1853 off_t StoredSize;
1854 time_t StoredTime;
1855 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001856
Ben Langmuir198c1682014-03-07 07:27:49 +00001857 assert(Record[0] == ID && "Bogus stored ID or offset");
1858 StoredSize = static_cast<off_t>(Record[1]);
1859 StoredTime = static_cast<time_t>(Record[2]);
1860 Overridden = static_cast<bool>(Record[3]);
1861 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001862 ResolveImportedPath(F, Filename);
1863
Hans Wennborg73945142014-03-14 17:45:06 +00001864 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1865 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001866}
1867
1868std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001869 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001870}
1871
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001872InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 // If this ID is bogus, just return an empty input file.
1874 if (ID == 0 || ID > F.InputFilesLoaded.size())
1875 return InputFile();
1876
1877 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001878 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 return F.InputFilesLoaded[ID-1];
1880
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001881 if (F.InputFilesLoaded[ID-1].isNotFound())
1882 return InputFile();
1883
Guy Benyei11169dd2012-12-18 14:30:41 +00001884 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001885 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 SavedStreamPosition SavedPosition(Cursor);
1887 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1888
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001889 InputFileInfo FI = readInputFileInfo(F, ID);
1890 off_t StoredSize = FI.StoredSize;
1891 time_t StoredTime = FI.StoredTime;
1892 bool Overridden = FI.Overridden;
1893 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001894
Ben Langmuir198c1682014-03-07 07:27:49 +00001895 const FileEntry *File
1896 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1897 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1898
1899 // If we didn't find the file, resolve it relative to the
1900 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001901 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001902 F.OriginalDir != CurrentDir) {
1903 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1904 F.OriginalDir,
1905 CurrentDir);
1906 if (!Resolved.empty())
1907 File = FileMgr.getFile(Resolved);
1908 }
1909
1910 // For an overridden file, create a virtual file with the stored
1911 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001912 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001913 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1914 }
1915
Craig Toppera13603a2014-05-22 05:54:18 +00001916 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001917 if (Complain) {
1918 std::string ErrorStr = "could not find file '";
1919 ErrorStr += Filename;
1920 ErrorStr += "' referenced by AST file";
1921 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001922 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001923 // Record that we didn't find the file.
1924 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1925 return InputFile();
1926 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001927
Ben Langmuir198c1682014-03-07 07:27:49 +00001928 // Check if there was a request to override the contents of the file
1929 // that was part of the precompiled header. Overridding such a file
1930 // can lead to problems when lexing using the source locations from the
1931 // PCH.
1932 SourceManager &SM = getSourceManager();
1933 if (!Overridden && SM.isFileOverridden(File)) {
1934 if (Complain)
1935 Error(diag::err_fe_pch_file_overridden, Filename);
1936 // After emitting the diagnostic, recover by disabling the override so
1937 // that the original file will be used.
1938 SM.disableFileContentsOverride(File);
1939 // The FileEntry is a virtual file entry with the size of the contents
1940 // that would override the original contents. Set it to the original's
1941 // size/time.
1942 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1943 StoredSize, StoredTime);
1944 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001945
Ben Langmuir198c1682014-03-07 07:27:49 +00001946 bool IsOutOfDate = false;
1947
1948 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001949 if (!Overridden && //
1950 (StoredSize != File->getSize() ||
1951#if defined(LLVM_ON_WIN32)
1952 false
1953#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001954 // In our regression testing, the Windows file system seems to
1955 // have inconsistent modification times that sometimes
1956 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001957 //
1958 // This also happens in networked file systems, so disable this
1959 // check if validation is disabled or if we have an explicitly
1960 // built PCM file.
1961 //
1962 // FIXME: Should we also do this for PCH files? They could also
1963 // reasonably get shared across a network during a distributed build.
1964 (StoredTime != File->getModificationTime() && !DisableValidation &&
1965 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001966#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 )) {
1968 if (Complain) {
1969 // Build a list of the PCH imports that got us here (in reverse).
1970 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1971 while (ImportStack.back()->ImportedBy.size() > 0)
1972 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001973
Ben Langmuir198c1682014-03-07 07:27:49 +00001974 // The top-level PCH is stale.
1975 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1976 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001977
Ben Langmuir198c1682014-03-07 07:27:49 +00001978 // Print the import stack.
1979 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1980 Diag(diag::note_pch_required_by)
1981 << Filename << ImportStack[0]->FileName;
1982 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001983 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001985 }
1986
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 if (!Diags.isDiagnosticInFlight())
1988 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001989 }
1990
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 }
1993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1995
1996 // Note that we've loaded this input file.
1997 F.InputFilesLoaded[ID-1] = IF;
1998 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00001999}
2000
Richard Smith7ed1bc92014-12-05 22:42:13 +00002001/// \brief If we are loading a relocatable PCH or module file, and the filename
2002/// is not an absolute path, add the system or module root to the beginning of
2003/// the file name.
2004void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2005 // Resolve relative to the base directory, if we have one.
2006 if (!M.BaseDirectory.empty())
2007 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002008}
2009
Richard Smith7ed1bc92014-12-05 22:42:13 +00002010void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002011 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2012 return;
2013
Richard Smith7ed1bc92014-12-05 22:42:13 +00002014 SmallString<128> Buffer;
2015 llvm::sys::path::append(Buffer, Prefix, Filename);
2016 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002017}
2018
2019ASTReader::ASTReadResult
2020ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002021 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002022 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002024 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025
2026 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2027 Error("malformed block record in AST file");
2028 return Failure;
2029 }
2030
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002031 // Should we allow the configuration of the module file to differ from the
2032 // configuration of the current translation unit in a compatible way?
2033 //
2034 // FIXME: Allow this for files explicitly specified with -include-pch too.
2035 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2036
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 // Read all of the records and blocks in the control block.
2038 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002039 unsigned NumInputs = 0;
2040 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002041 while (1) {
2042 llvm::BitstreamEntry Entry = Stream.advance();
2043
2044 switch (Entry.Kind) {
2045 case llvm::BitstreamEntry::Error:
2046 Error("malformed block record in AST file");
2047 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002048 case llvm::BitstreamEntry::EndBlock: {
2049 // Validate input files.
2050 const HeaderSearchOptions &HSOpts =
2051 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002052
Richard Smitha1825302014-10-23 22:18:29 +00002053 // All user input files reside at the index range [0, NumUserInputs), and
2054 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002055 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002057
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002058 // If we are reading a module, we will create a verification timestamp,
2059 // so we verify all input files. Otherwise, verify only user input
2060 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002061
2062 unsigned N = NumUserInputs;
2063 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002064 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002065 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002066 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002067 N = NumInputs;
2068
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002069 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002070 InputFile IF = getInputFile(F, I+1, Complain);
2071 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002075
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002076 if (Listener)
2077 Listener->visitModuleFile(F.FileName);
2078
Ben Langmuircb69b572014-03-07 06:40:32 +00002079 if (Listener && Listener->needsInputFileVisitation()) {
2080 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2081 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002082 for (unsigned I = 0; I < N; ++I) {
2083 bool IsSystem = I >= NumUserInputs;
2084 InputFileInfo FI = readInputFileInfo(F, I+1);
2085 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2086 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002087 }
2088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002090 }
2091
Chris Lattnere7b154b2013-01-19 21:39:22 +00002092 case llvm::BitstreamEntry::SubBlock:
2093 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002094 case INPUT_FILES_BLOCK_ID:
2095 F.InputFilesCursor = Stream;
2096 if (Stream.SkipBlock() || // Skip with the main cursor
2097 // Read the abbreviations
2098 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2099 Error("malformed block record in AST file");
2100 return Failure;
2101 }
2102 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002103
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002105 if (Stream.SkipBlock()) {
2106 Error("malformed block record in AST file");
2107 return Failure;
2108 }
2109 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002111
2112 case llvm::BitstreamEntry::Record:
2113 // The interesting case.
2114 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 }
2116
2117 // Read and process a record.
2118 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002119 StringRef Blob;
2120 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 case METADATA: {
2122 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2123 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002124 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2125 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 return VersionMismatch;
2127 }
2128
2129 bool hasErrors = Record[5];
2130 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2131 Diag(diag::err_pch_with_compiler_errors);
2132 return HadErrors;
2133 }
2134
2135 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002136 // Relative paths in a relocatable PCH are relative to our sysroot.
2137 if (F.RelocatablePCH)
2138 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002139
2140 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002141 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2143 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002144 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 return VersionMismatch;
2146 }
2147 break;
2148 }
2149
Ben Langmuir487ea142014-10-23 18:05:36 +00002150 case SIGNATURE:
2151 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2152 F.Signature = Record[0];
2153 break;
2154
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 case IMPORTS: {
2156 // Load each of the imported PCH files.
2157 unsigned Idx = 0, N = Record.size();
2158 while (Idx < N) {
2159 // Read information about the AST file.
2160 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2161 // The import location will be the local one for now; we will adjust
2162 // all import locations of module imports after the global source
2163 // location info are setup.
2164 SourceLocation ImportLoc =
2165 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002166 off_t StoredSize = (off_t)Record[Idx++];
2167 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002168 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002169 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002170
2171 // Load the AST file.
2172 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002173 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 ClientLoadCapabilities)) {
2175 case Failure: return Failure;
2176 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002177 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002178 case OutOfDate: return OutOfDate;
2179 case VersionMismatch: return VersionMismatch;
2180 case ConfigurationMismatch: return ConfigurationMismatch;
2181 case HadErrors: return HadErrors;
2182 case Success: break;
2183 }
2184 }
2185 break;
2186 }
2187
Richard Smith7f330cd2015-03-18 01:42:29 +00002188 case KNOWN_MODULE_FILES:
2189 break;
2190
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 case LANGUAGE_OPTIONS: {
2192 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002193 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002194 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002195 ParseLanguageOptions(Record, Complain, *Listener,
2196 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002197 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 return ConfigurationMismatch;
2199 break;
2200 }
2201
2202 case TARGET_OPTIONS: {
2203 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2204 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002205 ParseTargetOptions(Record, Complain, *Listener,
2206 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002207 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002208 return ConfigurationMismatch;
2209 break;
2210 }
2211
2212 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002213 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002215 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002216 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002217 !DisableValidation)
2218 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 break;
2220 }
2221
2222 case FILE_SYSTEM_OPTIONS: {
2223 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2224 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002225 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002227 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 return ConfigurationMismatch;
2229 break;
2230 }
2231
2232 case HEADER_SEARCH_OPTIONS: {
2233 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2234 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002235 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002237 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 return ConfigurationMismatch;
2239 break;
2240 }
2241
2242 case PREPROCESSOR_OPTIONS: {
2243 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2244 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002245 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 ParsePreprocessorOptions(Record, Complain, *Listener,
2247 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002248 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 return ConfigurationMismatch;
2250 break;
2251 }
2252
2253 case ORIGINAL_FILE:
2254 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002255 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002257 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 break;
2259
2260 case ORIGINAL_FILE_ID:
2261 F.OriginalSourceFileID = FileID::get(Record[0]);
2262 break;
2263
2264 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002265 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 break;
2267
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002268 case MODULE_NAME:
2269 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002270 if (Listener)
2271 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002272 break;
2273
Richard Smith223d3f22014-12-06 03:21:08 +00002274 case MODULE_DIRECTORY: {
2275 assert(!F.ModuleName.empty() &&
2276 "MODULE_DIRECTORY found before MODULE_NAME");
2277 // If we've already loaded a module map file covering this module, we may
2278 // have a better path for it (relative to the current build).
2279 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2280 if (M && M->Directory) {
2281 // If we're implicitly loading a module, the base directory can't
2282 // change between the build and use.
2283 if (F.Kind != MK_ExplicitModule) {
2284 const DirectoryEntry *BuildDir =
2285 PP.getFileManager().getDirectory(Blob);
2286 if (!BuildDir || BuildDir != M->Directory) {
2287 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2288 Diag(diag::err_imported_module_relocated)
2289 << F.ModuleName << Blob << M->Directory->getName();
2290 return OutOfDate;
2291 }
2292 }
2293 F.BaseDirectory = M->Directory->getName();
2294 } else {
2295 F.BaseDirectory = Blob;
2296 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002297 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002298 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002299
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002300 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002301 if (ASTReadResult Result =
2302 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2303 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002304 break;
2305
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002307 NumInputs = Record[0];
2308 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002309 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002310 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 break;
2312 }
2313 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002314}
2315
Ben Langmuir2c9af442014-04-10 17:57:43 +00002316ASTReader::ASTReadResult
2317ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002318 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002319
2320 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2321 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002322 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 }
2324
2325 // Read all of the records and blocks for the AST file.
2326 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002327 while (1) {
2328 llvm::BitstreamEntry Entry = Stream.advance();
2329
2330 switch (Entry.Kind) {
2331 case llvm::BitstreamEntry::Error:
2332 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002333 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002334 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002335 // Outside of C++, we do not store a lookup map for the translation unit.
2336 // Instead, mark it as needing a lookup map to be built if this module
2337 // contains any declarations lexically within it (which it always does!).
2338 // This usually has no cost, since we very rarely need the lookup map for
2339 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002341 if (DC->hasExternalLexicalStorage() &&
2342 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002344
Ben Langmuir2c9af442014-04-10 17:57:43 +00002345 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002347 case llvm::BitstreamEntry::SubBlock:
2348 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 case DECLTYPES_BLOCK_ID:
2350 // We lazily load the decls block, but we want to set up the
2351 // DeclsCursor cursor to point into it. Clone our current bitcode
2352 // cursor to it, enter the block and read the abbrevs in that block.
2353 // With the main cursor, we just skip over it.
2354 F.DeclsCursor = Stream;
2355 if (Stream.SkipBlock() || // Skip with the main cursor.
2356 // Read the abbrevs.
2357 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2358 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002359 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 }
2361 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case PREPROCESSOR_BLOCK_ID:
2364 F.MacroCursor = Stream;
2365 if (!PP.getExternalSource())
2366 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 if (Stream.SkipBlock() ||
2369 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2370 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002371 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 }
2373 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2374 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 case PREPROCESSOR_DETAIL_BLOCK_ID:
2377 F.PreprocessorDetailCursor = Stream;
2378 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002379 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002381 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002382 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2386
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 if (!PP.getPreprocessingRecord())
2388 PP.createPreprocessingRecord();
2389 if (!PP.getPreprocessingRecord()->getExternalSource())
2390 PP.getPreprocessingRecord()->SetExternalSource(*this);
2391 break;
2392
2393 case SOURCE_MANAGER_BLOCK_ID:
2394 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002397
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002399 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2400 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002404 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 if (Stream.SkipBlock() ||
2406 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2407 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002408 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 }
2410 CommentsCursors.push_back(std::make_pair(C, &F));
2411 break;
2412 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002413
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415 if (Stream.SkipBlock()) {
2416 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002417 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002418 }
2419 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 }
2421 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422
2423 case llvm::BitstreamEntry::Record:
2424 // The interesting case.
2425 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 }
2427
2428 // Read and process a record.
2429 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002430 StringRef Blob;
2431 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 default: // Default behavior: ignore.
2433 break;
2434
2435 case TYPE_OFFSET: {
2436 if (F.LocalNumTypes != 0) {
2437 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002438 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002440 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 F.LocalNumTypes = Record[0];
2442 unsigned LocalBaseTypeIndex = Record[1];
2443 F.BaseTypeIndex = getTotalNumTypes();
2444
2445 if (F.LocalNumTypes > 0) {
2446 // Introduce the global -> local mapping for types within this module.
2447 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2448
2449 // Introduce the local -> global mapping for types within this module.
2450 F.TypeRemap.insertOrReplace(
2451 std::make_pair(LocalBaseTypeIndex,
2452 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002453
2454 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 }
2456 break;
2457 }
2458
2459 case DECL_OFFSET: {
2460 if (F.LocalNumDecls != 0) {
2461 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002462 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002464 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 F.LocalNumDecls = Record[0];
2466 unsigned LocalBaseDeclID = Record[1];
2467 F.BaseDeclID = getTotalNumDecls();
2468
2469 if (F.LocalNumDecls > 0) {
2470 // Introduce the global -> local mapping for declarations within this
2471 // module.
2472 GlobalDeclMap.insert(
2473 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2474
2475 // Introduce the local -> global mapping for declarations within this
2476 // module.
2477 F.DeclRemap.insertOrReplace(
2478 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2479
2480 // Introduce the global -> local mapping for declarations within this
2481 // module.
2482 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002483
Ben Langmuir52ca6782014-10-20 16:27:32 +00002484 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2485 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 break;
2487 }
2488
2489 case TU_UPDATE_LEXICAL: {
2490 DeclContext *TU = Context.getTranslationUnitDecl();
2491 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002492 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002494 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 TU->setHasExternalLexicalStorage(true);
2496 break;
2497 }
2498
2499 case UPDATE_VISIBLE: {
2500 unsigned Idx = 0;
2501 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2502 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002503 ASTDeclContextNameLookupTable::Create(
2504 (const unsigned char *)Blob.data() + Record[Idx++],
2505 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2506 (const unsigned char *)Blob.data(),
2507 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002508 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002509 auto *DC = cast<DeclContext>(D);
2510 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002511 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2512 delete LookupTable;
2513 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 } else
2515 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2516 break;
2517 }
2518
2519 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002520 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002522 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2523 (const unsigned char *)F.IdentifierTableData + Record[0],
2524 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2525 (const unsigned char *)F.IdentifierTableData,
2526 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002527
2528 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2529 }
2530 break;
2531
2532 case IDENTIFIER_OFFSET: {
2533 if (F.LocalNumIdentifiers != 0) {
2534 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002535 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002537 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 F.LocalNumIdentifiers = Record[0];
2539 unsigned LocalBaseIdentifierID = Record[1];
2540 F.BaseIdentifierID = getTotalNumIdentifiers();
2541
2542 if (F.LocalNumIdentifiers > 0) {
2543 // Introduce the global -> local mapping for identifiers within this
2544 // module.
2545 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2546 &F));
2547
2548 // Introduce the local -> global mapping for identifiers within this
2549 // module.
2550 F.IdentifierRemap.insertOrReplace(
2551 std::make_pair(LocalBaseIdentifierID,
2552 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002553
Ben Langmuir52ca6782014-10-20 16:27:32 +00002554 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2555 + F.LocalNumIdentifiers);
2556 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 break;
2558 }
2559
Ben Langmuir332aafe2014-01-31 01:06:56 +00002560 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002561 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2562 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002564 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 break;
2566
2567 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002568 if (SpecialTypes.empty()) {
2569 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2570 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2571 break;
2572 }
2573
2574 if (SpecialTypes.size() != Record.size()) {
2575 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002576 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002577 }
2578
2579 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2580 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2581 if (!SpecialTypes[I])
2582 SpecialTypes[I] = ID;
2583 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2584 // merge step?
2585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 break;
2587
2588 case STATISTICS:
2589 TotalNumStatements += Record[0];
2590 TotalNumMacros += Record[1];
2591 TotalLexicalDeclContexts += Record[2];
2592 TotalVisibleDeclContexts += Record[3];
2593 break;
2594
2595 case UNUSED_FILESCOPED_DECLS:
2596 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2597 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2598 break;
2599
2600 case DELEGATING_CTORS:
2601 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2602 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2603 break;
2604
2605 case WEAK_UNDECLARED_IDENTIFIERS:
2606 if (Record.size() % 4 != 0) {
2607 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 }
2610
2611 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2612 // files. This isn't the way to do it :)
2613 WeakUndeclaredIdentifiers.clear();
2614
2615 // Translate the weak, undeclared identifiers into global IDs.
2616 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2617 WeakUndeclaredIdentifiers.push_back(
2618 getGlobalIdentifierID(F, Record[I++]));
2619 WeakUndeclaredIdentifiers.push_back(
2620 getGlobalIdentifierID(F, Record[I++]));
2621 WeakUndeclaredIdentifiers.push_back(
2622 ReadSourceLocation(F, Record, I).getRawEncoding());
2623 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2624 }
2625 break;
2626
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002628 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 F.LocalNumSelectors = Record[0];
2630 unsigned LocalBaseSelectorID = Record[1];
2631 F.BaseSelectorID = getTotalNumSelectors();
2632
2633 if (F.LocalNumSelectors > 0) {
2634 // Introduce the global -> local mapping for selectors within this
2635 // module.
2636 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2637
2638 // Introduce the local -> global mapping for selectors within this
2639 // module.
2640 F.SelectorRemap.insertOrReplace(
2641 std::make_pair(LocalBaseSelectorID,
2642 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002643
2644 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 }
2646 break;
2647 }
2648
2649 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002650 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 if (Record[0])
2652 F.SelectorLookupTable
2653 = ASTSelectorLookupTable::Create(
2654 F.SelectorLookupTableData + Record[0],
2655 F.SelectorLookupTableData,
2656 ASTSelectorLookupTrait(*this, F));
2657 TotalNumMethodPoolEntries += Record[1];
2658 break;
2659
2660 case REFERENCED_SELECTOR_POOL:
2661 if (!Record.empty()) {
2662 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2663 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2664 Record[Idx++]));
2665 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2666 getRawEncoding());
2667 }
2668 }
2669 break;
2670
2671 case PP_COUNTER_VALUE:
2672 if (!Record.empty() && Listener)
2673 Listener->ReadCounter(F, Record[0]);
2674 break;
2675
2676 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002677 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 F.NumFileSortedDecls = Record[0];
2679 break;
2680
2681 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002682 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 F.LocalNumSLocEntries = Record[0];
2684 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002685 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002686 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 SLocSpaceSize);
2688 // Make our entry in the range map. BaseID is negative and growing, so
2689 // we invert it. Because we invert it, though, we need the other end of
2690 // the range.
2691 unsigned RangeStart =
2692 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2693 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2694 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2695
2696 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2697 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2698 GlobalSLocOffsetMap.insert(
2699 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2700 - SLocSpaceSize,&F));
2701
2702 // Initialize the remapping table.
2703 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002704 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002706 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2708
2709 TotalNumSLocEntries += F.LocalNumSLocEntries;
2710 break;
2711 }
2712
2713 case MODULE_OFFSET_MAP: {
2714 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002715 const unsigned char *Data = (const unsigned char*)Blob.data();
2716 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002717
2718 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2719 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2720 F.SLocRemap.insert(std::make_pair(0U, 0));
2721 F.SLocRemap.insert(std::make_pair(2U, 1));
2722 }
2723
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002725 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2726 RemapBuilder;
2727 RemapBuilder SLocRemap(F.SLocRemap);
2728 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2729 RemapBuilder MacroRemap(F.MacroRemap);
2730 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2731 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2732 RemapBuilder SelectorRemap(F.SelectorRemap);
2733 RemapBuilder DeclRemap(F.DeclRemap);
2734 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002735
2736 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002737 using namespace llvm::support;
2738 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 StringRef Name = StringRef((const char*)Data, Len);
2740 Data += Len;
2741 ModuleFile *OM = ModuleMgr.lookup(Name);
2742 if (!OM) {
2743 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002744 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 }
2746
Justin Bogner57ba0b22014-03-28 22:03:24 +00002747 uint32_t SLocOffset =
2748 endian::readNext<uint32_t, little, unaligned>(Data);
2749 uint32_t IdentifierIDOffset =
2750 endian::readNext<uint32_t, little, unaligned>(Data);
2751 uint32_t MacroIDOffset =
2752 endian::readNext<uint32_t, little, unaligned>(Data);
2753 uint32_t PreprocessedEntityIDOffset =
2754 endian::readNext<uint32_t, little, unaligned>(Data);
2755 uint32_t SubmoduleIDOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t SelectorIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t DeclIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t TypeIndexOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763
Ben Langmuir785180e2014-10-20 16:27:30 +00002764 uint32_t None = std::numeric_limits<uint32_t>::max();
2765
2766 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2767 RemapBuilder &Remap) {
2768 if (Offset != None)
2769 Remap.insert(std::make_pair(Offset,
2770 static_cast<int>(BaseOffset - Offset)));
2771 };
2772 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2773 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2774 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2775 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2776 PreprocessedEntityRemap);
2777 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2778 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2779 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2780 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002781
2782 // Global -> local mappings.
2783 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2784 }
2785 break;
2786 }
2787
2788 case SOURCE_MANAGER_LINE_TABLE:
2789 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002790 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 break;
2792
2793 case SOURCE_LOCATION_PRELOADS: {
2794 // Need to transform from the local view (1-based IDs) to the global view,
2795 // which is based off F.SLocEntryBaseID.
2796 if (!F.PreloadSLocEntries.empty()) {
2797 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002798 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 }
2800
2801 F.PreloadSLocEntries.swap(Record);
2802 break;
2803 }
2804
2805 case EXT_VECTOR_DECLS:
2806 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2807 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2808 break;
2809
2810 case VTABLE_USES:
2811 if (Record.size() % 3 != 0) {
2812 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002813 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 }
2815
2816 // Later tables overwrite earlier ones.
2817 // FIXME: Modules will have some trouble with this. This is clearly not
2818 // the right way to do this.
2819 VTableUses.clear();
2820
2821 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2822 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2823 VTableUses.push_back(
2824 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2825 VTableUses.push_back(Record[Idx++]);
2826 }
2827 break;
2828
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 case PENDING_IMPLICIT_INSTANTIATIONS:
2830 if (PendingInstantiations.size() % 2 != 0) {
2831 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002832 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 }
2834
2835 if (Record.size() % 2 != 0) {
2836 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002837 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 }
2839
2840 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2841 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2842 PendingInstantiations.push_back(
2843 ReadSourceLocation(F, Record, I).getRawEncoding());
2844 }
2845 break;
2846
2847 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002848 if (Record.size() != 2) {
2849 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002850 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2853 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2854 break;
2855
2856 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002857 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2858 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2859 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002860
2861 unsigned LocalBasePreprocessedEntityID = Record[0];
2862
2863 unsigned StartingID;
2864 if (!PP.getPreprocessingRecord())
2865 PP.createPreprocessingRecord();
2866 if (!PP.getPreprocessingRecord()->getExternalSource())
2867 PP.getPreprocessingRecord()->SetExternalSource(*this);
2868 StartingID
2869 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002870 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 F.BasePreprocessedEntityID = StartingID;
2872
2873 if (F.NumPreprocessedEntities > 0) {
2874 // Introduce the global -> local mapping for preprocessed entities in
2875 // this module.
2876 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2877
2878 // Introduce the local -> global mapping for preprocessed entities in
2879 // this module.
2880 F.PreprocessedEntityRemap.insertOrReplace(
2881 std::make_pair(LocalBasePreprocessedEntityID,
2882 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2883 }
2884
2885 break;
2886 }
2887
2888 case DECL_UPDATE_OFFSETS: {
2889 if (Record.size() % 2 != 0) {
2890 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002891 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002893 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2894 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2895 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2896
2897 // If we've already loaded the decl, perform the updates when we finish
2898 // loading this block.
2899 if (Decl *D = GetExistingDecl(ID))
2900 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2901 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 break;
2903 }
2904
2905 case DECL_REPLACEMENTS: {
2906 if (Record.size() % 3 != 0) {
2907 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002908 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 }
2910 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2911 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2912 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2913 break;
2914 }
2915
2916 case OBJC_CATEGORIES_MAP: {
2917 if (F.LocalNumObjCCategoriesInMap != 0) {
2918 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002919 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 }
2921
2922 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002923 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 break;
2925 }
2926
2927 case OBJC_CATEGORIES:
2928 F.ObjCCategories.swap(Record);
2929 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002930
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 case CXX_BASE_SPECIFIER_OFFSETS: {
2932 if (F.LocalNumCXXBaseSpecifiers != 0) {
2933 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002934 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002936
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002938 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002939 break;
2940 }
2941
2942 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2943 if (F.LocalNumCXXCtorInitializers != 0) {
2944 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2945 return Failure;
2946 }
2947
2948 F.LocalNumCXXCtorInitializers = Record[0];
2949 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 break;
2951 }
2952
2953 case DIAG_PRAGMA_MAPPINGS:
2954 if (F.PragmaDiagMappings.empty())
2955 F.PragmaDiagMappings.swap(Record);
2956 else
2957 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2958 Record.begin(), Record.end());
2959 break;
2960
2961 case CUDA_SPECIAL_DECL_REFS:
2962 // Later tables overwrite earlier ones.
2963 // FIXME: Modules will have trouble with this.
2964 CUDASpecialDeclRefs.clear();
2965 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2966 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2967 break;
2968
2969 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002970 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 if (Record[0]) {
2973 F.HeaderFileInfoTable
2974 = HeaderFileInfoLookupTable::Create(
2975 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2976 (const unsigned char *)F.HeaderFileInfoTableData,
2977 HeaderFileInfoTrait(*this, F,
2978 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002979 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002980
2981 PP.getHeaderSearchInfo().SetExternalSource(this);
2982 if (!PP.getHeaderSearchInfo().getExternalLookup())
2983 PP.getHeaderSearchInfo().SetExternalLookup(this);
2984 }
2985 break;
2986 }
2987
2988 case FP_PRAGMA_OPTIONS:
2989 // Later tables overwrite earlier ones.
2990 FPPragmaOptions.swap(Record);
2991 break;
2992
2993 case OPENCL_EXTENSIONS:
2994 // Later tables overwrite earlier ones.
2995 OpenCLExtensions.swap(Record);
2996 break;
2997
2998 case TENTATIVE_DEFINITIONS:
2999 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3000 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3001 break;
3002
3003 case KNOWN_NAMESPACES:
3004 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3005 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3006 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003007
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003008 case UNDEFINED_BUT_USED:
3009 if (UndefinedButUsed.size() % 2 != 0) {
3010 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003011 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003012 }
3013
3014 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003015 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003016 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003017 }
3018 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003019 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3020 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003021 ReadSourceLocation(F, Record, I).getRawEncoding());
3022 }
3023 break;
3024
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003026 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 // If we aren't loading a module (which has its own exports), make
3028 // all of the imported modules visible.
3029 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003030 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3031 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3032 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3033 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003034 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 }
3036 }
3037 break;
3038 }
3039
3040 case LOCAL_REDECLARATIONS: {
3041 F.RedeclarationChains.swap(Record);
3042 break;
3043 }
3044
3045 case LOCAL_REDECLARATIONS_MAP: {
3046 if (F.LocalNumRedeclarationsInMap != 0) {
3047 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003048 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 }
3050
3051 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003052 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 break;
3054 }
3055
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 case MACRO_OFFSET: {
3057 if (F.LocalNumMacros != 0) {
3058 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003059 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003061 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 F.LocalNumMacros = Record[0];
3063 unsigned LocalBaseMacroID = Record[1];
3064 F.BaseMacroID = getTotalNumMacros();
3065
3066 if (F.LocalNumMacros > 0) {
3067 // Introduce the global -> local mapping for macros within this module.
3068 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3069
3070 // Introduce the local -> global mapping for macros within this module.
3071 F.MacroRemap.insertOrReplace(
3072 std::make_pair(LocalBaseMacroID,
3073 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003074
3075 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 }
3077 break;
3078 }
3079
Richard Smithe40f2ba2013-08-07 21:41:30 +00003080 case LATE_PARSED_TEMPLATE: {
3081 LateParsedTemplates.append(Record.begin(), Record.end());
3082 break;
3083 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003084
3085 case OPTIMIZE_PRAGMA_OPTIONS:
3086 if (Record.size() != 1) {
3087 Error("invalid pragma optimize record");
3088 return Failure;
3089 }
3090 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3091 break;
Nico Weber72889432014-09-06 01:25:55 +00003092
3093 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3094 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3095 UnusedLocalTypedefNameCandidates.push_back(
3096 getGlobalDeclID(F, Record[I]));
3097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
3099 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003100}
3101
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003102ASTReader::ASTReadResult
3103ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3104 const ModuleFile *ImportedBy,
3105 unsigned ClientLoadCapabilities) {
3106 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003107 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003108
Richard Smithe842a472014-10-22 02:05:46 +00003109 if (F.Kind == MK_ExplicitModule) {
3110 // For an explicitly-loaded module, we don't care whether the original
3111 // module map file exists or matches.
3112 return Success;
3113 }
3114
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003115 // Try to resolve ModuleName in the current header search context and
3116 // verify that it is found in the same module map file as we saved. If the
3117 // top-level AST file is a main file, skip this check because there is no
3118 // usable header search context.
3119 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003120 "MODULE_NAME should come before MODULE_MAP_FILE");
3121 if (F.Kind == MK_ImplicitModule &&
3122 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3123 // An implicitly-loaded module file should have its module listed in some
3124 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003125 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003126 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3127 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3128 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003129 assert(ImportedBy && "top-level import should be verified");
3130 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003131 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3132 << ImportedBy->FileName
3133 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003134 return Missing;
3135 }
3136
Richard Smithe842a472014-10-22 02:05:46 +00003137 assert(M->Name == F.ModuleName && "found module with different name");
3138
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003139 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003140 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003141 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3142 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003143 assert(ImportedBy && "top-level import should be verified");
3144 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3145 Diag(diag::err_imported_module_modmap_changed)
3146 << F.ModuleName << ImportedBy->FileName
3147 << ModMap->getName() << F.ModuleMapPath;
3148 return OutOfDate;
3149 }
3150
3151 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3152 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3153 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003154 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155 const FileEntry *F =
3156 FileMgr.getFile(Filename, false, false);
3157 if (F == nullptr) {
3158 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3159 Error("could not find file '" + Filename +"' referenced by AST file");
3160 return OutOfDate;
3161 }
3162 AdditionalStoredMaps.insert(F);
3163 }
3164
3165 // Check any additional module map files (e.g. module.private.modulemap)
3166 // that are not in the pcm.
3167 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3168 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3169 // Remove files that match
3170 // Note: SmallPtrSet::erase is really remove
3171 if (!AdditionalStoredMaps.erase(ModMap)) {
3172 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3173 Diag(diag::err_module_different_modmap)
3174 << F.ModuleName << /*new*/0 << ModMap->getName();
3175 return OutOfDate;
3176 }
3177 }
3178 }
3179
3180 // Check any additional module map files that are in the pcm, but not
3181 // found in header search. Cases that match are already removed.
3182 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3183 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3184 Diag(diag::err_module_different_modmap)
3185 << F.ModuleName << /*not new*/1 << ModMap->getName();
3186 return OutOfDate;
3187 }
3188 }
3189
3190 if (Listener)
3191 Listener->ReadModuleMapFile(F.ModuleMapPath);
3192 return Success;
3193}
3194
3195
Douglas Gregorc1489562013-02-12 23:36:21 +00003196/// \brief Move the given method to the back of the global list of methods.
3197static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3198 // Find the entry for this selector in the method pool.
3199 Sema::GlobalMethodPool::iterator Known
3200 = S.MethodPool.find(Method->getSelector());
3201 if (Known == S.MethodPool.end())
3202 return;
3203
3204 // Retrieve the appropriate method list.
3205 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3206 : Known->second.second;
3207 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003208 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003209 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003210 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003211 Found = true;
3212 } else {
3213 // Keep searching.
3214 continue;
3215 }
3216 }
3217
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003218 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003219 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003220 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003221 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003222 }
3223}
3224
Richard Smithde711422015-04-23 21:20:19 +00003225void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003226 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003227 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003228 bool wasHidden = D->Hidden;
3229 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003230
Richard Smith49f906a2014-03-01 00:08:04 +00003231 if (wasHidden && SemaObj) {
3232 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3233 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003234 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 }
3236 }
3237}
3238
Richard Smith49f906a2014-03-01 00:08:04 +00003239void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003240 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003241 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003243 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003244 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003246 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003247
3248 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003249 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 // there is nothing more to do.
3251 continue;
3252 }
Richard Smith49f906a2014-03-01 00:08:04 +00003253
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 if (!Mod->isAvailable()) {
3255 // Modules that aren't available cannot be made visible.
3256 continue;
3257 }
3258
3259 // Update the module's name visibility.
3260 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003261
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 // If we've already deserialized any names from this module,
3263 // mark them as visible.
3264 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3265 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003266 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003268 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003269 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3270 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003272
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003274 SmallVector<Module *, 16> Exports;
3275 Mod->getExportedModules(Exports);
3276 for (SmallVectorImpl<Module *>::iterator
3277 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3278 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003279 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003280 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 }
3282 }
3283}
3284
Douglas Gregore060e572013-01-25 01:03:03 +00003285bool ASTReader::loadGlobalIndex() {
3286 if (GlobalIndex)
3287 return false;
3288
3289 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3290 !Context.getLangOpts().Modules)
3291 return true;
3292
3293 // Try to load the global index.
3294 TriedLoadingGlobalIndex = true;
3295 StringRef ModuleCachePath
3296 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3297 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003298 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003299 if (!Result.first)
3300 return true;
3301
3302 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003303 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003304 return false;
3305}
3306
3307bool ASTReader::isGlobalIndexUnavailable() const {
3308 return Context.getLangOpts().Modules && UseGlobalIndex &&
3309 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3310}
3311
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003312static void updateModuleTimestamp(ModuleFile &MF) {
3313 // Overwrite the timestamp file contents so that file's mtime changes.
3314 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003315 std::error_code EC;
3316 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3317 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003318 return;
3319 OS << "Timestamp file\n";
3320}
3321
Guy Benyei11169dd2012-12-18 14:30:41 +00003322ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3323 ModuleKind Type,
3324 SourceLocation ImportLoc,
3325 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003326 llvm::SaveAndRestore<SourceLocation>
3327 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3328
Richard Smithd1c46742014-04-30 02:24:17 +00003329 // Defer any pending actions until we get to the end of reading the AST file.
3330 Deserializing AnASTFile(this);
3331
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003333 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003334
3335 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003336 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003338 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003339 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 ClientLoadCapabilities)) {
3341 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003342 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 case OutOfDate:
3344 case VersionMismatch:
3345 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003346 case HadErrors: {
3347 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3348 for (const ImportedModule &IM : Loaded)
3349 LoadedSet.insert(IM.Mod);
3350
Douglas Gregor7029ce12013-03-19 00:28:20 +00003351 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003352 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003353 Context.getLangOpts().Modules
3354 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003355 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003356
3357 // If we find that any modules are unusable, the global index is going
3358 // to be out-of-date. Just remove it.
3359 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003360 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003362 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 case Success:
3364 break;
3365 }
3366
3367 // Here comes stuff that we only do once the entire chain is loaded.
3368
3369 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003370 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3371 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 M != MEnd; ++M) {
3373 ModuleFile &F = *M->Mod;
3374
3375 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003376 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3377 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003378
3379 // Once read, set the ModuleFile bit base offset and update the size in
3380 // bits of all files we've seen.
3381 F.GlobalBitOffset = TotalModulesSizeInBits;
3382 TotalModulesSizeInBits += F.SizeInBits;
3383 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3384
3385 // Preload SLocEntries.
3386 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3387 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3388 // Load it through the SourceManager and don't call ReadSLocEntry()
3389 // directly because the entry may have already been loaded in which case
3390 // calling ReadSLocEntry() directly would trigger an assertion in
3391 // SourceManager.
3392 SourceMgr.getLoadedSLocEntryByID(Index);
3393 }
3394 }
3395
Douglas Gregor603cd862013-03-22 18:50:14 +00003396 // Setup the import locations and notify the module manager that we've
3397 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003398 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3399 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 M != MEnd; ++M) {
3401 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003402
3403 ModuleMgr.moduleFileAccepted(&F);
3404
3405 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003406 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 if (!M->ImportedBy)
3408 F.ImportLoc = M->ImportLoc;
3409 else
3410 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3411 M->ImportLoc.getRawEncoding());
3412 }
3413
3414 // Mark all of the identifiers in the identifier table as being out of date,
3415 // so that various accessors know to check the loaded modules when the
3416 // identifier is used.
3417 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3418 IdEnd = PP.getIdentifierTable().end();
3419 Id != IdEnd; ++Id)
3420 Id->second->setOutOfDate(true);
3421
3422 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003423 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3424 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3426 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003427
3428 switch (Unresolved.Kind) {
3429 case UnresolvedModuleRef::Conflict:
3430 if (ResolvedMod) {
3431 Module::Conflict Conflict;
3432 Conflict.Other = ResolvedMod;
3433 Conflict.Message = Unresolved.String.str();
3434 Unresolved.Mod->Conflicts.push_back(Conflict);
3435 }
3436 continue;
3437
3438 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003440 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003441 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003442
Douglas Gregorfb912652013-03-20 21:10:35 +00003443 case UnresolvedModuleRef::Export:
3444 if (ResolvedMod || Unresolved.IsWildcard)
3445 Unresolved.Mod->Exports.push_back(
3446 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3447 continue;
3448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003450 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003451
3452 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3453 // Might be unnecessary as use declarations are only used to build the
3454 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003455
3456 InitializeContext();
3457
Richard Smith3d8e97e2013-10-18 06:54:39 +00003458 if (SemaObj)
3459 UpdateSema();
3460
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 if (DeserializationListener)
3462 DeserializationListener->ReaderInitialized(this);
3463
3464 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3465 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3466 PrimaryModule.OriginalSourceFileID
3467 = FileID::get(PrimaryModule.SLocEntryBaseID
3468 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3469
3470 // If this AST file is a precompiled preamble, then set the
3471 // preamble file ID of the source manager to the file source file
3472 // from which the preamble was built.
3473 if (Type == MK_Preamble) {
3474 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3475 } else if (Type == MK_MainFile) {
3476 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3477 }
3478 }
3479
3480 // For any Objective-C class definitions we have already loaded, make sure
3481 // that we load any additional categories.
3482 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3483 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3484 ObjCClassesLoaded[I],
3485 PreviousGeneration);
3486 }
Douglas Gregore060e572013-01-25 01:03:03 +00003487
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003488 if (PP.getHeaderSearchInfo()
3489 .getHeaderSearchOpts()
3490 .ModulesValidateOncePerBuildSession) {
3491 // Now we are certain that the module and all modules it depends on are
3492 // up to date. Create or update timestamp files for modules that are
3493 // located in the module cache (not for PCH files that could be anywhere
3494 // in the filesystem).
3495 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3496 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003497 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003498 updateModuleTimestamp(*M.Mod);
3499 }
3500 }
3501 }
3502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 return Success;
3504}
3505
Ben Langmuir487ea142014-10-23 18:05:36 +00003506static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3507
Ben Langmuir70a1b812015-03-24 04:43:52 +00003508/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3509static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3510 return Stream.Read(8) == 'C' &&
3511 Stream.Read(8) == 'P' &&
3512 Stream.Read(8) == 'C' &&
3513 Stream.Read(8) == 'H';
3514}
3515
Guy Benyei11169dd2012-12-18 14:30:41 +00003516ASTReader::ASTReadResult
3517ASTReader::ReadASTCore(StringRef FileName,
3518 ModuleKind Type,
3519 SourceLocation ImportLoc,
3520 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003521 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003522 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003523 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 unsigned ClientLoadCapabilities) {
3525 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003527 ModuleManager::AddModuleResult AddResult
3528 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003529 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003530 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003531 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003532
Douglas Gregor7029ce12013-03-19 00:28:20 +00003533 switch (AddResult) {
3534 case ModuleManager::AlreadyLoaded:
3535 return Success;
3536
3537 case ModuleManager::NewlyLoaded:
3538 // Load module file below.
3539 break;
3540
3541 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003542 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003543 // it.
3544 if (ClientLoadCapabilities & ARR_Missing)
3545 return Missing;
3546
3547 // Otherwise, return an error.
3548 {
3549 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3550 + ErrorStr;
3551 Error(Msg);
3552 }
3553 return Failure;
3554
3555 case ModuleManager::OutOfDate:
3556 // We couldn't load the module file because it is out-of-date. If the
3557 // client can handle out-of-date, return it.
3558 if (ClientLoadCapabilities & ARR_OutOfDate)
3559 return OutOfDate;
3560
3561 // Otherwise, return an error.
3562 {
3563 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3564 + ErrorStr;
3565 Error(Msg);
3566 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003567 return Failure;
3568 }
3569
Douglas Gregor7029ce12013-03-19 00:28:20 +00003570 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003571
3572 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3573 // module?
3574 if (FileName != "-") {
3575 CurrentDir = llvm::sys::path::parent_path(FileName);
3576 if (CurrentDir.empty()) CurrentDir = ".";
3577 }
3578
3579 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003580 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003581 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003582 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3583
Guy Benyei11169dd2012-12-18 14:30:41 +00003584 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003585 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003586 Diag(diag::err_not_a_pch_file) << FileName;
3587 return Failure;
3588 }
3589
3590 // This is used for compatibility with older PCH formats.
3591 bool HaveReadControlBlock = false;
3592
Chris Lattnerefa77172013-01-20 00:00:22 +00003593 while (1) {
3594 llvm::BitstreamEntry Entry = Stream.advance();
3595
3596 switch (Entry.Kind) {
3597 case llvm::BitstreamEntry::Error:
3598 case llvm::BitstreamEntry::EndBlock:
3599 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 Error("invalid record at top-level of AST file");
3601 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003602
3603 case llvm::BitstreamEntry::SubBlock:
3604 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 }
3606
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003608 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3610 if (Stream.ReadBlockInfoBlock()) {
3611 Error("malformed BlockInfoBlock in AST file");
3612 return Failure;
3613 }
3614 break;
3615 case CONTROL_BLOCK_ID:
3616 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003617 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 case Success:
3619 break;
3620
3621 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003622 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003623 case OutOfDate: return OutOfDate;
3624 case VersionMismatch: return VersionMismatch;
3625 case ConfigurationMismatch: return ConfigurationMismatch;
3626 case HadErrors: return HadErrors;
3627 }
3628 break;
3629 case AST_BLOCK_ID:
3630 if (!HaveReadControlBlock) {
3631 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003632 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 return VersionMismatch;
3634 }
3635
3636 // Record that we've loaded this module.
3637 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3638 return Success;
3639
3640 default:
3641 if (Stream.SkipBlock()) {
3642 Error("malformed block record in AST file");
3643 return Failure;
3644 }
3645 break;
3646 }
3647 }
3648
3649 return Success;
3650}
3651
Richard Smitha7e2cc62015-05-01 01:53:09 +00003652void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003653 // If there's a listener, notify them that we "read" the translation unit.
3654 if (DeserializationListener)
3655 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3656 Context.getTranslationUnitDecl());
3657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 // FIXME: Find a better way to deal with collisions between these
3659 // built-in types. Right now, we just ignore the problem.
3660
3661 // Load the special types.
3662 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3663 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3664 if (!Context.CFConstantStringTypeDecl)
3665 Context.setCFConstantStringType(GetType(String));
3666 }
3667
3668 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3669 QualType FileType = GetType(File);
3670 if (FileType.isNull()) {
3671 Error("FILE type is NULL");
3672 return;
3673 }
3674
3675 if (!Context.FILEDecl) {
3676 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3677 Context.setFILEDecl(Typedef->getDecl());
3678 else {
3679 const TagType *Tag = FileType->getAs<TagType>();
3680 if (!Tag) {
3681 Error("Invalid FILE type in AST file");
3682 return;
3683 }
3684 Context.setFILEDecl(Tag->getDecl());
3685 }
3686 }
3687 }
3688
3689 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3690 QualType Jmp_bufType = GetType(Jmp_buf);
3691 if (Jmp_bufType.isNull()) {
3692 Error("jmp_buf type is NULL");
3693 return;
3694 }
3695
3696 if (!Context.jmp_bufDecl) {
3697 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3698 Context.setjmp_bufDecl(Typedef->getDecl());
3699 else {
3700 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3701 if (!Tag) {
3702 Error("Invalid jmp_buf type in AST file");
3703 return;
3704 }
3705 Context.setjmp_bufDecl(Tag->getDecl());
3706 }
3707 }
3708 }
3709
3710 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3711 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3712 if (Sigjmp_bufType.isNull()) {
3713 Error("sigjmp_buf type is NULL");
3714 return;
3715 }
3716
3717 if (!Context.sigjmp_bufDecl) {
3718 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3719 Context.setsigjmp_bufDecl(Typedef->getDecl());
3720 else {
3721 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3722 assert(Tag && "Invalid sigjmp_buf type in AST file");
3723 Context.setsigjmp_bufDecl(Tag->getDecl());
3724 }
3725 }
3726 }
3727
3728 if (unsigned ObjCIdRedef
3729 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3730 if (Context.ObjCIdRedefinitionType.isNull())
3731 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3732 }
3733
3734 if (unsigned ObjCClassRedef
3735 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3736 if (Context.ObjCClassRedefinitionType.isNull())
3737 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3738 }
3739
3740 if (unsigned ObjCSelRedef
3741 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3742 if (Context.ObjCSelRedefinitionType.isNull())
3743 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3744 }
3745
3746 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3747 QualType Ucontext_tType = GetType(Ucontext_t);
3748 if (Ucontext_tType.isNull()) {
3749 Error("ucontext_t type is NULL");
3750 return;
3751 }
3752
3753 if (!Context.ucontext_tDecl) {
3754 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3755 Context.setucontext_tDecl(Typedef->getDecl());
3756 else {
3757 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3758 assert(Tag && "Invalid ucontext_t type in AST file");
3759 Context.setucontext_tDecl(Tag->getDecl());
3760 }
3761 }
3762 }
3763 }
3764
3765 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3766
3767 // If there were any CUDA special declarations, deserialize them.
3768 if (!CUDASpecialDeclRefs.empty()) {
3769 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3770 Context.setcudaConfigureCallDecl(
3771 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3772 }
Richard Smith56be7542014-03-21 00:33:59 +00003773
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003775 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003776 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003777 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003778 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003779 /*ImportLoc=*/Import.ImportLoc);
3780 PP.makeModuleVisible(Imported, Import.ImportLoc);
3781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 }
3783 ImportedModules.clear();
3784}
3785
3786void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003787 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003788}
3789
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003790/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3791/// cursor into the start of the given block ID, returning false on success and
3792/// true on failure.
3793static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003794 while (1) {
3795 llvm::BitstreamEntry Entry = Cursor.advance();
3796 switch (Entry.Kind) {
3797 case llvm::BitstreamEntry::Error:
3798 case llvm::BitstreamEntry::EndBlock:
3799 return true;
3800
3801 case llvm::BitstreamEntry::Record:
3802 // Ignore top-level records.
3803 Cursor.skipRecord(Entry.ID);
3804 break;
3805
3806 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003807 if (Entry.ID == BlockID) {
3808 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003809 return true;
3810 // Found it!
3811 return false;
3812 }
3813
3814 if (Cursor.SkipBlock())
3815 return true;
3816 }
3817 }
3818}
3819
Ben Langmuir70a1b812015-03-24 04:43:52 +00003820/// \brief Reads and return the signature record from \p StreamFile's control
3821/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003822static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3823 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003824 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003825 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003826
3827 // Scan for the CONTROL_BLOCK_ID block.
3828 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3829 return 0;
3830
3831 // Scan for SIGNATURE inside the control block.
3832 ASTReader::RecordData Record;
3833 while (1) {
3834 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3835 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3836 Entry.Kind != llvm::BitstreamEntry::Record)
3837 return 0;
3838
3839 Record.clear();
3840 StringRef Blob;
3841 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3842 return Record[0];
3843 }
3844}
3845
Guy Benyei11169dd2012-12-18 14:30:41 +00003846/// \brief Retrieve the name of the original source file name
3847/// directly from the AST file, without actually loading the AST
3848/// file.
3849std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3850 FileManager &FileMgr,
3851 DiagnosticsEngine &Diags) {
3852 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003853 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003855 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3856 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003857 return std::string();
3858 }
3859
3860 // Initialize the stream
3861 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003862 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3863 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003864 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003865
3866 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003867 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3869 return std::string();
3870 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003871
Chris Lattnere7b154b2013-01-19 21:39:22 +00003872 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003873 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003874 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3875 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003876 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003877
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003878 // Scan for ORIGINAL_FILE inside the control block.
3879 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003880 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003881 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003882 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3883 return std::string();
3884
3885 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3886 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3887 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003889
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003891 StringRef Blob;
3892 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3893 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003895}
3896
3897namespace {
3898 class SimplePCHValidator : public ASTReaderListener {
3899 const LangOptions &ExistingLangOpts;
3900 const TargetOptions &ExistingTargetOpts;
3901 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003902 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003903 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003904
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 public:
3906 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3907 const TargetOptions &ExistingTargetOpts,
3908 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003909 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 FileManager &FileMgr)
3911 : ExistingLangOpts(ExistingLangOpts),
3912 ExistingTargetOpts(ExistingTargetOpts),
3913 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003914 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 FileMgr(FileMgr)
3916 {
3917 }
3918
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003919 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3920 bool AllowCompatibleDifferences) override {
3921 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3922 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003924 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3925 bool AllowCompatibleDifferences) override {
3926 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3927 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003929 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3930 StringRef SpecificModuleCachePath,
3931 bool Complain) override {
3932 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3933 ExistingModuleCachePath,
3934 nullptr, ExistingLangOpts);
3935 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003936 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3937 bool Complain,
3938 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003939 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003940 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 }
3942 };
3943}
3944
3945bool ASTReader::readASTFileControlBlock(StringRef Filename,
3946 FileManager &FileMgr,
3947 ASTReaderListener &Listener) {
3948 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003949 // FIXME: This allows use of the VFS; we do not allow use of the
3950 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003951 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 if (!Buffer) {
3953 return true;
3954 }
3955
3956 // Initialize the stream
3957 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003958 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3959 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003960 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003961
3962 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003963 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003965
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003966 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003967 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003968 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003969
3970 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003971 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00003972 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003973 BitstreamCursor InputFilesCursor;
3974 if (NeedsInputFiles) {
3975 InputFilesCursor = Stream;
3976 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3977 return true;
3978
3979 // Read the abbreviations
3980 while (true) {
3981 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3982 unsigned Code = InputFilesCursor.ReadCode();
3983
3984 // We expect all abbrevs to be at the start of the block.
3985 if (Code != llvm::bitc::DEFINE_ABBREV) {
3986 InputFilesCursor.JumpToBit(Offset);
3987 break;
3988 }
3989 InputFilesCursor.ReadAbbrevRecord();
3990 }
3991 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003992
3993 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003995 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003996 while (1) {
3997 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3998 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3999 return false;
4000
4001 if (Entry.Kind != llvm::BitstreamEntry::Record)
4002 return true;
4003
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004005 StringRef Blob;
4006 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004007 switch ((ControlRecordTypes)RecCode) {
4008 case METADATA: {
4009 if (Record[0] != VERSION_MAJOR)
4010 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004011
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004012 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004013 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004014
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004015 break;
4016 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004017 case MODULE_NAME:
4018 Listener.ReadModuleName(Blob);
4019 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004020 case MODULE_DIRECTORY:
4021 ModuleDir = Blob;
4022 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004023 case MODULE_MAP_FILE: {
4024 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004025 auto Path = ReadString(Record, Idx);
4026 ResolveImportedPath(Path, ModuleDir);
4027 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004028 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004029 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004031 if (ParseLanguageOptions(Record, false, Listener,
4032 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004033 return true;
4034 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004035
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004037 if (ParseTargetOptions(Record, false, Listener,
4038 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004039 return true;
4040 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004041
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004042 case DIAGNOSTIC_OPTIONS:
4043 if (ParseDiagnosticOptions(Record, false, Listener))
4044 return true;
4045 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004046
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004047 case FILE_SYSTEM_OPTIONS:
4048 if (ParseFileSystemOptions(Record, false, Listener))
4049 return true;
4050 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004051
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004052 case HEADER_SEARCH_OPTIONS:
4053 if (ParseHeaderSearchOptions(Record, false, Listener))
4054 return true;
4055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 case PREPROCESSOR_OPTIONS: {
4058 std::string IgnoredSuggestedPredefines;
4059 if (ParsePreprocessorOptions(Record, false, Listener,
4060 IgnoredSuggestedPredefines))
4061 return true;
4062 break;
4063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004065 case INPUT_FILE_OFFSETS: {
4066 if (!NeedsInputFiles)
4067 break;
4068
4069 unsigned NumInputFiles = Record[0];
4070 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004071 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004072 for (unsigned I = 0; I != NumInputFiles; ++I) {
4073 // Go find this input file.
4074 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004075
4076 if (isSystemFile && !NeedsSystemInputFiles)
4077 break; // the rest are system input files
4078
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004079 BitstreamCursor &Cursor = InputFilesCursor;
4080 SavedStreamPosition SavedPosition(Cursor);
4081 Cursor.JumpToBit(InputFileOffs[I]);
4082
4083 unsigned Code = Cursor.ReadCode();
4084 RecordData Record;
4085 StringRef Blob;
4086 bool shouldContinue = false;
4087 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4088 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004089 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004090 std::string Filename = Blob;
4091 ResolveImportedPath(Filename, ModuleDir);
4092 shouldContinue =
4093 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004094 break;
4095 }
4096 if (!shouldContinue)
4097 break;
4098 }
4099 break;
4100 }
4101
Richard Smithd4b230b2014-10-27 23:01:16 +00004102 case IMPORTS: {
4103 if (!NeedsImports)
4104 break;
4105
4106 unsigned Idx = 0, N = Record.size();
4107 while (Idx < N) {
4108 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004109 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004110 std::string Filename = ReadString(Record, Idx);
4111 ResolveImportedPath(Filename, ModuleDir);
4112 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004113 }
4114 break;
4115 }
4116
Richard Smith7f330cd2015-03-18 01:42:29 +00004117 case KNOWN_MODULE_FILES: {
4118 // Known-but-not-technically-used module files are treated as imports.
4119 if (!NeedsImports)
4120 break;
4121
4122 unsigned Idx = 0, N = Record.size();
4123 while (Idx < N) {
4124 std::string Filename = ReadString(Record, Idx);
4125 ResolveImportedPath(Filename, ModuleDir);
4126 Listener.visitImport(Filename);
4127 }
4128 break;
4129 }
4130
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004131 default:
4132 // No other validation to perform.
4133 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 }
4135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004136}
4137
4138
4139bool ASTReader::isAcceptableASTFile(StringRef Filename,
4140 FileManager &FileMgr,
4141 const LangOptions &LangOpts,
4142 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004143 const PreprocessorOptions &PPOpts,
4144 std::string ExistingModuleCachePath) {
4145 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4146 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 return !readASTFileControlBlock(Filename, FileMgr, validator);
4148}
4149
Ben Langmuir2c9af442014-04-10 17:57:43 +00004150ASTReader::ASTReadResult
4151ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 // Enter the submodule block.
4153 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4154 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004155 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156 }
4157
4158 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4159 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004160 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 RecordData Record;
4162 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004163 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4164
4165 switch (Entry.Kind) {
4166 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4167 case llvm::BitstreamEntry::Error:
4168 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004169 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004170 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004171 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004172 case llvm::BitstreamEntry::Record:
4173 // The interesting case.
4174 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004176
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004178 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004180 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4181
4182 if ((Kind == SUBMODULE_METADATA) != First) {
4183 Error("submodule metadata record should be at beginning of block");
4184 return Failure;
4185 }
4186 First = false;
4187
4188 // Submodule information is only valid if we have a current module.
4189 // FIXME: Should we error on these cases?
4190 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4191 Kind != SUBMODULE_DEFINITION)
4192 continue;
4193
4194 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 default: // Default behavior: ignore.
4196 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197
Richard Smith03478d92014-10-23 22:12:14 +00004198 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004199 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004201 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
Richard Smith03478d92014-10-23 22:12:14 +00004203
Chris Lattner0e6c9402013-01-20 02:38:54 +00004204 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004205 unsigned Idx = 0;
4206 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4207 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4208 bool IsFramework = Record[Idx++];
4209 bool IsExplicit = Record[Idx++];
4210 bool IsSystem = Record[Idx++];
4211 bool IsExternC = Record[Idx++];
4212 bool InferSubmodules = Record[Idx++];
4213 bool InferExplicitSubmodules = Record[Idx++];
4214 bool InferExportWildcard = Record[Idx++];
4215 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004216
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004217 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004218 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004220
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 // Retrieve this (sub)module from the module map, creating it if
4222 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004223 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004225
4226 // FIXME: set the definition loc for CurrentModule, or call
4227 // ModMap.setInferredModuleAllowedBy()
4228
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4230 if (GlobalIndex >= SubmodulesLoaded.size() ||
4231 SubmodulesLoaded[GlobalIndex]) {
4232 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004233 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004235
Douglas Gregor7029ce12013-03-19 00:28:20 +00004236 if (!ParentModule) {
4237 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4238 if (CurFile != F.File) {
4239 if (!Diags.isDiagnosticInFlight()) {
4240 Diag(diag::err_module_file_conflict)
4241 << CurrentModule->getTopLevelModuleName()
4242 << CurFile->getName()
4243 << F.File->getName();
4244 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004245 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004246 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004247 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004248
4249 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004250 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004251
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 CurrentModule->IsFromModuleFile = true;
4253 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004254 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 CurrentModule->InferSubmodules = InferSubmodules;
4256 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4257 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004258 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 if (DeserializationListener)
4260 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4261
4262 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004263
Douglas Gregorfb912652013-03-20 21:10:35 +00004264 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004265 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004266 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004267 CurrentModule->UnresolvedConflicts.clear();
4268 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 break;
4270 }
4271
4272 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004273 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 if (!CurrentModule->getUmbrellaHeader())
4275 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4276 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004277 // This can be a spurious difference caused by changing the VFS to
4278 // point to a different copy of the file, and it is too late to
4279 // to rebuild safely.
4280 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4281 // after input file validation only real problems would remain and we
4282 // could just error. For now, assume it's okay.
4283 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 }
4285 }
4286 break;
4287 }
4288
Richard Smith202210b2014-10-24 20:23:01 +00004289 case SUBMODULE_HEADER:
4290 case SUBMODULE_EXCLUDED_HEADER:
4291 case SUBMODULE_PRIVATE_HEADER:
4292 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004293 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4294 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004295 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296
Richard Smith202210b2014-10-24 20:23:01 +00004297 case SUBMODULE_TEXTUAL_HEADER:
4298 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4299 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4300 // them here.
4301 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004302
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004304 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 break;
4306 }
4307
4308 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004310 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 if (!CurrentModule->getUmbrellaDir())
4312 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4313 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004314 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4315 Error("mismatched umbrella directories in submodule");
4316 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 }
4318 }
4319 break;
4320 }
4321
4322 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 F.BaseSubmoduleID = getTotalNumSubmodules();
4324 F.LocalNumSubmodules = Record[0];
4325 unsigned LocalBaseSubmoduleID = Record[1];
4326 if (F.LocalNumSubmodules > 0) {
4327 // Introduce the global -> local mapping for submodules within this
4328 // module.
4329 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4330
4331 // Introduce the local -> global mapping for submodules within this
4332 // module.
4333 F.SubmoduleRemap.insertOrReplace(
4334 std::make_pair(LocalBaseSubmoduleID,
4335 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004336
Ben Langmuir52ca6782014-10-20 16:27:32 +00004337 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 break;
4340 }
4341
4342 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004344 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 Unresolved.File = &F;
4346 Unresolved.Mod = CurrentModule;
4347 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004348 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004350 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 }
4352 break;
4353 }
4354
4355 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004357 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 Unresolved.File = &F;
4359 Unresolved.Mod = CurrentModule;
4360 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004361 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004363 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 }
4365
4366 // Once we've loaded the set of exports, there's no reason to keep
4367 // the parsed, unresolved exports around.
4368 CurrentModule->UnresolvedExports.clear();
4369 break;
4370 }
4371 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004372 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 Context.getTargetInfo());
4374 break;
4375 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004376
4377 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004378 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004379 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004380 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004381
4382 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004383 CurrentModule->ConfigMacros.push_back(Blob.str());
4384 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004385
4386 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 UnresolvedModuleRef Unresolved;
4388 Unresolved.File = &F;
4389 Unresolved.Mod = CurrentModule;
4390 Unresolved.ID = Record[0];
4391 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4392 Unresolved.IsWildcard = false;
4393 Unresolved.String = Blob;
4394 UnresolvedModuleRefs.push_back(Unresolved);
4395 break;
4396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 }
4398 }
4399}
4400
4401/// \brief Parse the record that corresponds to a LangOptions data
4402/// structure.
4403///
4404/// This routine parses the language options from the AST file and then gives
4405/// them to the AST listener if one is set.
4406///
4407/// \returns true if the listener deems the file unacceptable, false otherwise.
4408bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4409 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004410 ASTReaderListener &Listener,
4411 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 LangOptions LangOpts;
4413 unsigned Idx = 0;
4414#define LANGOPT(Name, Bits, Default, Description) \
4415 LangOpts.Name = Record[Idx++];
4416#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4417 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4418#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004419#define SANITIZER(NAME, ID) \
4420 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004421#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004422
4423 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4424 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4425 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4426
4427 unsigned Length = Record[Idx++];
4428 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4429 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004430
4431 Idx += Length;
4432
4433 // Comment options.
4434 for (unsigned N = Record[Idx++]; N; --N) {
4435 LangOpts.CommentOpts.BlockCommandNames.push_back(
4436 ReadString(Record, Idx));
4437 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004438 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004439
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004440 return Listener.ReadLanguageOptions(LangOpts, Complain,
4441 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004442}
4443
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004444bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4445 ASTReaderListener &Listener,
4446 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004447 unsigned Idx = 0;
4448 TargetOptions TargetOpts;
4449 TargetOpts.Triple = ReadString(Record, Idx);
4450 TargetOpts.CPU = ReadString(Record, Idx);
4451 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 for (unsigned N = Record[Idx++]; N; --N) {
4453 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4454 }
4455 for (unsigned N = Record[Idx++]; N; --N) {
4456 TargetOpts.Features.push_back(ReadString(Record, Idx));
4457 }
4458
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004459 return Listener.ReadTargetOptions(TargetOpts, Complain,
4460 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004461}
4462
4463bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4464 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004465 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004467#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004468#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004469 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004470#include "clang/Basic/DiagnosticOptions.def"
4471
Richard Smith3be1cb22014-08-07 00:24:21 +00004472 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004473 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004474 for (unsigned N = Record[Idx++]; N; --N)
4475 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004476
4477 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4478}
4479
4480bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4481 ASTReaderListener &Listener) {
4482 FileSystemOptions FSOpts;
4483 unsigned Idx = 0;
4484 FSOpts.WorkingDir = ReadString(Record, Idx);
4485 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4486}
4487
4488bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4489 bool Complain,
4490 ASTReaderListener &Listener) {
4491 HeaderSearchOptions HSOpts;
4492 unsigned Idx = 0;
4493 HSOpts.Sysroot = ReadString(Record, Idx);
4494
4495 // Include entries.
4496 for (unsigned N = Record[Idx++]; N; --N) {
4497 std::string Path = ReadString(Record, Idx);
4498 frontend::IncludeDirGroup Group
4499 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 bool IsFramework = Record[Idx++];
4501 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004503 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 }
4505
4506 // System header prefixes.
4507 for (unsigned N = Record[Idx++]; N; --N) {
4508 std::string Prefix = ReadString(Record, Idx);
4509 bool IsSystemHeader = Record[Idx++];
4510 HSOpts.SystemHeaderPrefixes.push_back(
4511 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4512 }
4513
4514 HSOpts.ResourceDir = ReadString(Record, Idx);
4515 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004516 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 HSOpts.DisableModuleHash = Record[Idx++];
4518 HSOpts.UseBuiltinIncludes = Record[Idx++];
4519 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4520 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4521 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004522 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004523
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004524 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4525 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004526}
4527
4528bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4529 bool Complain,
4530 ASTReaderListener &Listener,
4531 std::string &SuggestedPredefines) {
4532 PreprocessorOptions PPOpts;
4533 unsigned Idx = 0;
4534
4535 // Macro definitions/undefs
4536 for (unsigned N = Record[Idx++]; N; --N) {
4537 std::string Macro = ReadString(Record, Idx);
4538 bool IsUndef = Record[Idx++];
4539 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4540 }
4541
4542 // Includes
4543 for (unsigned N = Record[Idx++]; N; --N) {
4544 PPOpts.Includes.push_back(ReadString(Record, Idx));
4545 }
4546
4547 // Macro Includes
4548 for (unsigned N = Record[Idx++]; N; --N) {
4549 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4550 }
4551
4552 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004553 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004554 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4555 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4556 PPOpts.ObjCXXARCStandardLibrary =
4557 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4558 SuggestedPredefines.clear();
4559 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4560 SuggestedPredefines);
4561}
4562
4563std::pair<ModuleFile *, unsigned>
4564ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4565 GlobalPreprocessedEntityMapType::iterator
4566 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4567 assert(I != GlobalPreprocessedEntityMap.end() &&
4568 "Corrupted global preprocessed entity map");
4569 ModuleFile *M = I->second;
4570 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4571 return std::make_pair(M, LocalIndex);
4572}
4573
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004574llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004575ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4576 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4577 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4578 Mod.NumPreprocessedEntities);
4579
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004580 return llvm::make_range(PreprocessingRecord::iterator(),
4581 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004582}
4583
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004584llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004585ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004586 return llvm::make_range(
4587 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4588 ModuleDeclIterator(this, &Mod,
4589 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004590}
4591
4592PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4593 PreprocessedEntityID PPID = Index+1;
4594 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4595 ModuleFile &M = *PPInfo.first;
4596 unsigned LocalIndex = PPInfo.second;
4597 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4598
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 if (!PP.getPreprocessingRecord()) {
4600 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004601 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
4603
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004604 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4605 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4606
4607 llvm::BitstreamEntry Entry =
4608 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4609 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004610 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004611
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 // Read the record.
4613 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4614 ReadSourceLocation(M, PPOffs.End));
4615 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004616 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 RecordData Record;
4618 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004619 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4620 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 switch (RecType) {
4622 case PPD_MACRO_EXPANSION: {
4623 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004624 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004625 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 if (isBuiltin)
4627 Name = getLocalIdentifier(M, Record[1]);
4628 else {
Richard Smith66a81862015-05-04 02:25:31 +00004629 PreprocessedEntityID GlobalID =
4630 getGlobalPreprocessedEntityID(M, Record[1]);
4631 Def = cast<MacroDefinitionRecord>(
4632 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634
4635 MacroExpansion *ME;
4636 if (isBuiltin)
4637 ME = new (PPRec) MacroExpansion(Name, Range);
4638 else
4639 ME = new (PPRec) MacroExpansion(Def, Range);
4640
4641 return ME;
4642 }
4643
4644 case PPD_MACRO_DEFINITION: {
4645 // Decode the identifier info and then check again; if the macro is
4646 // still defined and associated with the identifier,
4647 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004648 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004649
4650 if (DeserializationListener)
4651 DeserializationListener->MacroDefinitionRead(PPID, MD);
4652
4653 return MD;
4654 }
4655
4656 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004657 const char *FullFileNameStart = Blob.data() + Record[0];
4658 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004659 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 if (!FullFileName.empty())
4661 File = PP.getFileManager().getFile(FullFileName);
4662
4663 // FIXME: Stable encoding
4664 InclusionDirective::InclusionKind Kind
4665 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4666 InclusionDirective *ID
4667 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004668 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 Record[1], Record[3],
4670 File,
4671 Range);
4672 return ID;
4673 }
4674 }
4675
4676 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4677}
4678
4679/// \brief \arg SLocMapI points at a chunk of a module that contains no
4680/// preprocessed entities or the entities it contains are not the ones we are
4681/// looking for. Find the next module that contains entities and return the ID
4682/// of the first entry.
4683PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4684 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4685 ++SLocMapI;
4686 for (GlobalSLocOffsetMapType::const_iterator
4687 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4688 ModuleFile &M = *SLocMapI->second;
4689 if (M.NumPreprocessedEntities)
4690 return M.BasePreprocessedEntityID;
4691 }
4692
4693 return getTotalNumPreprocessedEntities();
4694}
4695
4696namespace {
4697
4698template <unsigned PPEntityOffset::*PPLoc>
4699struct PPEntityComp {
4700 const ASTReader &Reader;
4701 ModuleFile &M;
4702
4703 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4704
4705 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4706 SourceLocation LHS = getLoc(L);
4707 SourceLocation RHS = getLoc(R);
4708 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4709 }
4710
4711 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4712 SourceLocation LHS = getLoc(L);
4713 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4714 }
4715
4716 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4717 SourceLocation RHS = getLoc(R);
4718 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4719 }
4720
4721 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4722 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4723 }
4724};
4725
4726}
4727
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004728PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4729 bool EndsAfter) const {
4730 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 return getTotalNumPreprocessedEntities();
4732
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004733 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4734 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4736 "Corrupted global sloc offset map");
4737
4738 if (SLocMapI->second->NumPreprocessedEntities == 0)
4739 return findNextPreprocessedEntity(SLocMapI);
4740
4741 ModuleFile &M = *SLocMapI->second;
4742 typedef const PPEntityOffset *pp_iterator;
4743 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4744 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4745
4746 size_t Count = M.NumPreprocessedEntities;
4747 size_t Half;
4748 pp_iterator First = pp_begin;
4749 pp_iterator PPI;
4750
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004751 if (EndsAfter) {
4752 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4753 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4754 } else {
4755 // Do a binary search manually instead of using std::lower_bound because
4756 // The end locations of entities may be unordered (when a macro expansion
4757 // is inside another macro argument), but for this case it is not important
4758 // whether we get the first macro expansion or its containing macro.
4759 while (Count > 0) {
4760 Half = Count / 2;
4761 PPI = First;
4762 std::advance(PPI, Half);
4763 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4764 Loc)) {
4765 First = PPI;
4766 ++First;
4767 Count = Count - Half - 1;
4768 } else
4769 Count = Half;
4770 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 }
4772
4773 if (PPI == pp_end)
4774 return findNextPreprocessedEntity(SLocMapI);
4775
4776 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4777}
4778
Guy Benyei11169dd2012-12-18 14:30:41 +00004779/// \brief Returns a pair of [Begin, End) indices of preallocated
4780/// preprocessed entities that \arg Range encompasses.
4781std::pair<unsigned, unsigned>
4782 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4783 if (Range.isInvalid())
4784 return std::make_pair(0,0);
4785 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4786
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004787 PreprocessedEntityID BeginID =
4788 findPreprocessedEntity(Range.getBegin(), false);
4789 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 return std::make_pair(BeginID, EndID);
4791}
4792
4793/// \brief Optionally returns true or false if the preallocated preprocessed
4794/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004795Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 FileID FID) {
4797 if (FID.isInvalid())
4798 return false;
4799
4800 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4801 ModuleFile &M = *PPInfo.first;
4802 unsigned LocalIndex = PPInfo.second;
4803 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4804
4805 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4806 if (Loc.isInvalid())
4807 return false;
4808
4809 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4810 return true;
4811 else
4812 return false;
4813}
4814
4815namespace {
4816 /// \brief Visitor used to search for information about a header file.
4817 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 const FileEntry *FE;
4819
David Blaikie05785d12013-02-20 22:23:23 +00004820 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004821
4822 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004823 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4824 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004825
4826 static bool visit(ModuleFile &M, void *UserData) {
4827 HeaderFileInfoVisitor *This
4828 = static_cast<HeaderFileInfoVisitor *>(UserData);
4829
Guy Benyei11169dd2012-12-18 14:30:41 +00004830 HeaderFileInfoLookupTable *Table
4831 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4832 if (!Table)
4833 return false;
4834
4835 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004836 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 if (Pos == Table->end())
4838 return false;
4839
4840 This->HFI = *Pos;
4841 return true;
4842 }
4843
David Blaikie05785d12013-02-20 22:23:23 +00004844 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 };
4846}
4847
4848HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004849 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004851 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004853
4854 return HeaderFileInfo();
4855}
4856
4857void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4858 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004859 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4861 ModuleFile &F = *(*I);
4862 unsigned Idx = 0;
4863 DiagStates.clear();
4864 assert(!Diag.DiagStates.empty());
4865 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4866 while (Idx < F.PragmaDiagMappings.size()) {
4867 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4868 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4869 if (DiagStateID != 0) {
4870 Diag.DiagStatePoints.push_back(
4871 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4872 FullSourceLoc(Loc, SourceMgr)));
4873 continue;
4874 }
4875
4876 assert(DiagStateID == 0);
4877 // A new DiagState was created here.
4878 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4879 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4880 DiagStates.push_back(NewState);
4881 Diag.DiagStatePoints.push_back(
4882 DiagnosticsEngine::DiagStatePoint(NewState,
4883 FullSourceLoc(Loc, SourceMgr)));
4884 while (1) {
4885 assert(Idx < F.PragmaDiagMappings.size() &&
4886 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4887 if (Idx >= F.PragmaDiagMappings.size()) {
4888 break; // Something is messed up but at least avoid infinite loop in
4889 // release build.
4890 }
4891 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4892 if (DiagID == (unsigned)-1) {
4893 break; // no more diag/map pairs for this location.
4894 }
Alp Tokerc726c362014-06-10 09:31:37 +00004895 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4896 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4897 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 }
4899 }
4900 }
4901}
4902
4903/// \brief Get the correct cursor and offset for loading a type.
4904ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4905 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4906 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4907 ModuleFile *M = I->second;
4908 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4909}
4910
4911/// \brief Read and return the type with the given index..
4912///
4913/// The index is the type ID, shifted and minus the number of predefs. This
4914/// routine actually reads the record corresponding to the type at the given
4915/// location. It is a helper routine for GetType, which deals with reading type
4916/// IDs.
4917QualType ASTReader::readTypeRecord(unsigned Index) {
4918 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004919 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004920
4921 // Keep track of where we are in the stream, then jump back there
4922 // after reading this type.
4923 SavedStreamPosition SavedPosition(DeclsCursor);
4924
4925 ReadingKindTracker ReadingKind(Read_Type, *this);
4926
4927 // Note that we are loading a type record.
4928 Deserializing AType(this);
4929
4930 unsigned Idx = 0;
4931 DeclsCursor.JumpToBit(Loc.Offset);
4932 RecordData Record;
4933 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004934 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 case TYPE_EXT_QUAL: {
4936 if (Record.size() != 2) {
4937 Error("Incorrect encoding of extended qualifier type");
4938 return QualType();
4939 }
4940 QualType Base = readType(*Loc.F, Record, Idx);
4941 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4942 return Context.getQualifiedType(Base, Quals);
4943 }
4944
4945 case TYPE_COMPLEX: {
4946 if (Record.size() != 1) {
4947 Error("Incorrect encoding of complex type");
4948 return QualType();
4949 }
4950 QualType ElemType = readType(*Loc.F, Record, Idx);
4951 return Context.getComplexType(ElemType);
4952 }
4953
4954 case TYPE_POINTER: {
4955 if (Record.size() != 1) {
4956 Error("Incorrect encoding of pointer type");
4957 return QualType();
4958 }
4959 QualType PointeeType = readType(*Loc.F, Record, Idx);
4960 return Context.getPointerType(PointeeType);
4961 }
4962
Reid Kleckner8a365022013-06-24 17:51:48 +00004963 case TYPE_DECAYED: {
4964 if (Record.size() != 1) {
4965 Error("Incorrect encoding of decayed type");
4966 return QualType();
4967 }
4968 QualType OriginalType = readType(*Loc.F, Record, Idx);
4969 QualType DT = Context.getAdjustedParameterType(OriginalType);
4970 if (!isa<DecayedType>(DT))
4971 Error("Decayed type does not decay");
4972 return DT;
4973 }
4974
Reid Kleckner0503a872013-12-05 01:23:43 +00004975 case TYPE_ADJUSTED: {
4976 if (Record.size() != 2) {
4977 Error("Incorrect encoding of adjusted type");
4978 return QualType();
4979 }
4980 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4981 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4982 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4983 }
4984
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 case TYPE_BLOCK_POINTER: {
4986 if (Record.size() != 1) {
4987 Error("Incorrect encoding of block pointer type");
4988 return QualType();
4989 }
4990 QualType PointeeType = readType(*Loc.F, Record, Idx);
4991 return Context.getBlockPointerType(PointeeType);
4992 }
4993
4994 case TYPE_LVALUE_REFERENCE: {
4995 if (Record.size() != 2) {
4996 Error("Incorrect encoding of lvalue reference type");
4997 return QualType();
4998 }
4999 QualType PointeeType = readType(*Loc.F, Record, Idx);
5000 return Context.getLValueReferenceType(PointeeType, Record[1]);
5001 }
5002
5003 case TYPE_RVALUE_REFERENCE: {
5004 if (Record.size() != 1) {
5005 Error("Incorrect encoding of rvalue reference type");
5006 return QualType();
5007 }
5008 QualType PointeeType = readType(*Loc.F, Record, Idx);
5009 return Context.getRValueReferenceType(PointeeType);
5010 }
5011
5012 case TYPE_MEMBER_POINTER: {
5013 if (Record.size() != 2) {
5014 Error("Incorrect encoding of member pointer type");
5015 return QualType();
5016 }
5017 QualType PointeeType = readType(*Loc.F, Record, Idx);
5018 QualType ClassType = readType(*Loc.F, Record, Idx);
5019 if (PointeeType.isNull() || ClassType.isNull())
5020 return QualType();
5021
5022 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5023 }
5024
5025 case TYPE_CONSTANT_ARRAY: {
5026 QualType ElementType = readType(*Loc.F, Record, Idx);
5027 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5028 unsigned IndexTypeQuals = Record[2];
5029 unsigned Idx = 3;
5030 llvm::APInt Size = ReadAPInt(Record, Idx);
5031 return Context.getConstantArrayType(ElementType, Size,
5032 ASM, IndexTypeQuals);
5033 }
5034
5035 case TYPE_INCOMPLETE_ARRAY: {
5036 QualType ElementType = readType(*Loc.F, Record, Idx);
5037 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5038 unsigned IndexTypeQuals = Record[2];
5039 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5040 }
5041
5042 case TYPE_VARIABLE_ARRAY: {
5043 QualType ElementType = readType(*Loc.F, Record, Idx);
5044 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5045 unsigned IndexTypeQuals = Record[2];
5046 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5047 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5048 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5049 ASM, IndexTypeQuals,
5050 SourceRange(LBLoc, RBLoc));
5051 }
5052
5053 case TYPE_VECTOR: {
5054 if (Record.size() != 3) {
5055 Error("incorrect encoding of vector type in AST file");
5056 return QualType();
5057 }
5058
5059 QualType ElementType = readType(*Loc.F, Record, Idx);
5060 unsigned NumElements = Record[1];
5061 unsigned VecKind = Record[2];
5062 return Context.getVectorType(ElementType, NumElements,
5063 (VectorType::VectorKind)VecKind);
5064 }
5065
5066 case TYPE_EXT_VECTOR: {
5067 if (Record.size() != 3) {
5068 Error("incorrect encoding of extended vector type in AST file");
5069 return QualType();
5070 }
5071
5072 QualType ElementType = readType(*Loc.F, Record, Idx);
5073 unsigned NumElements = Record[1];
5074 return Context.getExtVectorType(ElementType, NumElements);
5075 }
5076
5077 case TYPE_FUNCTION_NO_PROTO: {
5078 if (Record.size() != 6) {
5079 Error("incorrect encoding of no-proto function type");
5080 return QualType();
5081 }
5082 QualType ResultType = readType(*Loc.F, Record, Idx);
5083 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5084 (CallingConv)Record[4], Record[5]);
5085 return Context.getFunctionNoProtoType(ResultType, Info);
5086 }
5087
5088 case TYPE_FUNCTION_PROTO: {
5089 QualType ResultType = readType(*Loc.F, Record, Idx);
5090
5091 FunctionProtoType::ExtProtoInfo EPI;
5092 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5093 /*hasregparm*/ Record[2],
5094 /*regparm*/ Record[3],
5095 static_cast<CallingConv>(Record[4]),
5096 /*produces*/ Record[5]);
5097
5098 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005099
5100 EPI.Variadic = Record[Idx++];
5101 EPI.HasTrailingReturn = Record[Idx++];
5102 EPI.TypeQuals = Record[Idx++];
5103 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005104 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005105 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005106
5107 unsigned NumParams = Record[Idx++];
5108 SmallVector<QualType, 16> ParamTypes;
5109 for (unsigned I = 0; I != NumParams; ++I)
5110 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5111
Jordan Rose5c382722013-03-08 21:51:21 +00005112 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 }
5114
5115 case TYPE_UNRESOLVED_USING: {
5116 unsigned Idx = 0;
5117 return Context.getTypeDeclType(
5118 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5119 }
5120
5121 case TYPE_TYPEDEF: {
5122 if (Record.size() != 2) {
5123 Error("incorrect encoding of typedef type");
5124 return QualType();
5125 }
5126 unsigned Idx = 0;
5127 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5128 QualType Canonical = readType(*Loc.F, Record, Idx);
5129 if (!Canonical.isNull())
5130 Canonical = Context.getCanonicalType(Canonical);
5131 return Context.getTypedefType(Decl, Canonical);
5132 }
5133
5134 case TYPE_TYPEOF_EXPR:
5135 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5136
5137 case TYPE_TYPEOF: {
5138 if (Record.size() != 1) {
5139 Error("incorrect encoding of typeof(type) in AST file");
5140 return QualType();
5141 }
5142 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5143 return Context.getTypeOfType(UnderlyingType);
5144 }
5145
5146 case TYPE_DECLTYPE: {
5147 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5148 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5149 }
5150
5151 case TYPE_UNARY_TRANSFORM: {
5152 QualType BaseType = readType(*Loc.F, Record, Idx);
5153 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5154 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5155 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5156 }
5157
Richard Smith74aeef52013-04-26 16:15:35 +00005158 case TYPE_AUTO: {
5159 QualType Deduced = readType(*Loc.F, Record, Idx);
5160 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005161 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005162 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005164
5165 case TYPE_RECORD: {
5166 if (Record.size() != 2) {
5167 Error("incorrect encoding of record type");
5168 return QualType();
5169 }
5170 unsigned Idx = 0;
5171 bool IsDependent = Record[Idx++];
5172 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5173 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5174 QualType T = Context.getRecordType(RD);
5175 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5176 return T;
5177 }
5178
5179 case TYPE_ENUM: {
5180 if (Record.size() != 2) {
5181 Error("incorrect encoding of enum type");
5182 return QualType();
5183 }
5184 unsigned Idx = 0;
5185 bool IsDependent = Record[Idx++];
5186 QualType T
5187 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5188 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5189 return T;
5190 }
5191
5192 case TYPE_ATTRIBUTED: {
5193 if (Record.size() != 3) {
5194 Error("incorrect encoding of attributed type");
5195 return QualType();
5196 }
5197 QualType modifiedType = readType(*Loc.F, Record, Idx);
5198 QualType equivalentType = readType(*Loc.F, Record, Idx);
5199 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5200 return Context.getAttributedType(kind, modifiedType, equivalentType);
5201 }
5202
5203 case TYPE_PAREN: {
5204 if (Record.size() != 1) {
5205 Error("incorrect encoding of paren type");
5206 return QualType();
5207 }
5208 QualType InnerType = readType(*Loc.F, Record, Idx);
5209 return Context.getParenType(InnerType);
5210 }
5211
5212 case TYPE_PACK_EXPANSION: {
5213 if (Record.size() != 2) {
5214 Error("incorrect encoding of pack expansion type");
5215 return QualType();
5216 }
5217 QualType Pattern = readType(*Loc.F, Record, Idx);
5218 if (Pattern.isNull())
5219 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005220 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 if (Record[1])
5222 NumExpansions = Record[1] - 1;
5223 return Context.getPackExpansionType(Pattern, NumExpansions);
5224 }
5225
5226 case TYPE_ELABORATED: {
5227 unsigned Idx = 0;
5228 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5229 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5230 QualType NamedType = readType(*Loc.F, Record, Idx);
5231 return Context.getElaboratedType(Keyword, NNS, NamedType);
5232 }
5233
5234 case TYPE_OBJC_INTERFACE: {
5235 unsigned Idx = 0;
5236 ObjCInterfaceDecl *ItfD
5237 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5238 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5239 }
5240
5241 case TYPE_OBJC_OBJECT: {
5242 unsigned Idx = 0;
5243 QualType Base = readType(*Loc.F, Record, Idx);
5244 unsigned NumProtos = Record[Idx++];
5245 SmallVector<ObjCProtocolDecl*, 4> Protos;
5246 for (unsigned I = 0; I != NumProtos; ++I)
5247 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5248 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5249 }
5250
5251 case TYPE_OBJC_OBJECT_POINTER: {
5252 unsigned Idx = 0;
5253 QualType Pointee = readType(*Loc.F, Record, Idx);
5254 return Context.getObjCObjectPointerType(Pointee);
5255 }
5256
5257 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5258 unsigned Idx = 0;
5259 QualType Parm = readType(*Loc.F, Record, Idx);
5260 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005261 return Context.getSubstTemplateTypeParmType(
5262 cast<TemplateTypeParmType>(Parm),
5263 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 }
5265
5266 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5267 unsigned Idx = 0;
5268 QualType Parm = readType(*Loc.F, Record, Idx);
5269 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5270 return Context.getSubstTemplateTypeParmPackType(
5271 cast<TemplateTypeParmType>(Parm),
5272 ArgPack);
5273 }
5274
5275 case TYPE_INJECTED_CLASS_NAME: {
5276 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5277 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5278 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5279 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005280 const Type *T = nullptr;
5281 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5282 if (const Type *Existing = DI->getTypeForDecl()) {
5283 T = Existing;
5284 break;
5285 }
5286 }
5287 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005288 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005289 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5290 DI->setTypeForDecl(T);
5291 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005292 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 }
5294
5295 case TYPE_TEMPLATE_TYPE_PARM: {
5296 unsigned Idx = 0;
5297 unsigned Depth = Record[Idx++];
5298 unsigned Index = Record[Idx++];
5299 bool Pack = Record[Idx++];
5300 TemplateTypeParmDecl *D
5301 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5302 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5303 }
5304
5305 case TYPE_DEPENDENT_NAME: {
5306 unsigned Idx = 0;
5307 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5308 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5309 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5310 QualType Canon = readType(*Loc.F, Record, Idx);
5311 if (!Canon.isNull())
5312 Canon = Context.getCanonicalType(Canon);
5313 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5314 }
5315
5316 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5317 unsigned Idx = 0;
5318 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5319 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5320 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5321 unsigned NumArgs = Record[Idx++];
5322 SmallVector<TemplateArgument, 8> Args;
5323 Args.reserve(NumArgs);
5324 while (NumArgs--)
5325 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5326 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5327 Args.size(), Args.data());
5328 }
5329
5330 case TYPE_DEPENDENT_SIZED_ARRAY: {
5331 unsigned Idx = 0;
5332
5333 // ArrayType
5334 QualType ElementType = readType(*Loc.F, Record, Idx);
5335 ArrayType::ArraySizeModifier ASM
5336 = (ArrayType::ArraySizeModifier)Record[Idx++];
5337 unsigned IndexTypeQuals = Record[Idx++];
5338
5339 // DependentSizedArrayType
5340 Expr *NumElts = ReadExpr(*Loc.F);
5341 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5342
5343 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5344 IndexTypeQuals, Brackets);
5345 }
5346
5347 case TYPE_TEMPLATE_SPECIALIZATION: {
5348 unsigned Idx = 0;
5349 bool IsDependent = Record[Idx++];
5350 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5351 SmallVector<TemplateArgument, 8> Args;
5352 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5353 QualType Underlying = readType(*Loc.F, Record, Idx);
5354 QualType T;
5355 if (Underlying.isNull())
5356 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5357 Args.size());
5358 else
5359 T = Context.getTemplateSpecializationType(Name, Args.data(),
5360 Args.size(), Underlying);
5361 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5362 return T;
5363 }
5364
5365 case TYPE_ATOMIC: {
5366 if (Record.size() != 1) {
5367 Error("Incorrect encoding of atomic type");
5368 return QualType();
5369 }
5370 QualType ValueType = readType(*Loc.F, Record, Idx);
5371 return Context.getAtomicType(ValueType);
5372 }
5373 }
5374 llvm_unreachable("Invalid TypeCode!");
5375}
5376
Richard Smith564417a2014-03-20 21:47:22 +00005377void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5378 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005379 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005380 const RecordData &Record, unsigned &Idx) {
5381 ExceptionSpecificationType EST =
5382 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005383 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005384 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005385 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005386 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005387 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005388 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005389 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005390 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005391 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5392 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005393 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005394 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005395 }
5396}
5397
Guy Benyei11169dd2012-12-18 14:30:41 +00005398class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5399 ASTReader &Reader;
5400 ModuleFile &F;
5401 const ASTReader::RecordData &Record;
5402 unsigned &Idx;
5403
5404 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5405 unsigned &I) {
5406 return Reader.ReadSourceLocation(F, R, I);
5407 }
5408
5409 template<typename T>
5410 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5411 return Reader.ReadDeclAs<T>(F, Record, Idx);
5412 }
5413
5414public:
5415 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5416 const ASTReader::RecordData &Record, unsigned &Idx)
5417 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5418 { }
5419
5420 // We want compile-time assurance that we've enumerated all of
5421 // these, so unfortunately we have to declare them first, then
5422 // define them out-of-line.
5423#define ABSTRACT_TYPELOC(CLASS, PARENT)
5424#define TYPELOC(CLASS, PARENT) \
5425 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5426#include "clang/AST/TypeLocNodes.def"
5427
5428 void VisitFunctionTypeLoc(FunctionTypeLoc);
5429 void VisitArrayTypeLoc(ArrayTypeLoc);
5430};
5431
5432void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5433 // nothing to do
5434}
5435void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5436 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5437 if (TL.needsExtraLocalData()) {
5438 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5439 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5440 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5441 TL.setModeAttr(Record[Idx++]);
5442 }
5443}
5444void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5445 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5446}
5447void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5448 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5449}
Reid Kleckner8a365022013-06-24 17:51:48 +00005450void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5451 // nothing to do
5452}
Reid Kleckner0503a872013-12-05 01:23:43 +00005453void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5454 // nothing to do
5455}
Guy Benyei11169dd2012-12-18 14:30:41 +00005456void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5457 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5458}
5459void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5460 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5461}
5462void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5463 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5464}
5465void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5466 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5467 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5468}
5469void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5470 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5471 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5472 if (Record[Idx++])
5473 TL.setSizeExpr(Reader.ReadExpr(F));
5474 else
Craig Toppera13603a2014-05-22 05:54:18 +00005475 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005476}
5477void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5478 VisitArrayTypeLoc(TL);
5479}
5480void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5481 VisitArrayTypeLoc(TL);
5482}
5483void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5484 VisitArrayTypeLoc(TL);
5485}
5486void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5487 DependentSizedArrayTypeLoc TL) {
5488 VisitArrayTypeLoc(TL);
5489}
5490void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5491 DependentSizedExtVectorTypeLoc TL) {
5492 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5493}
5494void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5495 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5496}
5497void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5498 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5499}
5500void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5501 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5502 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5503 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5504 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005505 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5506 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 }
5508}
5509void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5510 VisitFunctionTypeLoc(TL);
5511}
5512void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5513 VisitFunctionTypeLoc(TL);
5514}
5515void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5516 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5517}
5518void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5519 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5520}
5521void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5522 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5523 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5524 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5525}
5526void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5527 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5528 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5529 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5530 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5531}
5532void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5533 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5534}
5535void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5536 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5537 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5538 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5539 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5540}
5541void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5542 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5543}
5544void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5545 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5546}
5547void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5548 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5549}
5550void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5551 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5552 if (TL.hasAttrOperand()) {
5553 SourceRange range;
5554 range.setBegin(ReadSourceLocation(Record, Idx));
5555 range.setEnd(ReadSourceLocation(Record, Idx));
5556 TL.setAttrOperandParensRange(range);
5557 }
5558 if (TL.hasAttrExprOperand()) {
5559 if (Record[Idx++])
5560 TL.setAttrExprOperand(Reader.ReadExpr(F));
5561 else
Craig Toppera13603a2014-05-22 05:54:18 +00005562 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 } else if (TL.hasAttrEnumOperand())
5564 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5565}
5566void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5567 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5568}
5569void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5570 SubstTemplateTypeParmTypeLoc TL) {
5571 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5574 SubstTemplateTypeParmPackTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5578 TemplateSpecializationTypeLoc TL) {
5579 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5580 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5581 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5582 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5583 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5584 TL.setArgLocInfo(i,
5585 Reader.GetTemplateArgumentLocInfo(F,
5586 TL.getTypePtr()->getArg(i).getKind(),
5587 Record, Idx));
5588}
5589void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5590 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5591 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5594 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5595 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5596}
5597void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5598 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5599}
5600void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5601 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5602 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5603 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5604}
5605void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5606 DependentTemplateSpecializationTypeLoc TL) {
5607 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5608 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5609 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5610 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5611 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5612 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5613 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5614 TL.setArgLocInfo(I,
5615 Reader.GetTemplateArgumentLocInfo(F,
5616 TL.getTypePtr()->getArg(I).getKind(),
5617 Record, Idx));
5618}
5619void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5620 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5621}
5622void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5623 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5626 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5627 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5628 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5629 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5630 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5631}
5632void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5633 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5636 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5637 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5639}
5640
5641TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5642 const RecordData &Record,
5643 unsigned &Idx) {
5644 QualType InfoTy = readType(F, Record, Idx);
5645 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005646 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005647
5648 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5649 TypeLocReader TLR(*this, F, Record, Idx);
5650 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5651 TLR.Visit(TL);
5652 return TInfo;
5653}
5654
5655QualType ASTReader::GetType(TypeID ID) {
5656 unsigned FastQuals = ID & Qualifiers::FastMask;
5657 unsigned Index = ID >> Qualifiers::FastWidth;
5658
5659 if (Index < NUM_PREDEF_TYPE_IDS) {
5660 QualType T;
5661 switch ((PredefinedTypeIDs)Index) {
5662 case PREDEF_TYPE_NULL_ID: return QualType();
5663 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5664 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5665
5666 case PREDEF_TYPE_CHAR_U_ID:
5667 case PREDEF_TYPE_CHAR_S_ID:
5668 // FIXME: Check that the signedness of CharTy is correct!
5669 T = Context.CharTy;
5670 break;
5671
5672 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5673 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5674 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5675 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5676 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5677 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5678 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5679 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5680 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5681 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5682 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5683 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5684 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5685 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5686 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5687 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5688 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5689 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5690 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5691 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5692 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5693 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5694 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5695 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5696 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5697 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5698 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5699 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005700 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5701 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5702 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5703 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5704 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5705 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005706 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005707 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005708 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5709
5710 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5711 T = Context.getAutoRRefDeductType();
5712 break;
5713
5714 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5715 T = Context.ARCUnbridgedCastTy;
5716 break;
5717
5718 case PREDEF_TYPE_VA_LIST_TAG:
5719 T = Context.getVaListTagType();
5720 break;
5721
5722 case PREDEF_TYPE_BUILTIN_FN:
5723 T = Context.BuiltinFnTy;
5724 break;
5725 }
5726
5727 assert(!T.isNull() && "Unknown predefined type");
5728 return T.withFastQualifiers(FastQuals);
5729 }
5730
5731 Index -= NUM_PREDEF_TYPE_IDS;
5732 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5733 if (TypesLoaded[Index].isNull()) {
5734 TypesLoaded[Index] = readTypeRecord(Index);
5735 if (TypesLoaded[Index].isNull())
5736 return QualType();
5737
5738 TypesLoaded[Index]->setFromAST();
5739 if (DeserializationListener)
5740 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5741 TypesLoaded[Index]);
5742 }
5743
5744 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5745}
5746
5747QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5748 return GetType(getGlobalTypeID(F, LocalID));
5749}
5750
5751serialization::TypeID
5752ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5753 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5754 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5755
5756 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5757 return LocalID;
5758
5759 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5760 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5761 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5762
5763 unsigned GlobalIndex = LocalIndex + I->second;
5764 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5765}
5766
5767TemplateArgumentLocInfo
5768ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5769 TemplateArgument::ArgKind Kind,
5770 const RecordData &Record,
5771 unsigned &Index) {
5772 switch (Kind) {
5773 case TemplateArgument::Expression:
5774 return ReadExpr(F);
5775 case TemplateArgument::Type:
5776 return GetTypeSourceInfo(F, Record, Index);
5777 case TemplateArgument::Template: {
5778 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5779 Index);
5780 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5781 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5782 SourceLocation());
5783 }
5784 case TemplateArgument::TemplateExpansion: {
5785 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5786 Index);
5787 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5788 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5789 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5790 EllipsisLoc);
5791 }
5792 case TemplateArgument::Null:
5793 case TemplateArgument::Integral:
5794 case TemplateArgument::Declaration:
5795 case TemplateArgument::NullPtr:
5796 case TemplateArgument::Pack:
5797 // FIXME: Is this right?
5798 return TemplateArgumentLocInfo();
5799 }
5800 llvm_unreachable("unexpected template argument loc");
5801}
5802
5803TemplateArgumentLoc
5804ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5805 const RecordData &Record, unsigned &Index) {
5806 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5807
5808 if (Arg.getKind() == TemplateArgument::Expression) {
5809 if (Record[Index++]) // bool InfoHasSameExpr.
5810 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5811 }
5812 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5813 Record, Index));
5814}
5815
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005816const ASTTemplateArgumentListInfo*
5817ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5818 const RecordData &Record,
5819 unsigned &Index) {
5820 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5821 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5822 unsigned NumArgsAsWritten = Record[Index++];
5823 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5824 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5825 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5826 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5827}
5828
Guy Benyei11169dd2012-12-18 14:30:41 +00005829Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5830 return GetDecl(ID);
5831}
5832
Richard Smith50895422015-01-31 03:04:55 +00005833template<typename TemplateSpecializationDecl>
5834static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5835 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5836 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5837}
5838
Richard Smith053f6c62014-05-16 23:01:30 +00005839void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005840 if (NumCurrentElementsDeserializing) {
5841 // We arrange to not care about the complete redeclaration chain while we're
5842 // deserializing. Just remember that the AST has marked this one as complete
5843 // but that it's not actually complete yet, so we know we still need to
5844 // complete it later.
5845 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5846 return;
5847 }
5848
Richard Smith053f6c62014-05-16 23:01:30 +00005849 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5850
Richard Smith053f6c62014-05-16 23:01:30 +00005851 // If this is a named declaration, complete it by looking it up
5852 // within its context.
5853 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005854 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005855 // all mergeable entities within it.
5856 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5857 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5858 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5859 auto *II = Name.getAsIdentifierInfo();
5860 if (isa<TranslationUnitDecl>(DC) && II) {
5861 // Outside of C++, we don't have a lookup table for the TU, so update
5862 // the identifier instead. In C++, either way should work fine.
5863 if (II->isOutOfDate())
5864 updateOutOfDateIdentifier(*II);
5865 } else
5866 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005867 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5868 // FIXME: It'd be nice to do something a bit more targeted here.
5869 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005870 }
5871 }
Richard Smith50895422015-01-31 03:04:55 +00005872
5873 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5874 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5875 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5876 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5877 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5878 if (auto *Template = FD->getPrimaryTemplate())
5879 Template->LoadLazySpecializations();
5880 }
Richard Smith053f6c62014-05-16 23:01:30 +00005881}
5882
Richard Smithc2bb8182015-03-24 06:36:48 +00005883uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5884 const RecordData &Record,
5885 unsigned &Idx) {
5886 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5887 Error("malformed AST file: missing C++ ctor initializers");
5888 return 0;
5889 }
5890
5891 unsigned LocalID = Record[Idx++];
5892 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5893}
5894
5895CXXCtorInitializer **
5896ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5897 RecordLocation Loc = getLocalBitOffset(Offset);
5898 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5899 SavedStreamPosition SavedPosition(Cursor);
5900 Cursor.JumpToBit(Loc.Offset);
5901 ReadingKindTracker ReadingKind(Read_Decl, *this);
5902
5903 RecordData Record;
5904 unsigned Code = Cursor.ReadCode();
5905 unsigned RecCode = Cursor.readRecord(Code, Record);
5906 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5907 Error("malformed AST file: missing C++ ctor initializers");
5908 return nullptr;
5909 }
5910
5911 unsigned Idx = 0;
5912 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5913}
5914
Richard Smithcd45dbc2014-04-19 03:48:30 +00005915uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5916 const RecordData &Record,
5917 unsigned &Idx) {
5918 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5919 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005920 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005921 }
5922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923 unsigned LocalID = Record[Idx++];
5924 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5925}
5926
5927CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5928 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005929 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005930 SavedStreamPosition SavedPosition(Cursor);
5931 Cursor.JumpToBit(Loc.Offset);
5932 ReadingKindTracker ReadingKind(Read_Decl, *this);
5933 RecordData Record;
5934 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005935 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005937 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005938 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 }
5940
5941 unsigned Idx = 0;
5942 unsigned NumBases = Record[Idx++];
5943 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5944 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5945 for (unsigned I = 0; I != NumBases; ++I)
5946 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5947 return Bases;
5948}
5949
5950serialization::DeclID
5951ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5952 if (LocalID < NUM_PREDEF_DECL_IDS)
5953 return LocalID;
5954
5955 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5956 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5957 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5958
5959 return LocalID + I->second;
5960}
5961
5962bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5963 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005964 // Predefined decls aren't from any module.
5965 if (ID < NUM_PREDEF_DECL_IDS)
5966 return false;
5967
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5969 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5970 return &M == I->second;
5971}
5972
Douglas Gregor9f782892013-01-21 15:25:38 +00005973ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005974 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00005975 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5977 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5978 return I->second;
5979}
5980
5981SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5982 if (ID < NUM_PREDEF_DECL_IDS)
5983 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00005984
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5986
5987 if (Index > DeclsLoaded.size()) {
5988 Error("declaration ID out-of-range for AST file");
5989 return SourceLocation();
5990 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005991
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 if (Decl *D = DeclsLoaded[Index])
5993 return D->getLocation();
5994
5995 unsigned RawLocation = 0;
5996 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5997 return ReadSourceLocation(*Rec.F, RawLocation);
5998}
5999
Richard Smithfe620d22015-03-05 23:24:12 +00006000static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6001 switch (ID) {
6002 case PREDEF_DECL_NULL_ID:
6003 return nullptr;
6004
6005 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6006 return Context.getTranslationUnitDecl();
6007
6008 case PREDEF_DECL_OBJC_ID_ID:
6009 return Context.getObjCIdDecl();
6010
6011 case PREDEF_DECL_OBJC_SEL_ID:
6012 return Context.getObjCSelDecl();
6013
6014 case PREDEF_DECL_OBJC_CLASS_ID:
6015 return Context.getObjCClassDecl();
6016
6017 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6018 return Context.getObjCProtocolDecl();
6019
6020 case PREDEF_DECL_INT_128_ID:
6021 return Context.getInt128Decl();
6022
6023 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6024 return Context.getUInt128Decl();
6025
6026 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6027 return Context.getObjCInstanceTypeDecl();
6028
6029 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6030 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006031
6032 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6033 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006034 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006035 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006036}
6037
Richard Smithcd45dbc2014-04-19 03:48:30 +00006038Decl *ASTReader::GetExistingDecl(DeclID ID) {
6039 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006040 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6041 if (D) {
6042 // Track that we have merged the declaration with ID \p ID into the
6043 // pre-existing predefined declaration \p D.
6044 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6045 if (Merged.empty())
6046 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 }
Richard Smithfe620d22015-03-05 23:24:12 +00006048 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006050
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6052
6053 if (Index >= DeclsLoaded.size()) {
6054 assert(0 && "declaration ID out-of-range for AST file");
6055 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006056 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006058
6059 return DeclsLoaded[Index];
6060}
6061
6062Decl *ASTReader::GetDecl(DeclID ID) {
6063 if (ID < NUM_PREDEF_DECL_IDS)
6064 return GetExistingDecl(ID);
6065
6066 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6067
6068 if (Index >= DeclsLoaded.size()) {
6069 assert(0 && "declaration ID out-of-range for AST file");
6070 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006071 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006072 }
6073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 if (!DeclsLoaded[Index]) {
6075 ReadDeclRecord(ID);
6076 if (DeserializationListener)
6077 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6078 }
6079
6080 return DeclsLoaded[Index];
6081}
6082
6083DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6084 DeclID GlobalID) {
6085 if (GlobalID < NUM_PREDEF_DECL_IDS)
6086 return GlobalID;
6087
6088 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6089 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6090 ModuleFile *Owner = I->second;
6091
6092 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6093 = M.GlobalToLocalDeclIDs.find(Owner);
6094 if (Pos == M.GlobalToLocalDeclIDs.end())
6095 return 0;
6096
6097 return GlobalID - Owner->BaseDeclID + Pos->second;
6098}
6099
6100serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6101 const RecordData &Record,
6102 unsigned &Idx) {
6103 if (Idx >= Record.size()) {
6104 Error("Corrupted AST file");
6105 return 0;
6106 }
6107
6108 return getGlobalDeclID(F, Record[Idx++]);
6109}
6110
6111/// \brief Resolve the offset of a statement into a statement.
6112///
6113/// This operation will read a new statement from the external
6114/// source each time it is called, and is meant to be used via a
6115/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6116Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6117 // Switch case IDs are per Decl.
6118 ClearSwitchCaseIDs();
6119
6120 // Offset here is a global offset across the entire chain.
6121 RecordLocation Loc = getLocalBitOffset(Offset);
6122 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6123 return ReadStmtFromStream(*Loc.F);
6124}
6125
6126namespace {
6127 class FindExternalLexicalDeclsVisitor {
6128 ASTReader &Reader;
6129 const DeclContext *DC;
6130 bool (*isKindWeWant)(Decl::Kind);
6131
6132 SmallVectorImpl<Decl*> &Decls;
6133 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6134
6135 public:
6136 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6137 bool (*isKindWeWant)(Decl::Kind),
6138 SmallVectorImpl<Decl*> &Decls)
6139 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6140 {
6141 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6142 PredefsVisited[I] = false;
6143 }
6144
6145 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6146 if (Preorder)
6147 return false;
6148
6149 FindExternalLexicalDeclsVisitor *This
6150 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6151
6152 ModuleFile::DeclContextInfosMap::iterator Info
6153 = M.DeclContextInfos.find(This->DC);
6154 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6155 return false;
6156
6157 // Load all of the declaration IDs
6158 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6159 *IDE = ID + Info->second.NumLexicalDecls;
6160 ID != IDE; ++ID) {
6161 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6162 continue;
6163
6164 // Don't add predefined declarations to the lexical context more
6165 // than once.
6166 if (ID->second < NUM_PREDEF_DECL_IDS) {
6167 if (This->PredefsVisited[ID->second])
6168 continue;
6169
6170 This->PredefsVisited[ID->second] = true;
6171 }
6172
6173 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6174 if (!This->DC->isDeclInLexicalTraversal(D))
6175 This->Decls.push_back(D);
6176 }
6177 }
6178
6179 return false;
6180 }
6181 };
6182}
6183
6184ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6185 bool (*isKindWeWant)(Decl::Kind),
6186 SmallVectorImpl<Decl*> &Decls) {
6187 // There might be lexical decls in multiple modules, for the TU at
6188 // least. Walk all of the modules in the order they were loaded.
6189 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6190 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6191 ++NumLexicalDeclContextsRead;
6192 return ELR_Success;
6193}
6194
6195namespace {
6196
6197class DeclIDComp {
6198 ASTReader &Reader;
6199 ModuleFile &Mod;
6200
6201public:
6202 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6203
6204 bool operator()(LocalDeclID L, LocalDeclID R) const {
6205 SourceLocation LHS = getLocation(L);
6206 SourceLocation RHS = getLocation(R);
6207 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6208 }
6209
6210 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6211 SourceLocation RHS = getLocation(R);
6212 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6213 }
6214
6215 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6216 SourceLocation LHS = getLocation(L);
6217 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6218 }
6219
6220 SourceLocation getLocation(LocalDeclID ID) const {
6221 return Reader.getSourceManager().getFileLoc(
6222 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6223 }
6224};
6225
6226}
6227
6228void ASTReader::FindFileRegionDecls(FileID File,
6229 unsigned Offset, unsigned Length,
6230 SmallVectorImpl<Decl *> &Decls) {
6231 SourceManager &SM = getSourceManager();
6232
6233 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6234 if (I == FileDeclIDs.end())
6235 return;
6236
6237 FileDeclsInfo &DInfo = I->second;
6238 if (DInfo.Decls.empty())
6239 return;
6240
6241 SourceLocation
6242 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6243 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6244
6245 DeclIDComp DIDComp(*this, *DInfo.Mod);
6246 ArrayRef<serialization::LocalDeclID>::iterator
6247 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6248 BeginLoc, DIDComp);
6249 if (BeginIt != DInfo.Decls.begin())
6250 --BeginIt;
6251
6252 // If we are pointing at a top-level decl inside an objc container, we need
6253 // to backtrack until we find it otherwise we will fail to report that the
6254 // region overlaps with an objc container.
6255 while (BeginIt != DInfo.Decls.begin() &&
6256 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6257 ->isTopLevelDeclInObjCContainer())
6258 --BeginIt;
6259
6260 ArrayRef<serialization::LocalDeclID>::iterator
6261 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6262 EndLoc, DIDComp);
6263 if (EndIt != DInfo.Decls.end())
6264 ++EndIt;
6265
6266 for (ArrayRef<serialization::LocalDeclID>::iterator
6267 DIt = BeginIt; DIt != EndIt; ++DIt)
6268 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6269}
6270
6271namespace {
6272 /// \brief ModuleFile visitor used to perform name lookup into a
6273 /// declaration context.
6274 class DeclContextNameLookupVisitor {
6275 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006276 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 DeclarationName Name;
6278 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006279 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006280
6281 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006282 DeclContextNameLookupVisitor(ASTReader &Reader,
6283 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006285 SmallVectorImpl<NamedDecl *> &Decls,
6286 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6287 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6288 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006289
6290 static bool visit(ModuleFile &M, void *UserData) {
6291 DeclContextNameLookupVisitor *This
6292 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6293
6294 // Check whether we have any visible declaration information for
6295 // this context in this module.
6296 ModuleFile::DeclContextInfosMap::iterator Info;
6297 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006298 for (auto *DC : This->Contexts) {
6299 Info = M.DeclContextInfos.find(DC);
6300 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006301 Info->second.NameLookupTableData) {
6302 FoundInfo = true;
6303 break;
6304 }
6305 }
6306
6307 if (!FoundInfo)
6308 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006309
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006311 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 Info->second.NameLookupTableData;
6313 ASTDeclContextNameLookupTable::iterator Pos
6314 = LookupTable->find(This->Name);
6315 if (Pos == LookupTable->end())
6316 return false;
6317
6318 bool FoundAnything = false;
6319 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6320 for (; Data.first != Data.second; ++Data.first) {
6321 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6322 if (!ND)
6323 continue;
6324
6325 if (ND->getDeclName() != This->Name) {
6326 // A name might be null because the decl's redeclarable part is
6327 // currently read before reading its name. The lookup is triggered by
6328 // building that decl (likely indirectly), and so it is later in the
6329 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006330 // FIXME: This should not happen; deserializing declarations should
6331 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 continue;
6333 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006334
Guy Benyei11169dd2012-12-18 14:30:41 +00006335 // Record this declaration.
6336 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006337 if (This->DeclSet.insert(ND).second)
6338 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 }
6340
6341 return FoundAnything;
6342 }
6343 };
6344}
6345
Douglas Gregor9f782892013-01-21 15:25:38 +00006346/// \brief Retrieve the "definitive" module file for the definition of the
6347/// given declaration context, if there is one.
6348///
6349/// The "definitive" module file is the only place where we need to look to
6350/// find information about the declarations within the given declaration
6351/// context. For example, C++ and Objective-C classes, C structs/unions, and
6352/// Objective-C protocols, categories, and extensions are all defined in a
6353/// single place in the source code, so they have definitive module files
6354/// associated with them. C++ namespaces, on the other hand, can have
6355/// definitions in multiple different module files.
6356///
6357/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6358/// NDEBUG checking.
6359static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6360 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006361 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6362 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006363
Craig Toppera13603a2014-05-22 05:54:18 +00006364 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006365}
6366
Richard Smith9ce12e32013-02-07 03:30:24 +00006367bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006368ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6369 DeclarationName Name) {
6370 assert(DC->hasExternalVisibleStorage() &&
6371 "DeclContext has no visible decls in storage");
6372 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006373 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006374
Richard Smith8c913ec2014-08-14 02:21:01 +00006375 Deserializing LookupResults(this);
6376
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006378 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006379
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 // Compute the declaration contexts we need to look into. Multiple such
6381 // declaration contexts occur when two declaration contexts from disjoint
6382 // modules get merged, e.g., when two namespaces with the same name are
6383 // independently defined in separate modules.
6384 SmallVector<const DeclContext *, 2> Contexts;
6385 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006386
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006388 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006389 if (Merged != MergedDecls.end()) {
6390 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6391 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6392 }
6393 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006394
6395 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006396 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006397
6398 // If we can definitively determine which module file to look into,
6399 // only look there. Otherwise, look in all module files.
6400 ModuleFile *Definitive;
6401 if (Contexts.size() == 1 &&
6402 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6403 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6404 } else {
6405 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6406 }
6407 };
6408
6409 LookUpInContexts(Contexts);
6410
6411 // If this might be an implicit special member function, then also search
6412 // all merged definitions of the surrounding class. We need to search them
6413 // individually, because finding an entity in one of them doesn't imply that
6414 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006415 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006416 auto Merged = MergedLookups.find(DC);
6417 if (Merged != MergedLookups.end()) {
6418 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6419 const DeclContext *Context = Merged->second[I];
6420 LookUpInContexts(Context);
6421 // We might have just added some more merged lookups. If so, our
6422 // iterator is now invalid, so grab a fresh one before continuing.
6423 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006424 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006425 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006426 }
6427
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 ++NumVisibleDeclContextsRead;
6429 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006430 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006431}
6432
6433namespace {
6434 /// \brief ModuleFile visitor used to retrieve all visible names in a
6435 /// declaration context.
6436 class DeclContextAllNamesVisitor {
6437 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006438 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006439 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006440 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006441 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006442
6443 public:
6444 DeclContextAllNamesVisitor(ASTReader &Reader,
6445 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006446 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006447 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006448
6449 static bool visit(ModuleFile &M, void *UserData) {
6450 DeclContextAllNamesVisitor *This
6451 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6452
6453 // Check whether we have any visible declaration information for
6454 // this context in this module.
6455 ModuleFile::DeclContextInfosMap::iterator Info;
6456 bool FoundInfo = false;
6457 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6458 Info = M.DeclContextInfos.find(This->Contexts[I]);
6459 if (Info != M.DeclContextInfos.end() &&
6460 Info->second.NameLookupTableData) {
6461 FoundInfo = true;
6462 break;
6463 }
6464 }
6465
6466 if (!FoundInfo)
6467 return false;
6468
Richard Smith52e3fba2014-03-11 07:17:35 +00006469 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006470 Info->second.NameLookupTableData;
6471 bool FoundAnything = false;
6472 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006473 I = LookupTable->data_begin(), E = LookupTable->data_end();
6474 I != E;
6475 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 ASTDeclContextNameLookupTrait::data_type Data = *I;
6477 for (; Data.first != Data.second; ++Data.first) {
6478 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6479 *Data.first);
6480 if (!ND)
6481 continue;
6482
6483 // Record this declaration.
6484 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006485 if (This->DeclSet.insert(ND).second)
6486 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 }
6488 }
6489
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006490 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 }
6492 };
6493}
6494
6495void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6496 if (!DC->hasExternalVisibleStorage())
6497 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006498 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006499
6500 // Compute the declaration contexts we need to look into. Multiple such
6501 // declaration contexts occur when two declaration contexts from disjoint
6502 // modules get merged, e.g., when two namespaces with the same name are
6503 // independently defined in separate modules.
6504 SmallVector<const DeclContext *, 2> Contexts;
6505 Contexts.push_back(DC);
6506
6507 if (DC->isNamespace()) {
6508 MergedDeclsMap::iterator Merged
6509 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6510 if (Merged != MergedDecls.end()) {
6511 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6512 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6513 }
6514 }
6515
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006516 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6517 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6519 ++NumVisibleDeclContextsRead;
6520
Craig Topper79be4cd2013-07-05 04:33:53 +00006521 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6523 }
6524 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6525}
6526
6527/// \brief Under non-PCH compilation the consumer receives the objc methods
6528/// before receiving the implementation, and codegen depends on this.
6529/// We simulate this by deserializing and passing to consumer the methods of the
6530/// implementation before passing the deserialized implementation decl.
6531static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6532 ASTConsumer *Consumer) {
6533 assert(ImplD && Consumer);
6534
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006535 for (auto *I : ImplD->methods())
6536 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006537
6538 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6539}
6540
6541void ASTReader::PassInterestingDeclsToConsumer() {
6542 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006543
6544 if (PassingDeclsToConsumer)
6545 return;
6546
6547 // Guard variable to avoid recursively redoing the process of passing
6548 // decls to consumer.
6549 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6550 true);
6551
Richard Smith9e2341d2015-03-23 03:25:59 +00006552 // Ensure that we've loaded all potentially-interesting declarations
6553 // that need to be eagerly loaded.
6554 for (auto ID : EagerlyDeserializedDecls)
6555 GetDecl(ID);
6556 EagerlyDeserializedDecls.clear();
6557
Guy Benyei11169dd2012-12-18 14:30:41 +00006558 while (!InterestingDecls.empty()) {
6559 Decl *D = InterestingDecls.front();
6560 InterestingDecls.pop_front();
6561
6562 PassInterestingDeclToConsumer(D);
6563 }
6564}
6565
6566void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6567 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6568 PassObjCImplDeclToConsumer(ImplD, Consumer);
6569 else
6570 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6571}
6572
6573void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6574 this->Consumer = Consumer;
6575
Richard Smith9e2341d2015-03-23 03:25:59 +00006576 if (Consumer)
6577 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006578
6579 if (DeserializationListener)
6580 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006581}
6582
6583void ASTReader::PrintStats() {
6584 std::fprintf(stderr, "*** AST File Statistics:\n");
6585
6586 unsigned NumTypesLoaded
6587 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6588 QualType());
6589 unsigned NumDeclsLoaded
6590 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006591 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 unsigned NumIdentifiersLoaded
6593 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6594 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006595 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 unsigned NumMacrosLoaded
6597 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6598 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006599 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 unsigned NumSelectorsLoaded
6601 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6602 SelectorsLoaded.end(),
6603 Selector());
6604
6605 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6606 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6607 NumSLocEntriesRead, TotalNumSLocEntries,
6608 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6609 if (!TypesLoaded.empty())
6610 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6611 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6612 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6613 if (!DeclsLoaded.empty())
6614 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6615 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6616 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6617 if (!IdentifiersLoaded.empty())
6618 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6619 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6620 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6621 if (!MacrosLoaded.empty())
6622 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6623 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6624 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6625 if (!SelectorsLoaded.empty())
6626 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6627 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6628 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6629 if (TotalNumStatements)
6630 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6631 NumStatementsRead, TotalNumStatements,
6632 ((float)NumStatementsRead/TotalNumStatements * 100));
6633 if (TotalNumMacros)
6634 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6635 NumMacrosRead, TotalNumMacros,
6636 ((float)NumMacrosRead/TotalNumMacros * 100));
6637 if (TotalLexicalDeclContexts)
6638 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6639 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6640 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6641 * 100));
6642 if (TotalVisibleDeclContexts)
6643 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6644 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6645 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6646 * 100));
6647 if (TotalNumMethodPoolEntries) {
6648 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6649 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6650 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6651 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006652 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006653 if (NumMethodPoolLookups) {
6654 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6655 NumMethodPoolHits, NumMethodPoolLookups,
6656 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6657 }
6658 if (NumMethodPoolTableLookups) {
6659 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6660 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6661 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6662 * 100.0));
6663 }
6664
Douglas Gregor00a50f72013-01-25 00:38:33 +00006665 if (NumIdentifierLookupHits) {
6666 std::fprintf(stderr,
6667 " %u / %u identifier table lookups succeeded (%f%%)\n",
6668 NumIdentifierLookupHits, NumIdentifierLookups,
6669 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6670 }
6671
Douglas Gregore060e572013-01-25 01:03:03 +00006672 if (GlobalIndex) {
6673 std::fprintf(stderr, "\n");
6674 GlobalIndex->printStats();
6675 }
6676
Guy Benyei11169dd2012-12-18 14:30:41 +00006677 std::fprintf(stderr, "\n");
6678 dump();
6679 std::fprintf(stderr, "\n");
6680}
6681
6682template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6683static void
6684dumpModuleIDMap(StringRef Name,
6685 const ContinuousRangeMap<Key, ModuleFile *,
6686 InitialCapacity> &Map) {
6687 if (Map.begin() == Map.end())
6688 return;
6689
6690 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6691 llvm::errs() << Name << ":\n";
6692 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6693 I != IEnd; ++I) {
6694 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6695 << "\n";
6696 }
6697}
6698
6699void ASTReader::dump() {
6700 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6701 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6702 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6703 dumpModuleIDMap("Global type map", GlobalTypeMap);
6704 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6705 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6706 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6707 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6708 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6709 dumpModuleIDMap("Global preprocessed entity map",
6710 GlobalPreprocessedEntityMap);
6711
6712 llvm::errs() << "\n*** PCH/Modules Loaded:";
6713 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6714 MEnd = ModuleMgr.end();
6715 M != MEnd; ++M)
6716 (*M)->dump();
6717}
6718
6719/// Return the amount of memory used by memory buffers, breaking down
6720/// by heap-backed versus mmap'ed memory.
6721void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6722 for (ModuleConstIterator I = ModuleMgr.begin(),
6723 E = ModuleMgr.end(); I != E; ++I) {
6724 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6725 size_t bytes = buf->getBufferSize();
6726 switch (buf->getBufferKind()) {
6727 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6728 sizes.malloc_bytes += bytes;
6729 break;
6730 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6731 sizes.mmap_bytes += bytes;
6732 break;
6733 }
6734 }
6735 }
6736}
6737
6738void ASTReader::InitializeSema(Sema &S) {
6739 SemaObj = &S;
6740 S.addExternalSource(this);
6741
6742 // Makes sure any declarations that were deserialized "too early"
6743 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006744 for (uint64_t ID : PreloadedDeclIDs) {
6745 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6746 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006747 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006748 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006749
Richard Smith3d8e97e2013-10-18 06:54:39 +00006750 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 if (!FPPragmaOptions.empty()) {
6752 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6753 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6754 }
6755
Richard Smith3d8e97e2013-10-18 06:54:39 +00006756 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006757 if (!OpenCLExtensions.empty()) {
6758 unsigned I = 0;
6759#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6760#include "clang/Basic/OpenCLExtensions.def"
6761
6762 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6763 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006764
6765 UpdateSema();
6766}
6767
6768void ASTReader::UpdateSema() {
6769 assert(SemaObj && "no Sema to update");
6770
6771 // Load the offsets of the declarations that Sema references.
6772 // They will be lazily deserialized when needed.
6773 if (!SemaDeclRefs.empty()) {
6774 assert(SemaDeclRefs.size() % 2 == 0);
6775 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6776 if (!SemaObj->StdNamespace)
6777 SemaObj->StdNamespace = SemaDeclRefs[I];
6778 if (!SemaObj->StdBadAlloc)
6779 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6780 }
6781 SemaDeclRefs.clear();
6782 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006783
6784 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6785 // encountered the pragma in the source.
6786 if(OptimizeOffPragmaLocation.isValid())
6787 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006788}
6789
6790IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6791 // Note that we are loading an identifier.
6792 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006793 StringRef Name(NameStart, NameEnd - NameStart);
6794
6795 // If there is a global index, look there first to determine which modules
6796 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006797 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006798 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006799 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006800 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6801 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006802 }
6803 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006804 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006805 NumIdentifierLookups,
6806 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006807 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 IdentifierInfo *II = Visitor.getIdentifierInfo();
6809 markIdentifierUpToDate(II);
6810 return II;
6811}
6812
6813namespace clang {
6814 /// \brief An identifier-lookup iterator that enumerates all of the
6815 /// identifiers stored within a set of AST files.
6816 class ASTIdentifierIterator : public IdentifierIterator {
6817 /// \brief The AST reader whose identifiers are being enumerated.
6818 const ASTReader &Reader;
6819
6820 /// \brief The current index into the chain of AST files stored in
6821 /// the AST reader.
6822 unsigned Index;
6823
6824 /// \brief The current position within the identifier lookup table
6825 /// of the current AST file.
6826 ASTIdentifierLookupTable::key_iterator Current;
6827
6828 /// \brief The end position within the identifier lookup table of
6829 /// the current AST file.
6830 ASTIdentifierLookupTable::key_iterator End;
6831
6832 public:
6833 explicit ASTIdentifierIterator(const ASTReader &Reader);
6834
Craig Topper3e89dfe2014-03-13 02:13:41 +00006835 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 };
6837}
6838
6839ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6840 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6841 ASTIdentifierLookupTable *IdTable
6842 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6843 Current = IdTable->key_begin();
6844 End = IdTable->key_end();
6845}
6846
6847StringRef ASTIdentifierIterator::Next() {
6848 while (Current == End) {
6849 // If we have exhausted all of our AST files, we're done.
6850 if (Index == 0)
6851 return StringRef();
6852
6853 --Index;
6854 ASTIdentifierLookupTable *IdTable
6855 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6856 IdentifierLookupTable;
6857 Current = IdTable->key_begin();
6858 End = IdTable->key_end();
6859 }
6860
6861 // We have any identifiers remaining in the current AST file; return
6862 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006863 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006865 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006866}
6867
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006868IdentifierIterator *ASTReader::getIdentifiers() {
6869 if (!loadGlobalIndex())
6870 return GlobalIndex->createIdentifierIterator();
6871
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 return new ASTIdentifierIterator(*this);
6873}
6874
6875namespace clang { namespace serialization {
6876 class ReadMethodPoolVisitor {
6877 ASTReader &Reader;
6878 Selector Sel;
6879 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006880 unsigned InstanceBits;
6881 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006882 bool InstanceHasMoreThanOneDecl;
6883 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006884 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6885 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006886
6887 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006888 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006890 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006891 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6892 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006893
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 static bool visit(ModuleFile &M, void *UserData) {
6895 ReadMethodPoolVisitor *This
6896 = static_cast<ReadMethodPoolVisitor *>(UserData);
6897
6898 if (!M.SelectorLookupTable)
6899 return false;
6900
6901 // If we've already searched this module file, skip it now.
6902 if (M.Generation <= This->PriorGeneration)
6903 return true;
6904
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006905 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006906 ASTSelectorLookupTable *PoolTable
6907 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6908 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6909 if (Pos == PoolTable->end())
6910 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006911
6912 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006913 ++This->Reader.NumSelectorsRead;
6914 // FIXME: Not quite happy with the statistics here. We probably should
6915 // disable this tracking when called via LoadSelector.
6916 // Also, should entries without methods count as misses?
6917 ++This->Reader.NumMethodPoolEntriesRead;
6918 ASTSelectorLookupTrait::data_type Data = *Pos;
6919 if (This->Reader.DeserializationListener)
6920 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6921 This->Sel);
6922
6923 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6924 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006925 This->InstanceBits = Data.InstanceBits;
6926 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006927 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6928 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 return true;
6930 }
6931
6932 /// \brief Retrieve the instance methods found by this visitor.
6933 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6934 return InstanceMethods;
6935 }
6936
6937 /// \brief Retrieve the instance methods found by this visitor.
6938 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6939 return FactoryMethods;
6940 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006941
6942 unsigned getInstanceBits() const { return InstanceBits; }
6943 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006944 bool instanceHasMoreThanOneDecl() const {
6945 return InstanceHasMoreThanOneDecl;
6946 }
6947 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 };
6949} } // end namespace clang::serialization
6950
6951/// \brief Add the given set of methods to the method list.
6952static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6953 ObjCMethodList &List) {
6954 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6955 S.addMethodToGlobalList(&List, Methods[I]);
6956 }
6957}
6958
6959void ASTReader::ReadMethodPool(Selector Sel) {
6960 // Get the selector generation and update it to the current generation.
6961 unsigned &Generation = SelectorGeneration[Sel];
6962 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006963 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006964
6965 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006966 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6968 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6969
6970 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006971 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006972 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006973
6974 ++NumMethodPoolHits;
6975
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 if (!getSema())
6977 return;
6978
6979 Sema &S = *getSema();
6980 Sema::GlobalMethodPool::iterator Pos
6981 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00006982
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006983 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006984 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006985 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006986 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00006987
6988 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
6989 // when building a module we keep every method individually and may need to
6990 // update hasMoreThanOneDecl as we add the methods.
6991 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6992 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00006993}
6994
6995void ASTReader::ReadKnownNamespaces(
6996 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6997 Namespaces.clear();
6998
6999 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7000 if (NamespaceDecl *Namespace
7001 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7002 Namespaces.push_back(Namespace);
7003 }
7004}
7005
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007006void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007007 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007008 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7009 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007010 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007011 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007012 Undefined.insert(std::make_pair(D, Loc));
7013 }
7014}
Nick Lewycky8334af82013-01-26 00:35:08 +00007015
Guy Benyei11169dd2012-12-18 14:30:41 +00007016void ASTReader::ReadTentativeDefinitions(
7017 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7018 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7019 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7020 if (Var)
7021 TentativeDefs.push_back(Var);
7022 }
7023 TentativeDefinitions.clear();
7024}
7025
7026void ASTReader::ReadUnusedFileScopedDecls(
7027 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7028 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7029 DeclaratorDecl *D
7030 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7031 if (D)
7032 Decls.push_back(D);
7033 }
7034 UnusedFileScopedDecls.clear();
7035}
7036
7037void ASTReader::ReadDelegatingConstructors(
7038 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7039 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7040 CXXConstructorDecl *D
7041 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7042 if (D)
7043 Decls.push_back(D);
7044 }
7045 DelegatingCtorDecls.clear();
7046}
7047
7048void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7049 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7050 TypedefNameDecl *D
7051 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7052 if (D)
7053 Decls.push_back(D);
7054 }
7055 ExtVectorDecls.clear();
7056}
7057
Nico Weber72889432014-09-06 01:25:55 +00007058void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7059 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7060 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7061 ++I) {
7062 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7063 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7064 if (D)
7065 Decls.insert(D);
7066 }
7067 UnusedLocalTypedefNameCandidates.clear();
7068}
7069
Guy Benyei11169dd2012-12-18 14:30:41 +00007070void ASTReader::ReadReferencedSelectors(
7071 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7072 if (ReferencedSelectorsData.empty())
7073 return;
7074
7075 // If there are @selector references added them to its pool. This is for
7076 // implementation of -Wselector.
7077 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7078 unsigned I = 0;
7079 while (I < DataSize) {
7080 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7081 SourceLocation SelLoc
7082 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7083 Sels.push_back(std::make_pair(Sel, SelLoc));
7084 }
7085 ReferencedSelectorsData.clear();
7086}
7087
7088void ASTReader::ReadWeakUndeclaredIdentifiers(
7089 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7090 if (WeakUndeclaredIdentifiers.empty())
7091 return;
7092
7093 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7094 IdentifierInfo *WeakId
7095 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7096 IdentifierInfo *AliasId
7097 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7098 SourceLocation Loc
7099 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7100 bool Used = WeakUndeclaredIdentifiers[I++];
7101 WeakInfo WI(AliasId, Loc);
7102 WI.setUsed(Used);
7103 WeakIDs.push_back(std::make_pair(WeakId, WI));
7104 }
7105 WeakUndeclaredIdentifiers.clear();
7106}
7107
7108void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7109 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7110 ExternalVTableUse VT;
7111 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7112 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7113 VT.DefinitionRequired = VTableUses[Idx++];
7114 VTables.push_back(VT);
7115 }
7116
7117 VTableUses.clear();
7118}
7119
7120void ASTReader::ReadPendingInstantiations(
7121 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7122 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7123 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7124 SourceLocation Loc
7125 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7126
7127 Pending.push_back(std::make_pair(D, Loc));
7128 }
7129 PendingInstantiations.clear();
7130}
7131
Richard Smithe40f2ba2013-08-07 21:41:30 +00007132void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007133 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007134 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7135 /* In loop */) {
7136 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7137
7138 LateParsedTemplate *LT = new LateParsedTemplate;
7139 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7140
7141 ModuleFile *F = getOwningModuleFile(LT->D);
7142 assert(F && "No module");
7143
7144 unsigned TokN = LateParsedTemplates[Idx++];
7145 LT->Toks.reserve(TokN);
7146 for (unsigned T = 0; T < TokN; ++T)
7147 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7148
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007149 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007150 }
7151
7152 LateParsedTemplates.clear();
7153}
7154
Guy Benyei11169dd2012-12-18 14:30:41 +00007155void ASTReader::LoadSelector(Selector Sel) {
7156 // It would be complicated to avoid reading the methods anyway. So don't.
7157 ReadMethodPool(Sel);
7158}
7159
7160void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7161 assert(ID && "Non-zero identifier ID required");
7162 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7163 IdentifiersLoaded[ID - 1] = II;
7164 if (DeserializationListener)
7165 DeserializationListener->IdentifierRead(ID, II);
7166}
7167
7168/// \brief Set the globally-visible declarations associated with the given
7169/// identifier.
7170///
7171/// If the AST reader is currently in a state where the given declaration IDs
7172/// cannot safely be resolved, they are queued until it is safe to resolve
7173/// them.
7174///
7175/// \param II an IdentifierInfo that refers to one or more globally-visible
7176/// declarations.
7177///
7178/// \param DeclIDs the set of declaration IDs with the name @p II that are
7179/// visible at global scope.
7180///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007181/// \param Decls if non-null, this vector will be populated with the set of
7182/// deserialized declarations. These declarations will not be pushed into
7183/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007184void
7185ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7186 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007187 SmallVectorImpl<Decl *> *Decls) {
7188 if (NumCurrentElementsDeserializing && !Decls) {
7189 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 return;
7191 }
7192
7193 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007194 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007195 // Queue this declaration so that it will be added to the
7196 // translation unit scope and identifier's declaration chain
7197 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007198 PreloadedDeclIDs.push_back(DeclIDs[I]);
7199 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007201
7202 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7203
7204 // If we're simply supposed to record the declarations, do so now.
7205 if (Decls) {
7206 Decls->push_back(D);
7207 continue;
7208 }
7209
7210 // Introduce this declaration into the translation-unit scope
7211 // and add it to the declaration chain for this identifier, so
7212 // that (unqualified) name lookup will find it.
7213 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 }
7215}
7216
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007217IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007218 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007219 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007220
7221 if (IdentifiersLoaded.empty()) {
7222 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007223 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 }
7225
7226 ID -= 1;
7227 if (!IdentifiersLoaded[ID]) {
7228 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7229 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7230 ModuleFile *M = I->second;
7231 unsigned Index = ID - M->BaseIdentifierID;
7232 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7233
7234 // All of the strings in the AST file are preceded by a 16-bit length.
7235 // Extract that 16-bit length to avoid having to execute strlen().
7236 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7237 // unsigned integers. This is important to avoid integer overflow when
7238 // we cast them to 'unsigned'.
7239 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7240 unsigned StrLen = (((unsigned) StrLenPtr[0])
7241 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007242 IdentifiersLoaded[ID]
7243 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 if (DeserializationListener)
7245 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7246 }
7247
7248 return IdentifiersLoaded[ID];
7249}
7250
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007251IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7252 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007253}
7254
7255IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7256 if (LocalID < NUM_PREDEF_IDENT_IDS)
7257 return LocalID;
7258
7259 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7260 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7261 assert(I != M.IdentifierRemap.end()
7262 && "Invalid index into identifier index remap");
7263
7264 return LocalID + I->second;
7265}
7266
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007267MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007269 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007270
7271 if (MacrosLoaded.empty()) {
7272 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007273 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 }
7275
7276 ID -= NUM_PREDEF_MACRO_IDS;
7277 if (!MacrosLoaded[ID]) {
7278 GlobalMacroMapType::iterator I
7279 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7280 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7281 ModuleFile *M = I->second;
7282 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007283 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7284
7285 if (DeserializationListener)
7286 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7287 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 }
7289
7290 return MacrosLoaded[ID];
7291}
7292
7293MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7294 if (LocalID < NUM_PREDEF_MACRO_IDS)
7295 return LocalID;
7296
7297 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7298 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7299 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7300
7301 return LocalID + I->second;
7302}
7303
7304serialization::SubmoduleID
7305ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7306 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7307 return LocalID;
7308
7309 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7310 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7311 assert(I != M.SubmoduleRemap.end()
7312 && "Invalid index into submodule index remap");
7313
7314 return LocalID + I->second;
7315}
7316
7317Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7318 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7319 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007320 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007321 }
7322
7323 if (GlobalID > SubmodulesLoaded.size()) {
7324 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007325 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 }
7327
7328 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7329}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007330
7331Module *ASTReader::getModule(unsigned ID) {
7332 return getSubmodule(ID);
7333}
7334
Guy Benyei11169dd2012-12-18 14:30:41 +00007335Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7336 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7337}
7338
7339Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7340 if (ID == 0)
7341 return Selector();
7342
7343 if (ID > SelectorsLoaded.size()) {
7344 Error("selector ID out of range in AST file");
7345 return Selector();
7346 }
7347
Craig Toppera13603a2014-05-22 05:54:18 +00007348 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007349 // Load this selector from the selector table.
7350 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7351 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7352 ModuleFile &M = *I->second;
7353 ASTSelectorLookupTrait Trait(*this, M);
7354 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7355 SelectorsLoaded[ID - 1] =
7356 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7357 if (DeserializationListener)
7358 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7359 }
7360
7361 return SelectorsLoaded[ID - 1];
7362}
7363
7364Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7365 return DecodeSelector(ID);
7366}
7367
7368uint32_t ASTReader::GetNumExternalSelectors() {
7369 // ID 0 (the null selector) is considered an external selector.
7370 return getTotalNumSelectors() + 1;
7371}
7372
7373serialization::SelectorID
7374ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7375 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7376 return LocalID;
7377
7378 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7379 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7380 assert(I != M.SelectorRemap.end()
7381 && "Invalid index into selector index remap");
7382
7383 return LocalID + I->second;
7384}
7385
7386DeclarationName
7387ASTReader::ReadDeclarationName(ModuleFile &F,
7388 const RecordData &Record, unsigned &Idx) {
7389 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7390 switch (Kind) {
7391 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007392 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007393
7394 case DeclarationName::ObjCZeroArgSelector:
7395 case DeclarationName::ObjCOneArgSelector:
7396 case DeclarationName::ObjCMultiArgSelector:
7397 return DeclarationName(ReadSelector(F, Record, Idx));
7398
7399 case DeclarationName::CXXConstructorName:
7400 return Context.DeclarationNames.getCXXConstructorName(
7401 Context.getCanonicalType(readType(F, Record, Idx)));
7402
7403 case DeclarationName::CXXDestructorName:
7404 return Context.DeclarationNames.getCXXDestructorName(
7405 Context.getCanonicalType(readType(F, Record, Idx)));
7406
7407 case DeclarationName::CXXConversionFunctionName:
7408 return Context.DeclarationNames.getCXXConversionFunctionName(
7409 Context.getCanonicalType(readType(F, Record, Idx)));
7410
7411 case DeclarationName::CXXOperatorName:
7412 return Context.DeclarationNames.getCXXOperatorName(
7413 (OverloadedOperatorKind)Record[Idx++]);
7414
7415 case DeclarationName::CXXLiteralOperatorName:
7416 return Context.DeclarationNames.getCXXLiteralOperatorName(
7417 GetIdentifierInfo(F, Record, Idx));
7418
7419 case DeclarationName::CXXUsingDirective:
7420 return DeclarationName::getUsingDirectiveName();
7421 }
7422
7423 llvm_unreachable("Invalid NameKind!");
7424}
7425
7426void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7427 DeclarationNameLoc &DNLoc,
7428 DeclarationName Name,
7429 const RecordData &Record, unsigned &Idx) {
7430 switch (Name.getNameKind()) {
7431 case DeclarationName::CXXConstructorName:
7432 case DeclarationName::CXXDestructorName:
7433 case DeclarationName::CXXConversionFunctionName:
7434 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7435 break;
7436
7437 case DeclarationName::CXXOperatorName:
7438 DNLoc.CXXOperatorName.BeginOpNameLoc
7439 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7440 DNLoc.CXXOperatorName.EndOpNameLoc
7441 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7442 break;
7443
7444 case DeclarationName::CXXLiteralOperatorName:
7445 DNLoc.CXXLiteralOperatorName.OpNameLoc
7446 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7447 break;
7448
7449 case DeclarationName::Identifier:
7450 case DeclarationName::ObjCZeroArgSelector:
7451 case DeclarationName::ObjCOneArgSelector:
7452 case DeclarationName::ObjCMultiArgSelector:
7453 case DeclarationName::CXXUsingDirective:
7454 break;
7455 }
7456}
7457
7458void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7459 DeclarationNameInfo &NameInfo,
7460 const RecordData &Record, unsigned &Idx) {
7461 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7462 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7463 DeclarationNameLoc DNLoc;
7464 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7465 NameInfo.setInfo(DNLoc);
7466}
7467
7468void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7469 const RecordData &Record, unsigned &Idx) {
7470 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7471 unsigned NumTPLists = Record[Idx++];
7472 Info.NumTemplParamLists = NumTPLists;
7473 if (NumTPLists) {
7474 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7475 for (unsigned i=0; i != NumTPLists; ++i)
7476 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7477 }
7478}
7479
7480TemplateName
7481ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7482 unsigned &Idx) {
7483 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7484 switch (Kind) {
7485 case TemplateName::Template:
7486 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7487
7488 case TemplateName::OverloadedTemplate: {
7489 unsigned size = Record[Idx++];
7490 UnresolvedSet<8> Decls;
7491 while (size--)
7492 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7493
7494 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7495 }
7496
7497 case TemplateName::QualifiedTemplate: {
7498 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7499 bool hasTemplKeyword = Record[Idx++];
7500 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7501 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7502 }
7503
7504 case TemplateName::DependentTemplate: {
7505 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7506 if (Record[Idx++]) // isIdentifier
7507 return Context.getDependentTemplateName(NNS,
7508 GetIdentifierInfo(F, Record,
7509 Idx));
7510 return Context.getDependentTemplateName(NNS,
7511 (OverloadedOperatorKind)Record[Idx++]);
7512 }
7513
7514 case TemplateName::SubstTemplateTemplateParm: {
7515 TemplateTemplateParmDecl *param
7516 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7517 if (!param) return TemplateName();
7518 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7519 return Context.getSubstTemplateTemplateParm(param, replacement);
7520 }
7521
7522 case TemplateName::SubstTemplateTemplateParmPack: {
7523 TemplateTemplateParmDecl *Param
7524 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7525 if (!Param)
7526 return TemplateName();
7527
7528 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7529 if (ArgPack.getKind() != TemplateArgument::Pack)
7530 return TemplateName();
7531
7532 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7533 }
7534 }
7535
7536 llvm_unreachable("Unhandled template name kind!");
7537}
7538
7539TemplateArgument
7540ASTReader::ReadTemplateArgument(ModuleFile &F,
7541 const RecordData &Record, unsigned &Idx) {
7542 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7543 switch (Kind) {
7544 case TemplateArgument::Null:
7545 return TemplateArgument();
7546 case TemplateArgument::Type:
7547 return TemplateArgument(readType(F, Record, Idx));
7548 case TemplateArgument::Declaration: {
7549 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007550 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007551 }
7552 case TemplateArgument::NullPtr:
7553 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7554 case TemplateArgument::Integral: {
7555 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7556 QualType T = readType(F, Record, Idx);
7557 return TemplateArgument(Context, Value, T);
7558 }
7559 case TemplateArgument::Template:
7560 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7561 case TemplateArgument::TemplateExpansion: {
7562 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007563 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 if (unsigned NumExpansions = Record[Idx++])
7565 NumTemplateExpansions = NumExpansions - 1;
7566 return TemplateArgument(Name, NumTemplateExpansions);
7567 }
7568 case TemplateArgument::Expression:
7569 return TemplateArgument(ReadExpr(F));
7570 case TemplateArgument::Pack: {
7571 unsigned NumArgs = Record[Idx++];
7572 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7573 for (unsigned I = 0; I != NumArgs; ++I)
7574 Args[I] = ReadTemplateArgument(F, Record, Idx);
7575 return TemplateArgument(Args, NumArgs);
7576 }
7577 }
7578
7579 llvm_unreachable("Unhandled template argument kind!");
7580}
7581
7582TemplateParameterList *
7583ASTReader::ReadTemplateParameterList(ModuleFile &F,
7584 const RecordData &Record, unsigned &Idx) {
7585 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7586 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7587 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7588
7589 unsigned NumParams = Record[Idx++];
7590 SmallVector<NamedDecl *, 16> Params;
7591 Params.reserve(NumParams);
7592 while (NumParams--)
7593 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7594
7595 TemplateParameterList* TemplateParams =
7596 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7597 Params.data(), Params.size(), RAngleLoc);
7598 return TemplateParams;
7599}
7600
7601void
7602ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007603ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 ModuleFile &F, const RecordData &Record,
7605 unsigned &Idx) {
7606 unsigned NumTemplateArgs = Record[Idx++];
7607 TemplArgs.reserve(NumTemplateArgs);
7608 while (NumTemplateArgs--)
7609 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7610}
7611
7612/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007613void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007614 const RecordData &Record, unsigned &Idx) {
7615 unsigned NumDecls = Record[Idx++];
7616 Set.reserve(Context, NumDecls);
7617 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007618 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007620 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 }
7622}
7623
7624CXXBaseSpecifier
7625ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7626 const RecordData &Record, unsigned &Idx) {
7627 bool isVirtual = static_cast<bool>(Record[Idx++]);
7628 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7629 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7630 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7631 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7632 SourceRange Range = ReadSourceRange(F, Record, Idx);
7633 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7634 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7635 EllipsisLoc);
7636 Result.setInheritConstructors(inheritConstructors);
7637 return Result;
7638}
7639
Richard Smithc2bb8182015-03-24 06:36:48 +00007640CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007641ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7642 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007644 assert(NumInitializers && "wrote ctor initializers but have no inits");
7645 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7646 for (unsigned i = 0; i != NumInitializers; ++i) {
7647 TypeSourceInfo *TInfo = nullptr;
7648 bool IsBaseVirtual = false;
7649 FieldDecl *Member = nullptr;
7650 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007651
Richard Smithc2bb8182015-03-24 06:36:48 +00007652 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7653 switch (Type) {
7654 case CTOR_INITIALIZER_BASE:
7655 TInfo = GetTypeSourceInfo(F, Record, Idx);
7656 IsBaseVirtual = Record[Idx++];
7657 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007658
Richard Smithc2bb8182015-03-24 06:36:48 +00007659 case CTOR_INITIALIZER_DELEGATING:
7660 TInfo = GetTypeSourceInfo(F, Record, Idx);
7661 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007662
Richard Smithc2bb8182015-03-24 06:36:48 +00007663 case CTOR_INITIALIZER_MEMBER:
7664 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7665 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666
Richard Smithc2bb8182015-03-24 06:36:48 +00007667 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7668 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7669 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007670 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007671
7672 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7673 Expr *Init = ReadExpr(F);
7674 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7675 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7676 bool IsWritten = Record[Idx++];
7677 unsigned SourceOrderOrNumArrayIndices;
7678 SmallVector<VarDecl *, 8> Indices;
7679 if (IsWritten) {
7680 SourceOrderOrNumArrayIndices = Record[Idx++];
7681 } else {
7682 SourceOrderOrNumArrayIndices = Record[Idx++];
7683 Indices.reserve(SourceOrderOrNumArrayIndices);
7684 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7685 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7686 }
7687
7688 CXXCtorInitializer *BOMInit;
7689 if (Type == CTOR_INITIALIZER_BASE) {
7690 BOMInit = new (Context)
7691 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7692 RParenLoc, MemberOrEllipsisLoc);
7693 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7694 BOMInit = new (Context)
7695 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7696 } else if (IsWritten) {
7697 if (Member)
7698 BOMInit = new (Context) CXXCtorInitializer(
7699 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7700 else
7701 BOMInit = new (Context)
7702 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7703 LParenLoc, Init, RParenLoc);
7704 } else {
7705 if (IndirectMember) {
7706 assert(Indices.empty() && "Indirect field improperly initialized");
7707 BOMInit = new (Context)
7708 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7709 LParenLoc, Init, RParenLoc);
7710 } else {
7711 BOMInit = CXXCtorInitializer::Create(
7712 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7713 Indices.data(), Indices.size());
7714 }
7715 }
7716
7717 if (IsWritten)
7718 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7719 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 }
7721
Richard Smithc2bb8182015-03-24 06:36:48 +00007722 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007723}
7724
7725NestedNameSpecifier *
7726ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7727 const RecordData &Record, unsigned &Idx) {
7728 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007729 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 for (unsigned I = 0; I != N; ++I) {
7731 NestedNameSpecifier::SpecifierKind Kind
7732 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7733 switch (Kind) {
7734 case NestedNameSpecifier::Identifier: {
7735 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7736 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7737 break;
7738 }
7739
7740 case NestedNameSpecifier::Namespace: {
7741 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7742 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7743 break;
7744 }
7745
7746 case NestedNameSpecifier::NamespaceAlias: {
7747 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7748 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7749 break;
7750 }
7751
7752 case NestedNameSpecifier::TypeSpec:
7753 case NestedNameSpecifier::TypeSpecWithTemplate: {
7754 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7755 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007756 return nullptr;
7757
Guy Benyei11169dd2012-12-18 14:30:41 +00007758 bool Template = Record[Idx++];
7759 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7760 break;
7761 }
7762
7763 case NestedNameSpecifier::Global: {
7764 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7765 // No associated value, and there can't be a prefix.
7766 break;
7767 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007768
7769 case NestedNameSpecifier::Super: {
7770 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7771 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7772 break;
7773 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007774 }
7775 Prev = NNS;
7776 }
7777 return NNS;
7778}
7779
7780NestedNameSpecifierLoc
7781ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7782 unsigned &Idx) {
7783 unsigned N = Record[Idx++];
7784 NestedNameSpecifierLocBuilder Builder;
7785 for (unsigned I = 0; I != N; ++I) {
7786 NestedNameSpecifier::SpecifierKind Kind
7787 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7788 switch (Kind) {
7789 case NestedNameSpecifier::Identifier: {
7790 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7791 SourceRange Range = ReadSourceRange(F, Record, Idx);
7792 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7793 break;
7794 }
7795
7796 case NestedNameSpecifier::Namespace: {
7797 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7798 SourceRange Range = ReadSourceRange(F, Record, Idx);
7799 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7800 break;
7801 }
7802
7803 case NestedNameSpecifier::NamespaceAlias: {
7804 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7805 SourceRange Range = ReadSourceRange(F, Record, Idx);
7806 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7807 break;
7808 }
7809
7810 case NestedNameSpecifier::TypeSpec:
7811 case NestedNameSpecifier::TypeSpecWithTemplate: {
7812 bool Template = Record[Idx++];
7813 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7814 if (!T)
7815 return NestedNameSpecifierLoc();
7816 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7817
7818 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7819 Builder.Extend(Context,
7820 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7821 T->getTypeLoc(), ColonColonLoc);
7822 break;
7823 }
7824
7825 case NestedNameSpecifier::Global: {
7826 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7827 Builder.MakeGlobal(Context, ColonColonLoc);
7828 break;
7829 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007830
7831 case NestedNameSpecifier::Super: {
7832 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7833 SourceRange Range = ReadSourceRange(F, Record, Idx);
7834 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7835 break;
7836 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 }
7838 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007839
Guy Benyei11169dd2012-12-18 14:30:41 +00007840 return Builder.getWithLocInContext(Context);
7841}
7842
7843SourceRange
7844ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7845 unsigned &Idx) {
7846 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7847 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7848 return SourceRange(beg, end);
7849}
7850
7851/// \brief Read an integral value
7852llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7853 unsigned BitWidth = Record[Idx++];
7854 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7855 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7856 Idx += NumWords;
7857 return Result;
7858}
7859
7860/// \brief Read a signed integral value
7861llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7862 bool isUnsigned = Record[Idx++];
7863 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7864}
7865
7866/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007867llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7868 const llvm::fltSemantics &Sem,
7869 unsigned &Idx) {
7870 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007871}
7872
7873// \brief Read a string
7874std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7875 unsigned Len = Record[Idx++];
7876 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7877 Idx += Len;
7878 return Result;
7879}
7880
Richard Smith7ed1bc92014-12-05 22:42:13 +00007881std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7882 unsigned &Idx) {
7883 std::string Filename = ReadString(Record, Idx);
7884 ResolveImportedPath(F, Filename);
7885 return Filename;
7886}
7887
Guy Benyei11169dd2012-12-18 14:30:41 +00007888VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7889 unsigned &Idx) {
7890 unsigned Major = Record[Idx++];
7891 unsigned Minor = Record[Idx++];
7892 unsigned Subminor = Record[Idx++];
7893 if (Minor == 0)
7894 return VersionTuple(Major);
7895 if (Subminor == 0)
7896 return VersionTuple(Major, Minor - 1);
7897 return VersionTuple(Major, Minor - 1, Subminor - 1);
7898}
7899
7900CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7901 const RecordData &Record,
7902 unsigned &Idx) {
7903 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7904 return CXXTemporary::Create(Context, Decl);
7905}
7906
7907DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007908 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007909}
7910
7911DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7912 return Diags.Report(Loc, DiagID);
7913}
7914
7915/// \brief Retrieve the identifier table associated with the
7916/// preprocessor.
7917IdentifierTable &ASTReader::getIdentifierTable() {
7918 return PP.getIdentifierTable();
7919}
7920
7921/// \brief Record that the given ID maps to the given switch-case
7922/// statement.
7923void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007924 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007925 "Already have a SwitchCase with this ID");
7926 (*CurrSwitchCaseStmts)[ID] = SC;
7927}
7928
7929/// \brief Retrieve the switch-case statement with the given ID.
7930SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007931 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007932 return (*CurrSwitchCaseStmts)[ID];
7933}
7934
7935void ASTReader::ClearSwitchCaseIDs() {
7936 CurrSwitchCaseStmts->clear();
7937}
7938
7939void ASTReader::ReadComments() {
7940 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007941 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 serialization::ModuleFile *> >::iterator
7943 I = CommentsCursors.begin(),
7944 E = CommentsCursors.end();
7945 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007946 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007947 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007948 serialization::ModuleFile &F = *I->second;
7949 SavedStreamPosition SavedPosition(Cursor);
7950
7951 RecordData Record;
7952 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007953 llvm::BitstreamEntry Entry =
7954 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007955
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007956 switch (Entry.Kind) {
7957 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7958 case llvm::BitstreamEntry::Error:
7959 Error("malformed block record in AST file");
7960 return;
7961 case llvm::BitstreamEntry::EndBlock:
7962 goto NextCursor;
7963 case llvm::BitstreamEntry::Record:
7964 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 }
7967
7968 // Read a record.
7969 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007970 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 case COMMENTS_RAW_COMMENT: {
7972 unsigned Idx = 0;
7973 SourceRange SR = ReadSourceRange(F, Record, Idx);
7974 RawComment::CommentKind Kind =
7975 (RawComment::CommentKind) Record[Idx++];
7976 bool IsTrailingComment = Record[Idx++];
7977 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007978 Comments.push_back(new (Context) RawComment(
7979 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7980 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 break;
7982 }
7983 }
7984 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007985 NextCursor:
7986 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007988}
7989
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00007990void ASTReader::getInputFiles(ModuleFile &F,
7991 SmallVectorImpl<serialization::InputFile> &Files) {
7992 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
7993 unsigned ID = I+1;
7994 Files.push_back(getInputFile(F, ID));
7995 }
7996}
7997
Richard Smithcd45dbc2014-04-19 03:48:30 +00007998std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7999 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008000 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008001 return M->getFullModuleName();
8002
8003 // Otherwise, use the name of the top-level module the decl is within.
8004 if (ModuleFile *M = getOwningModuleFile(D))
8005 return M->ModuleName;
8006
8007 // Not from a module.
8008 return "";
8009}
8010
Guy Benyei11169dd2012-12-18 14:30:41 +00008011void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008012 while (!PendingIdentifierInfos.empty() ||
8013 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008014 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008015 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 // If any identifiers with corresponding top-level declarations have
8017 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008018 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8019 TopLevelDeclsMap;
8020 TopLevelDeclsMap TopLevelDecls;
8021
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008023 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008024 SmallVector<uint32_t, 4> DeclIDs =
8025 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008026 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008027
8028 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008030
Richard Smith851072e2014-05-19 20:59:20 +00008031 // For each decl chain that we wanted to complete while deserializing, mark
8032 // it as "still needs to be completed".
8033 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8034 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8035 }
8036 PendingIncompleteDeclChains.clear();
8037
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008039 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008040 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008041 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008042 }
8043 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 PendingDeclChains.clear();
8045
Douglas Gregor6168bd22013-02-18 15:53:43 +00008046 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008047 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8048 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008049 IdentifierInfo *II = TLD->first;
8050 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008051 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008052 }
8053 }
8054
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 // Load any pending macro definitions.
8056 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008057 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8058 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8059 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8060 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008061 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008062 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008063 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008064 if (Info.M->Kind != MK_ImplicitModule &&
8065 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008066 resolvePendingMacro(II, Info);
8067 }
8068 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008069 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008070 ++IDIdx) {
8071 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008072 if (Info.M->Kind == MK_ImplicitModule ||
8073 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008074 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 }
8076 }
8077 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008078
8079 // Wire up the DeclContexts for Decls that we delayed setting until
8080 // recursive loading is completed.
8081 while (!PendingDeclContextInfos.empty()) {
8082 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8083 PendingDeclContextInfos.pop_front();
8084 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8085 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8086 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8087 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008088
Richard Smithd1c46742014-04-30 02:24:17 +00008089 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008090 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008091 auto Update = PendingUpdateRecords.pop_back_val();
8092 ReadingKindTracker ReadingKind(Read_Decl, *this);
8093 loadDeclUpdateRecords(Update.first, Update.second);
8094 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 }
Richard Smith8a639892015-01-24 01:07:20 +00008096
8097 // At this point, all update records for loaded decls are in place, so any
8098 // fake class definitions should have become real.
8099 assert(PendingFakeDefinitionData.empty() &&
8100 "faked up a class definition but never saw the real one");
8101
Guy Benyei11169dd2012-12-18 14:30:41 +00008102 // If we deserialized any C++ or Objective-C class definitions, any
8103 // Objective-C protocol definitions, or any redeclarable templates, make sure
8104 // that all redeclarations point to the definitions. Note that this can only
8105 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008106 for (Decl *D : PendingDefinitions) {
8107 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008108 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 // Make sure that the TagType points at the definition.
8110 const_cast<TagType*>(TagT)->decl = TD;
8111 }
Richard Smith8ce51082015-03-11 01:44:51 +00008112
Craig Topperc6914d02014-08-25 04:15:02 +00008113 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008114 for (auto *R = getMostRecentExistingDecl(RD); R;
8115 R = R->getPreviousDecl()) {
8116 assert((R == D) ==
8117 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008118 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008119 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 }
8122
8123 continue;
8124 }
Richard Smith8ce51082015-03-11 01:44:51 +00008125
Craig Topperc6914d02014-08-25 04:15:02 +00008126 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008127 // Make sure that the ObjCInterfaceType points at the definition.
8128 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8129 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008130
8131 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8132 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8133
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 continue;
8135 }
Richard Smith8ce51082015-03-11 01:44:51 +00008136
Craig Topperc6914d02014-08-25 04:15:02 +00008137 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008138 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8139 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 continue;
8142 }
Richard Smith8ce51082015-03-11 01:44:51 +00008143
Craig Topperc6914d02014-08-25 04:15:02 +00008144 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008145 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8146 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 }
8148 PendingDefinitions.clear();
8149
8150 // Load the bodies of any functions or methods we've encountered. We do
8151 // this now (delayed) so that we can be sure that the declaration chains
8152 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008153 // FIXME: There seems to be no point in delaying this, it does not depend
8154 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8156 PBEnd = PendingBodies.end();
8157 PB != PBEnd; ++PB) {
8158 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8159 // FIXME: Check for =delete/=default?
8160 // FIXME: Complain about ODR violations here?
8161 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8162 FD->setLazyBody(PB->second);
8163 continue;
8164 }
8165
8166 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8167 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8168 MD->setLazyBody(PB->second);
8169 }
8170 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008171
8172 // Do some cleanup.
8173 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8174 getContext().deduplicateMergedDefinitonsFor(ND);
8175 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008176}
8177
8178void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008179 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8180 return;
8181
Richard Smitha0ce9c42014-07-29 23:23:27 +00008182 // Trigger the import of the full definition of each class that had any
8183 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008184 // These updates may in turn find and diagnose some ODR failures, so take
8185 // ownership of the set first.
8186 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8187 PendingOdrMergeFailures.clear();
8188 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008189 Merge.first->buildLookup();
8190 Merge.first->decls_begin();
8191 Merge.first->bases_begin();
8192 Merge.first->vbases_begin();
8193 for (auto *RD : Merge.second) {
8194 RD->decls_begin();
8195 RD->bases_begin();
8196 RD->vbases_begin();
8197 }
8198 }
8199
8200 // For each declaration from a merged context, check that the canonical
8201 // definition of that context also contains a declaration of the same
8202 // entity.
8203 //
8204 // Caution: this loop does things that might invalidate iterators into
8205 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8206 while (!PendingOdrMergeChecks.empty()) {
8207 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8208
8209 // FIXME: Skip over implicit declarations for now. This matters for things
8210 // like implicitly-declared special member functions. This isn't entirely
8211 // correct; we can end up with multiple unmerged declarations of the same
8212 // implicit entity.
8213 if (D->isImplicit())
8214 continue;
8215
8216 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008217
8218 bool Found = false;
8219 const Decl *DCanon = D->getCanonicalDecl();
8220
Richard Smith01bdb7a2014-08-28 05:44:07 +00008221 for (auto RI : D->redecls()) {
8222 if (RI->getLexicalDeclContext() == CanonDef) {
8223 Found = true;
8224 break;
8225 }
8226 }
8227 if (Found)
8228 continue;
8229
Richard Smitha0ce9c42014-07-29 23:23:27 +00008230 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008231 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008232 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8233 !Found && I != E; ++I) {
8234 for (auto RI : (*I)->redecls()) {
8235 if (RI->getLexicalDeclContext() == CanonDef) {
8236 // This declaration is present in the canonical definition. If it's
8237 // in the same redecl chain, it's the one we're looking for.
8238 if (RI->getCanonicalDecl() == DCanon)
8239 Found = true;
8240 else
8241 Candidates.push_back(cast<NamedDecl>(RI));
8242 break;
8243 }
8244 }
8245 }
8246
8247 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008248 // The AST doesn't like TagDecls becoming invalid after they've been
8249 // completed. We only really need to mark FieldDecls as invalid here.
8250 if (!isa<TagDecl>(D))
8251 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008252
8253 // Ensure we don't accidentally recursively enter deserialization while
8254 // we're producing our diagnostic.
8255 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008256
8257 std::string CanonDefModule =
8258 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8259 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8260 << D << getOwningModuleNameForDiagnostic(D)
8261 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8262
8263 if (Candidates.empty())
8264 Diag(cast<Decl>(CanonDef)->getLocation(),
8265 diag::note_module_odr_violation_no_possible_decls) << D;
8266 else {
8267 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8268 Diag(Candidates[I]->getLocation(),
8269 diag::note_module_odr_violation_possible_decl)
8270 << Candidates[I];
8271 }
8272
8273 DiagnosedOdrMergeFailures.insert(CanonDef);
8274 }
8275 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008276
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008277 if (OdrMergeFailures.empty())
8278 return;
8279
8280 // Ensure we don't accidentally recursively enter deserialization while
8281 // we're producing our diagnostics.
8282 Deserializing RecursionGuard(this);
8283
Richard Smithcd45dbc2014-04-19 03:48:30 +00008284 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008285 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008286 // If we've already pointed out a specific problem with this class, don't
8287 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008288 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008289 continue;
8290
8291 bool Diagnosed = false;
8292 for (auto *RD : Merge.second) {
8293 // Multiple different declarations got merged together; tell the user
8294 // where they came from.
8295 if (Merge.first != RD) {
8296 // FIXME: Walk the definition, figure out what's different,
8297 // and diagnose that.
8298 if (!Diagnosed) {
8299 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8300 Diag(Merge.first->getLocation(),
8301 diag::err_module_odr_violation_different_definitions)
8302 << Merge.first << Module.empty() << Module;
8303 Diagnosed = true;
8304 }
8305
8306 Diag(RD->getLocation(),
8307 diag::note_module_odr_violation_different_definitions)
8308 << getOwningModuleNameForDiagnostic(RD);
8309 }
8310 }
8311
8312 if (!Diagnosed) {
8313 // All definitions are updates to the same declaration. This happens if a
8314 // module instantiates the declaration of a class template specialization
8315 // and two or more other modules instantiate its definition.
8316 //
8317 // FIXME: Indicate which modules had instantiations of this definition.
8318 // FIXME: How can this even happen?
8319 Diag(Merge.first->getLocation(),
8320 diag::err_module_odr_violation_different_instantiations)
8321 << Merge.first;
8322 }
8323 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008324}
8325
8326void ASTReader::FinishedDeserializing() {
8327 assert(NumCurrentElementsDeserializing &&
8328 "FinishedDeserializing not paired with StartedDeserializing");
8329 if (NumCurrentElementsDeserializing == 1) {
8330 // We decrease NumCurrentElementsDeserializing only after pending actions
8331 // are finished, to avoid recursively re-calling finishPendingActions().
8332 finishPendingActions();
8333 }
8334 --NumCurrentElementsDeserializing;
8335
Richard Smitha0ce9c42014-07-29 23:23:27 +00008336 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008337 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008338 while (!PendingExceptionSpecUpdates.empty()) {
8339 auto Updates = std::move(PendingExceptionSpecUpdates);
8340 PendingExceptionSpecUpdates.clear();
8341 for (auto Update : Updates) {
8342 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8343 SemaObj->UpdateExceptionSpec(Update.second,
8344 FPT->getExtProtoInfo().ExceptionSpec);
8345 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008346 }
8347
Richard Smitha0ce9c42014-07-29 23:23:27 +00008348 diagnoseOdrViolations();
8349
Richard Smith04d05b52014-03-23 00:27:18 +00008350 // We are not in recursive loading, so it's safe to pass the "interesting"
8351 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008352 if (Consumer)
8353 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
8355}
8356
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008357void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008358 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8359 // Remove any fake results before adding any real ones.
8360 auto It = PendingFakeLookupResults.find(II);
8361 if (It != PendingFakeLookupResults.end()) {
8362 for (auto *ND : PendingFakeLookupResults[II])
8363 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008364 // FIXME: this works around module+PCH performance issue.
8365 // Rather than erase the result from the map, which is O(n), just clear
8366 // the vector of NamedDecls.
8367 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008368 }
8369 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008370
8371 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8372 SemaObj->TUScope->AddDecl(D);
8373 } else if (SemaObj->TUScope) {
8374 // Adding the decl to IdResolver may have failed because it was already in
8375 // (even though it was not added in scope). If it is already in, make sure
8376 // it gets in the scope as well.
8377 if (std::find(SemaObj->IdResolver.begin(Name),
8378 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8379 SemaObj->TUScope->AddDecl(D);
8380 }
8381}
8382
Nico Weber824285e2014-05-08 04:26:47 +00008383ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8384 bool DisableValidation, bool AllowASTWithCompilerErrors,
8385 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008386 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008387 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008388 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008389 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8390 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8391 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8392 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008393 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8394 AllowConfigurationMismatch(AllowConfigurationMismatch),
8395 ValidateSystemInputs(ValidateSystemInputs),
8396 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008397 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008398 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8399 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8400 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8401 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8402 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8403 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8404 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8405 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8406 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008407 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 SourceMgr.setExternalSLocEntrySource(this);
8409}
8410
8411ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008412 if (OwnsDeserializationListener)
8413 delete DeserializationListener;
8414
Guy Benyei11169dd2012-12-18 14:30:41 +00008415 for (DeclContextVisibleUpdatesPending::iterator
8416 I = PendingVisibleUpdates.begin(),
8417 E = PendingVisibleUpdates.end();
8418 I != E; ++I) {
8419 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8420 F = I->second.end();
8421 J != F; ++J)
8422 delete J->first;
8423 }
8424}