blob: 7c211e41a1804f38887ab142dc6857aa390ec0d0 [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +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}
92bool
93ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
94 bool Complain) {
95 return First->ReadTargetOptions(TargetOpts, Complain) ||
96 Second->ReadTargetOptions(TargetOpts, Complain);
97}
98bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000099 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000100 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
101 Second->ReadDiagnosticOptions(DiagOpts, Complain);
102}
103bool
104ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
105 bool Complain) {
106 return First->ReadFileSystemOptions(FSOpts, Complain) ||
107 Second->ReadFileSystemOptions(FSOpts, Complain);
108}
109
110bool ChainedASTReaderListener::ReadHeaderSearchOptions(
111 const HeaderSearchOptions &HSOpts, bool Complain) {
112 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
113 Second->ReadHeaderSearchOptions(HSOpts, Complain);
114}
115bool ChainedASTReaderListener::ReadPreprocessorOptions(
116 const PreprocessorOptions &PPOpts, bool Complain,
117 std::string &SuggestedPredefines) {
118 return First->ReadPreprocessorOptions(PPOpts, Complain,
119 SuggestedPredefines) ||
120 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
121}
122void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
123 unsigned Value) {
124 First->ReadCounter(M, Value);
125 Second->ReadCounter(M, Value);
126}
127bool ChainedASTReaderListener::needsInputFileVisitation() {
128 return First->needsInputFileVisitation() ||
129 Second->needsInputFileVisitation();
130}
131bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
132 return First->needsSystemInputFileVisitation() ||
133 Second->needsSystemInputFileVisitation();
134}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000135void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
136 First->visitModuleFile(Filename);
137 Second->visitModuleFile(Filename);
138}
Ben Langmuircb69b572014-03-07 06:40:32 +0000139bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000140 bool isSystem,
141 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000142 bool Continue = false;
143 if (First->needsInputFileVisitation() &&
144 (!isSystem || First->needsSystemInputFileVisitation()))
145 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
146 if (Second->needsInputFileVisitation() &&
147 (!isSystem || Second->needsSystemInputFileVisitation()))
148 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
149 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000150}
151
Guy Benyei11169dd2012-12-18 14:30:41 +0000152//===----------------------------------------------------------------------===//
153// PCH validator implementation
154//===----------------------------------------------------------------------===//
155
156ASTReaderListener::~ASTReaderListener() {}
157
158/// \brief Compare the given set of language options against an existing set of
159/// language options.
160///
161/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000162/// \param AllowCompatibleDifferences If true, differences between compatible
163/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000164///
165/// \returns true if the languagae options mis-match, false otherwise.
166static bool checkLanguageOptions(const LangOptions &LangOpts,
167 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168 DiagnosticsEngine *Diags,
169 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000170#define LANGOPT(Name, Bits, Default, Description) \
171 if (ExistingLangOpts.Name != LangOpts.Name) { \
172 if (Diags) \
173 Diags->Report(diag::err_pch_langopt_mismatch) \
174 << Description << LangOpts.Name << ExistingLangOpts.Name; \
175 return true; \
176 }
177
178#define VALUE_LANGOPT(Name, Bits, Default, Description) \
179 if (ExistingLangOpts.Name != LangOpts.Name) { \
180 if (Diags) \
181 Diags->Report(diag::err_pch_langopt_value_mismatch) \
182 << Description; \
183 return true; \
184 }
185
186#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
187 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
188 if (Diags) \
189 Diags->Report(diag::err_pch_langopt_value_mismatch) \
190 << Description; \
191 return true; \
192 }
193
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000194#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
195 if (!AllowCompatibleDifferences) \
196 LANGOPT(Name, Bits, Default, Description)
197
198#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
199 if (!AllowCompatibleDifferences) \
200 ENUM_LANGOPT(Name, Bits, Default, Description)
201
Guy Benyei11169dd2012-12-18 14:30:41 +0000202#define BENIGN_LANGOPT(Name, Bits, Default, Description)
203#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
204#include "clang/Basic/LangOptions.def"
205
206 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
207 if (Diags)
208 Diags->Report(diag::err_pch_langopt_value_mismatch)
209 << "target Objective-C runtime";
210 return true;
211 }
212
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000213 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
214 LangOpts.CommentOpts.BlockCommandNames) {
215 if (Diags)
216 Diags->Report(diag::err_pch_langopt_value_mismatch)
217 << "block command names";
218 return true;
219 }
220
Guy Benyei11169dd2012-12-18 14:30:41 +0000221 return false;
222}
223
224/// \brief Compare the given set of target options against an existing set of
225/// target options.
226///
227/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
228///
229/// \returns true if the target options mis-match, false otherwise.
230static bool checkTargetOptions(const TargetOptions &TargetOpts,
231 const TargetOptions &ExistingTargetOpts,
232 DiagnosticsEngine *Diags) {
233#define CHECK_TARGET_OPT(Field, Name) \
234 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
235 if (Diags) \
236 Diags->Report(diag::err_pch_targetopt_mismatch) \
237 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
238 return true; \
239 }
240
241 CHECK_TARGET_OPT(Triple, "target");
242 CHECK_TARGET_OPT(CPU, "target CPU");
243 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000244#undef CHECK_TARGET_OPT
245
246 // Compare feature sets.
247 SmallVector<StringRef, 4> ExistingFeatures(
248 ExistingTargetOpts.FeaturesAsWritten.begin(),
249 ExistingTargetOpts.FeaturesAsWritten.end());
250 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
251 TargetOpts.FeaturesAsWritten.end());
252 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
253 std::sort(ReadFeatures.begin(), ReadFeatures.end());
254
255 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
256 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
257 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
258 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
259 ++ExistingIdx;
260 ++ReadIdx;
261 continue;
262 }
263
264 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
265 if (Diags)
266 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
267 << false << ReadFeatures[ReadIdx];
268 return true;
269 }
270
271 if (Diags)
272 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
273 << true << ExistingFeatures[ExistingIdx];
274 return true;
275 }
276
277 if (ExistingIdx < ExistingN) {
278 if (Diags)
279 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
280 << true << ExistingFeatures[ExistingIdx];
281 return true;
282 }
283
284 if (ReadIdx < ReadN) {
285 if (Diags)
286 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
287 << false << ReadFeatures[ReadIdx];
288 return true;
289 }
290
291 return false;
292}
293
294bool
295PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000296 bool Complain,
297 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 const LangOptions &ExistingLangOpts = PP.getLangOpts();
299 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000300 Complain ? &Reader.Diags : nullptr,
301 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302}
303
304bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
305 bool Complain) {
306 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
307 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000308 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000309}
310
311namespace {
312 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
313 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000314 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
315 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000316}
317
Ben Langmuirb92de022014-04-29 16:25:26 +0000318static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
319 DiagnosticsEngine &Diags,
320 bool Complain) {
321 typedef DiagnosticsEngine::Level Level;
322
323 // Check current mappings for new -Werror mappings, and the stored mappings
324 // for cases that were explicitly mapped to *not* be errors that are now
325 // errors because of options like -Werror.
326 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
327
328 for (DiagnosticsEngine *MappingSource : MappingSources) {
329 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
330 diag::kind DiagID = DiagIDMappingPair.first;
331 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
332 if (CurLevel < DiagnosticsEngine::Error)
333 continue; // not significant
334 Level StoredLevel =
335 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
336 if (StoredLevel < DiagnosticsEngine::Error) {
337 if (Complain)
338 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
339 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
340 return true;
341 }
342 }
343 }
344
345 return false;
346}
347
Alp Tokerac4e8e52014-06-22 21:58:33 +0000348static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
349 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
350 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
351 return true;
352 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000353}
354
355static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
356 DiagnosticsEngine &Diags,
357 bool IsSystem, bool Complain) {
358 // Top-level options
359 if (IsSystem) {
360 if (Diags.getSuppressSystemWarnings())
361 return false;
362 // If -Wsystem-headers was not enabled before, be conservative
363 if (StoredDiags.getSuppressSystemWarnings()) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
366 return true;
367 }
368 }
369
370 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
371 if (Complain)
372 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
373 return true;
374 }
375
376 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
377 !StoredDiags.getEnableAllWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
380 return true;
381 }
382
383 if (isExtHandlingFromDiagsError(Diags) &&
384 !isExtHandlingFromDiagsError(StoredDiags)) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
387 return true;
388 }
389
390 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
391}
392
393bool PCHValidator::ReadDiagnosticOptions(
394 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
395 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
396 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
397 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000398 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000399 // This should never fail, because we would have processed these options
400 // before writing them to an ASTFile.
401 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
402
403 ModuleManager &ModuleMgr = Reader.getModuleManager();
404 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
405
406 // If the original import came from a file explicitly generated by the user,
407 // don't check the diagnostic mappings.
408 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000409 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000410 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
411 // the transitive closure of its imports, since unrelated modules cannot be
412 // imported until after this module finishes validation.
413 ModuleFile *TopImport = *ModuleMgr.rbegin();
414 while (!TopImport->ImportedBy.empty())
415 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000416 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000417 return false;
418
419 StringRef ModuleName = TopImport->ModuleName;
420 assert(!ModuleName.empty() && "diagnostic options read before module name");
421
422 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
423 assert(M && "missing module");
424
425 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
426 // contains the union of their flags.
427 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
428}
429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430/// \brief Collect the macro definitions provided by the given preprocessor
431/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000432static void
433collectMacroDefinitions(const PreprocessorOptions &PPOpts,
434 MacroDefinitionsMap &Macros,
435 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000436 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
437 StringRef Macro = PPOpts.Macros[I].first;
438 bool IsUndef = PPOpts.Macros[I].second;
439
440 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
441 StringRef MacroName = MacroPair.first;
442 StringRef MacroBody = MacroPair.second;
443
444 // For an #undef'd macro, we only care about the name.
445 if (IsUndef) {
446 if (MacroNames && !Macros.count(MacroName))
447 MacroNames->push_back(MacroName);
448
449 Macros[MacroName] = std::make_pair("", true);
450 continue;
451 }
452
453 // For a #define'd macro, figure out the actual definition.
454 if (MacroName.size() == Macro.size())
455 MacroBody = "1";
456 else {
457 // Note: GCC drops anything following an end-of-line character.
458 StringRef::size_type End = MacroBody.find_first_of("\n\r");
459 MacroBody = MacroBody.substr(0, End);
460 }
461
462 if (MacroNames && !Macros.count(MacroName))
463 MacroNames->push_back(MacroName);
464 Macros[MacroName] = std::make_pair(MacroBody, false);
465 }
466}
467
468/// \brief Check the preprocessor options deserialized from the control block
469/// against the preprocessor options in an existing preprocessor.
470///
471/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
472static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
473 const PreprocessorOptions &ExistingPPOpts,
474 DiagnosticsEngine *Diags,
475 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000476 std::string &SuggestedPredefines,
477 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000478 // Check macro definitions.
479 MacroDefinitionsMap ASTFileMacros;
480 collectMacroDefinitions(PPOpts, ASTFileMacros);
481 MacroDefinitionsMap ExistingMacros;
482 SmallVector<StringRef, 4> ExistingMacroNames;
483 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
484
485 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
486 // Dig out the macro definition in the existing preprocessor options.
487 StringRef MacroName = ExistingMacroNames[I];
488 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
489
490 // Check whether we know anything about this macro name or not.
491 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
492 = ASTFileMacros.find(MacroName);
493 if (Known == ASTFileMacros.end()) {
494 // FIXME: Check whether this identifier was referenced anywhere in the
495 // AST file. If so, we should reject the AST file. Unfortunately, this
496 // information isn't in the control block. What shall we do about it?
497
498 if (Existing.second) {
499 SuggestedPredefines += "#undef ";
500 SuggestedPredefines += MacroName.str();
501 SuggestedPredefines += '\n';
502 } else {
503 SuggestedPredefines += "#define ";
504 SuggestedPredefines += MacroName.str();
505 SuggestedPredefines += ' ';
506 SuggestedPredefines += Existing.first.str();
507 SuggestedPredefines += '\n';
508 }
509 continue;
510 }
511
512 // If the macro was defined in one but undef'd in the other, we have a
513 // conflict.
514 if (Existing.second != Known->second.second) {
515 if (Diags) {
516 Diags->Report(diag::err_pch_macro_def_undef)
517 << MacroName << Known->second.second;
518 }
519 return true;
520 }
521
522 // If the macro was #undef'd in both, or if the macro bodies are identical,
523 // it's fine.
524 if (Existing.second || Existing.first == Known->second.first)
525 continue;
526
527 // The macro bodies differ; complain.
528 if (Diags) {
529 Diags->Report(diag::err_pch_macro_def_conflict)
530 << MacroName << Known->second.first << Existing.first;
531 }
532 return true;
533 }
534
535 // Check whether we're using predefines.
536 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
537 if (Diags) {
538 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
539 }
540 return true;
541 }
542
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000543 // Detailed record is important since it is used for the module cache hash.
544 if (LangOpts.Modules &&
545 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
546 if (Diags) {
547 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
548 }
549 return true;
550 }
551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 // Compute the #include and #include_macros lines we need.
553 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
554 StringRef File = ExistingPPOpts.Includes[I];
555 if (File == ExistingPPOpts.ImplicitPCHInclude)
556 continue;
557
558 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
559 != PPOpts.Includes.end())
560 continue;
561
562 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000563 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 SuggestedPredefines += "\"\n";
565 }
566
567 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.MacroIncludes[I];
569 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
570 File)
571 != PPOpts.MacroIncludes.end())
572 continue;
573
574 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000575 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 SuggestedPredefines += "\"\n##\n";
577 }
578
579 return false;
580}
581
582bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
583 bool Complain,
584 std::string &SuggestedPredefines) {
585 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
586
587 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000588 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000590 SuggestedPredefines,
591 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000592}
593
Guy Benyei11169dd2012-12-18 14:30:41 +0000594void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
595 PP.setCounterValue(Value);
596}
597
598//===----------------------------------------------------------------------===//
599// AST reader implementation
600//===----------------------------------------------------------------------===//
601
Nico Weber824285e2014-05-08 04:26:47 +0000602void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
603 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000605 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
608
609
610unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
611 return serialization::ComputeHash(Sel);
612}
613
614
615std::pair<unsigned, unsigned>
616ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000617 using namespace llvm::support;
618 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
619 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 return std::make_pair(KeyLen, DataLen);
621}
622
623ASTSelectorLookupTrait::internal_key_type
624ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000625 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000626 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000627 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
628 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
629 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 if (N == 0)
631 return SelTable.getNullarySelector(FirstII);
632 else if (N == 1)
633 return SelTable.getUnarySelector(FirstII);
634
635 SmallVector<IdentifierInfo *, 16> Args;
636 Args.push_back(FirstII);
637 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000638 Args.push_back(Reader.getLocalIdentifier(
639 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000640
641 return SelTable.getSelector(N, Args.data());
642}
643
644ASTSelectorLookupTrait::data_type
645ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
646 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000648
649 data_type Result;
650
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 Result.ID = Reader.getGlobalSelectorID(
652 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000653 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
654 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
655 Result.InstanceBits = FullInstanceBits & 0x3;
656 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
657 Result.FactoryBits = FullFactoryBits & 0x3;
658 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
659 unsigned NumInstanceMethods = FullInstanceBits >> 3;
660 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000661
662 // Load instance methods
663 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000664 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
665 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 Result.Instance.push_back(Method);
667 }
668
669 // Load factory methods
670 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
672 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 Result.Factory.push_back(Method);
674 }
675
676 return Result;
677}
678
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
680 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000681}
682
683std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000684ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000685 using namespace llvm::support;
686 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 return std::make_pair(KeyLen, DataLen);
689}
690
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000691ASTIdentifierLookupTraitBase::internal_key_type
692ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000694 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695}
696
Douglas Gregordcf25082013-02-11 18:16:18 +0000697/// \brief Whether the given identifier is "interesting".
698static bool isInterestingIdentifier(IdentifierInfo &II) {
699 return II.isPoisoned() ||
700 II.isExtensionToken() ||
701 II.getObjCOrBuiltinID() ||
702 II.hasRevertedTokenIDToIdentifier() ||
703 II.hadMacroDefinition() ||
704 II.getFETokenInfo<void>();
705}
706
Guy Benyei11169dd2012-12-18 14:30:41 +0000707IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
708 const unsigned char* d,
709 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000710 using namespace llvm::support;
711 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000712 bool IsInteresting = RawID & 0x01;
713
714 // Wipe out the "is interesting" bit.
715 RawID = RawID >> 1;
716
717 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
718 if (!IsInteresting) {
719 // For uninteresting identifiers, just build the IdentifierInfo
720 // and associate it with the persistent ID.
721 IdentifierInfo *II = KnownII;
722 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 KnownII = II;
725 }
726 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000727 if (!II->isFromAST()) {
728 bool WasInteresting = isInterestingIdentifier(*II);
729 II->setIsFromAST();
730 if (WasInteresting)
731 II->setChangedSinceDeserialization();
732 }
733 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 return II;
735 }
736
Justin Bogner57ba0b22014-03-28 22:03:24 +0000737 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 bool CPlusPlusOperatorKeyword = Bits & 0x01;
740 Bits >>= 1;
741 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
742 Bits >>= 1;
743 bool Poisoned = Bits & 0x01;
744 Bits >>= 1;
745 bool ExtensionToken = Bits & 0x01;
746 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000747 bool hasSubmoduleMacros = Bits & 0x01;
748 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 bool hadMacroDefinition = Bits & 0x01;
750 Bits >>= 1;
751
752 assert(Bits == 0 && "Extra bits in the identifier?");
753 DataLen -= 8;
754
755 // Build the IdentifierInfo itself and link the identifier ID with
756 // the new IdentifierInfo.
757 IdentifierInfo *II = KnownII;
758 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000759 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 KnownII = II;
761 }
762 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000763 if (!II->isFromAST()) {
764 bool WasInteresting = isInterestingIdentifier(*II);
765 II->setIsFromAST();
766 if (WasInteresting)
767 II->setChangedSinceDeserialization();
768 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000769
770 // Set or check the various bits in the IdentifierInfo structure.
771 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000772 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 II->RevertTokenIDToIdentifier();
774 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
775 assert(II->isExtensionToken() == ExtensionToken &&
776 "Incorrect extension token flag");
777 (void)ExtensionToken;
778 if (Poisoned)
779 II->setIsPoisoned(true);
780 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
781 "Incorrect C++ operator keyword flag");
782 (void)CPlusPlusOperatorKeyword;
783
784 // If this identifier is a macro, deserialize the macro
785 // definition.
786 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 uint32_t MacroDirectivesOffset =
788 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000789 DataLen -= 4;
790 SmallVector<uint32_t, 8> LocalMacroIDs;
791 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000792 while (true) {
793 uint32_t LocalMacroID =
794 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000795 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000796 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000797 LocalMacroIDs.push_back(LocalMacroID);
798 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000799 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000800
Richard Smithe842a472014-10-22 02:05:46 +0000801 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000802 // Macro definitions are stored from newest to oldest, so reverse them
803 // before registering them.
804 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000805 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000806 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
807 unsigned Size = 1;
808
809 static const uint32_t HasOverridesFlag = 0x80000000U;
810 if (I + 1 != E && (I[1] & HasOverridesFlag))
811 Size += 1 + (I[1] & ~HasOverridesFlag);
812
813 MacroSizes.push_back(Size);
814 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000815 }
Richard Smith49f906a2014-03-01 00:08:04 +0000816
817 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
818 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
819 SE = MacroSizes.rend();
820 SI != SE; ++SI) {
821 I -= *SI;
822
823 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000824 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000825 if (*SI != 1)
826 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
827 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
828 }
829 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 } else {
831 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
832 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 }
834
835 Reader.SetIdentifierInfo(ID, II);
836
837 // Read all of the declarations visible at global scope with this
838 // name.
839 if (DataLen > 0) {
840 SmallVector<uint32_t, 4> DeclIDs;
841 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000842 DeclIDs.push_back(Reader.getGlobalDeclID(
843 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000844 Reader.SetGloballyVisibleDecls(II, DeclIDs);
845 }
846
847 return II;
848}
849
850unsigned
851ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
852 llvm::FoldingSetNodeID ID;
853 ID.AddInteger(Key.Kind);
854
855 switch (Key.Kind) {
856 case DeclarationName::Identifier:
857 case DeclarationName::CXXLiteralOperatorName:
858 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
859 break;
860 case DeclarationName::ObjCZeroArgSelector:
861 case DeclarationName::ObjCOneArgSelector:
862 case DeclarationName::ObjCMultiArgSelector:
863 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
864 break;
865 case DeclarationName::CXXOperatorName:
866 ID.AddInteger((OverloadedOperatorKind)Key.Data);
867 break;
868 case DeclarationName::CXXConstructorName:
869 case DeclarationName::CXXDestructorName:
870 case DeclarationName::CXXConversionFunctionName:
871 case DeclarationName::CXXUsingDirective:
872 break;
873 }
874
875 return ID.ComputeHash();
876}
877
878ASTDeclContextNameLookupTrait::internal_key_type
879ASTDeclContextNameLookupTrait::GetInternalKey(
880 const external_key_type& Name) const {
881 DeclNameKey Key;
882 Key.Kind = Name.getNameKind();
883 switch (Name.getNameKind()) {
884 case DeclarationName::Identifier:
885 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
886 break;
887 case DeclarationName::ObjCZeroArgSelector:
888 case DeclarationName::ObjCOneArgSelector:
889 case DeclarationName::ObjCMultiArgSelector:
890 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
891 break;
892 case DeclarationName::CXXOperatorName:
893 Key.Data = Name.getCXXOverloadedOperator();
894 break;
895 case DeclarationName::CXXLiteralOperatorName:
896 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
897 break;
898 case DeclarationName::CXXConstructorName:
899 case DeclarationName::CXXDestructorName:
900 case DeclarationName::CXXConversionFunctionName:
901 case DeclarationName::CXXUsingDirective:
902 Key.Data = 0;
903 break;
904 }
905
906 return Key;
907}
908
909std::pair<unsigned, unsigned>
910ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 using namespace llvm::support;
912 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
913 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 return std::make_pair(KeyLen, DataLen);
915}
916
917ASTDeclContextNameLookupTrait::internal_key_type
918ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000919 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000920
921 DeclNameKey Key;
922 Key.Kind = (DeclarationName::NameKind)*d++;
923 switch (Key.Kind) {
924 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 Key.Data = (uint64_t)Reader.getLocalIdentifier(
926 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000927 break;
928 case DeclarationName::ObjCZeroArgSelector:
929 case DeclarationName::ObjCOneArgSelector:
930 case DeclarationName::ObjCMultiArgSelector:
931 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000932 (uint64_t)Reader.getLocalSelector(
933 F, endian::readNext<uint32_t, little, unaligned>(
934 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXOperatorName:
937 Key.Data = *d++; // OverloadedOperatorKind
938 break;
939 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000940 Key.Data = (uint64_t)Reader.getLocalIdentifier(
941 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 break;
943 case DeclarationName::CXXConstructorName:
944 case DeclarationName::CXXDestructorName:
945 case DeclarationName::CXXConversionFunctionName:
946 case DeclarationName::CXXUsingDirective:
947 Key.Data = 0;
948 break;
949 }
950
951 return Key;
952}
953
954ASTDeclContextNameLookupTrait::data_type
955ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
956 const unsigned char* d,
957 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 using namespace llvm::support;
959 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000960 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
961 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 return std::make_pair(Start, Start + NumDecls);
963}
964
965bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000966 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 const std::pair<uint64_t, uint64_t> &Offsets,
968 DeclContextInfo &Info) {
969 SavedStreamPosition SavedPosition(Cursor);
970 // First the lexical decls.
971 if (Offsets.first != 0) {
972 Cursor.JumpToBit(Offsets.first);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_LEXICAL) {
979 Error("Expected lexical block");
980 return true;
981 }
982
Chris Lattner0e6c9402013-01-20 02:38:54 +0000983 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
984 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 }
986
987 // Now the lookup table.
988 if (Offsets.second != 0) {
989 Cursor.JumpToBit(Offsets.second);
990
991 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000992 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000994 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 if (RecCode != DECL_CONTEXT_VISIBLE) {
996 Error("Expected visible lookup table block");
997 return true;
998 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000999 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1000 (const unsigned char *)Blob.data() + Record[0],
1001 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1002 (const unsigned char *)Blob.data(),
1003 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 return false;
1007}
1008
1009void ASTReader::Error(StringRef Msg) {
1010 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001011 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1012 Diag(diag::note_module_cache_path)
1013 << PP.getHeaderSearchInfo().getModuleCachePath();
1014 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001015}
1016
1017void ASTReader::Error(unsigned DiagID,
1018 StringRef Arg1, StringRef Arg2) {
1019 if (Diags.isDiagnosticInFlight())
1020 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1021 else
1022 Diag(DiagID) << Arg1 << Arg2;
1023}
1024
1025//===----------------------------------------------------------------------===//
1026// Source Manager Deserialization
1027//===----------------------------------------------------------------------===//
1028
1029/// \brief Read the line table in the source manager block.
1030/// \returns true if there was an error.
1031bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001032 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 unsigned Idx = 0;
1034 LineTableInfo &LineTable = SourceMgr.getLineTable();
1035
1036 // Parse the file names
1037 std::map<int, int> FileIDs;
1038 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1039 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001040 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1042 }
1043
1044 // Parse the line entries
1045 std::vector<LineEntry> Entries;
1046 while (Idx < Record.size()) {
1047 int FID = Record[Idx++];
1048 assert(FID >= 0 && "Serialized line entries for non-local file.");
1049 // Remap FileID from 1-based old view.
1050 FID += F.SLocEntryBaseID - 1;
1051
1052 // Extract the line entries
1053 unsigned NumEntries = Record[Idx++];
1054 assert(NumEntries && "Numentries is 00000");
1055 Entries.clear();
1056 Entries.reserve(NumEntries);
1057 for (unsigned I = 0; I != NumEntries; ++I) {
1058 unsigned FileOffset = Record[Idx++];
1059 unsigned LineNo = Record[Idx++];
1060 int FilenameID = FileIDs[Record[Idx++]];
1061 SrcMgr::CharacteristicKind FileKind
1062 = (SrcMgr::CharacteristicKind)Record[Idx++];
1063 unsigned IncludeOffset = Record[Idx++];
1064 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1065 FileKind, IncludeOffset));
1066 }
1067 LineTable.AddEntry(FileID::get(FID), Entries);
1068 }
1069
1070 return false;
1071}
1072
1073/// \brief Read a source manager block
1074bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1075 using namespace SrcMgr;
1076
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001077 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001078
1079 // Set the source-location entry cursor to the current position in
1080 // the stream. This cursor will be used to read the contents of the
1081 // source manager block initially, and then lazily read
1082 // source-location entries as needed.
1083 SLocEntryCursor = F.Stream;
1084
1085 // The stream itself is going to skip over the source manager block.
1086 if (F.Stream.SkipBlock()) {
1087 Error("malformed block record in AST file");
1088 return true;
1089 }
1090
1091 // Enter the source manager block.
1092 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1093 Error("malformed source manager block record in AST file");
1094 return true;
1095 }
1096
1097 RecordData Record;
1098 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001099 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1100
1101 switch (E.Kind) {
1102 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1103 case llvm::BitstreamEntry::Error:
1104 Error("malformed block record in AST file");
1105 return true;
1106 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001108 case llvm::BitstreamEntry::Record:
1109 // The interesting case.
1110 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001112
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001115 StringRef Blob;
1116 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 default: // Default behavior: ignore.
1118 break;
1119
1120 case SM_SLOC_FILE_ENTRY:
1121 case SM_SLOC_BUFFER_ENTRY:
1122 case SM_SLOC_EXPANSION_ENTRY:
1123 // Once we hit one of the source location entries, we're done.
1124 return false;
1125 }
1126 }
1127}
1128
1129/// \brief If a header file is not found at the path that we expect it to be
1130/// and the PCH file was moved from its original location, try to resolve the
1131/// file by assuming that header+PCH were moved together and the header is in
1132/// the same place relative to the PCH.
1133static std::string
1134resolveFileRelativeToOriginalDir(const std::string &Filename,
1135 const std::string &OriginalDir,
1136 const std::string &CurrDir) {
1137 assert(OriginalDir != CurrDir &&
1138 "No point trying to resolve the file if the PCH dir didn't change");
1139 using namespace llvm::sys;
1140 SmallString<128> filePath(Filename);
1141 fs::make_absolute(filePath);
1142 assert(path::is_absolute(OriginalDir));
1143 SmallString<128> currPCHPath(CurrDir);
1144
1145 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1146 fileDirE = path::end(path::parent_path(filePath));
1147 path::const_iterator origDirI = path::begin(OriginalDir),
1148 origDirE = path::end(OriginalDir);
1149 // Skip the common path components from filePath and OriginalDir.
1150 while (fileDirI != fileDirE && origDirI != origDirE &&
1151 *fileDirI == *origDirI) {
1152 ++fileDirI;
1153 ++origDirI;
1154 }
1155 for (; origDirI != origDirE; ++origDirI)
1156 path::append(currPCHPath, "..");
1157 path::append(currPCHPath, fileDirI, fileDirE);
1158 path::append(currPCHPath, path::filename(Filename));
1159 return currPCHPath.str();
1160}
1161
1162bool ASTReader::ReadSLocEntry(int ID) {
1163 if (ID == 0)
1164 return false;
1165
1166 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1167 Error("source location entry ID out-of-range for AST file");
1168 return true;
1169 }
1170
1171 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1172 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001173 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 unsigned BaseOffset = F->SLocEntryBaseOffset;
1175
1176 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001177 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1178 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 Error("incorrectly-formatted source location entry in AST file");
1180 return true;
1181 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001184 StringRef Blob;
1185 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 default:
1187 Error("incorrectly-formatted source location entry in AST file");
1188 return true;
1189
1190 case SM_SLOC_FILE_ENTRY: {
1191 // We will detect whether a file changed and return 'Failure' for it, but
1192 // we will also try to fail gracefully by setting up the SLocEntry.
1193 unsigned InputID = Record[4];
1194 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001195 const FileEntry *File = IF.getFile();
1196 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001197
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001198 // Note that we only check if a File was returned. If it was out-of-date
1199 // we have complained but we will continue creating a FileID to recover
1200 // gracefully.
1201 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 return true;
1203
1204 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1205 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1206 // This is the module's main file.
1207 IncludeLoc = getImportLocation(F);
1208 }
1209 SrcMgr::CharacteristicKind
1210 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1211 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1212 ID, BaseOffset + Record[0]);
1213 SrcMgr::FileInfo &FileInfo =
1214 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1215 FileInfo.NumCreatedFIDs = Record[5];
1216 if (Record[3])
1217 FileInfo.setHasLineDirectives();
1218
1219 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1220 unsigned NumFileDecls = Record[7];
1221 if (NumFileDecls) {
1222 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1223 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1224 NumFileDecls));
1225 }
1226
1227 const SrcMgr::ContentCache *ContentCache
1228 = SourceMgr.getOrCreateContentCache(File,
1229 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1230 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1231 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1232 unsigned Code = SLocEntryCursor.ReadCode();
1233 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001234 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001235
1236 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1237 Error("AST record has invalid code");
1238 return true;
1239 }
1240
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001241 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001242 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001243 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 }
1245
1246 break;
1247 }
1248
1249 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 unsigned Offset = Record[0];
1252 SrcMgr::CharacteristicKind
1253 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1254 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001255 if (IncludeLoc.isInvalid() &&
1256 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001257 IncludeLoc = getImportLocation(F);
1258 }
1259 unsigned Code = SLocEntryCursor.ReadCode();
1260 Record.clear();
1261 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001262 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263
1264 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1265 Error("AST record has invalid code");
1266 return true;
1267 }
1268
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001269 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1270 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001271 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001272 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 break;
1274 }
1275
1276 case SM_SLOC_EXPANSION_ENTRY: {
1277 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1278 SourceMgr.createExpansionLoc(SpellingLoc,
1279 ReadSourceLocation(*F, Record[2]),
1280 ReadSourceLocation(*F, Record[3]),
1281 Record[4],
1282 ID,
1283 BaseOffset + Record[0]);
1284 break;
1285 }
1286 }
1287
1288 return false;
1289}
1290
1291std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1292 if (ID == 0)
1293 return std::make_pair(SourceLocation(), "");
1294
1295 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1296 Error("source location entry ID out-of-range for AST file");
1297 return std::make_pair(SourceLocation(), "");
1298 }
1299
1300 // Find which module file this entry lands in.
1301 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001302 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 return std::make_pair(SourceLocation(), "");
1304
1305 // FIXME: Can we map this down to a particular submodule? That would be
1306 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001307 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001308}
1309
1310/// \brief Find the location where the module F is imported.
1311SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1312 if (F->ImportLoc.isValid())
1313 return F->ImportLoc;
1314
1315 // Otherwise we have a PCH. It's considered to be "imported" at the first
1316 // location of its includer.
1317 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001318 // Main file is the importer.
1319 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1320 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 return F->ImportedBy[0]->FirstLoc;
1323}
1324
1325/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1326/// specified cursor. Read the abbreviations that are at the top of the block
1327/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001328bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 if (Cursor.EnterSubBlock(BlockID)) {
1330 Error("malformed block record in AST file");
1331 return Failure;
1332 }
1333
1334 while (true) {
1335 uint64_t Offset = Cursor.GetCurrentBitNo();
1336 unsigned Code = Cursor.ReadCode();
1337
1338 // We expect all abbrevs to be at the start of the block.
1339 if (Code != llvm::bitc::DEFINE_ABBREV) {
1340 Cursor.JumpToBit(Offset);
1341 return false;
1342 }
1343 Cursor.ReadAbbrevRecord();
1344 }
1345}
1346
Richard Smithe40f2ba2013-08-07 21:41:30 +00001347Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001348 unsigned &Idx) {
1349 Token Tok;
1350 Tok.startToken();
1351 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1352 Tok.setLength(Record[Idx++]);
1353 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1354 Tok.setIdentifierInfo(II);
1355 Tok.setKind((tok::TokenKind)Record[Idx++]);
1356 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1357 return Tok;
1358}
1359
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001360MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001362
1363 // Keep track of where we are in the stream, then jump back there
1364 // after reading this macro.
1365 SavedStreamPosition SavedPosition(Stream);
1366
1367 Stream.JumpToBit(Offset);
1368 RecordData Record;
1369 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001370 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001371
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001373 // Advance to the next record, but if we get to the end of the block, don't
1374 // pop it (removing all the abbreviations from the cursor) since we want to
1375 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001376 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1378
1379 switch (Entry.Kind) {
1380 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1381 case llvm::BitstreamEntry::Error:
1382 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001383 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001384 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001385 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001386 case llvm::BitstreamEntry::Record:
1387 // The interesting case.
1388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 }
1390
1391 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 Record.clear();
1393 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001394 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 case PP_MACRO_DIRECTIVE_HISTORY:
1397 return Macro;
1398
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 case PP_MACRO_OBJECT_LIKE:
1400 case PP_MACRO_FUNCTION_LIKE: {
1401 // If we already have a macro, that means that we've hit the end
1402 // of the definition of the macro we were looking for. We're
1403 // done.
1404 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001406
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 unsigned NextIndex = 1; // Skip identifier ID.
1408 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001411 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001413 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1416 // Decode function-like macro info.
1417 bool isC99VarArgs = Record[NextIndex++];
1418 bool isGNUVarArgs = Record[NextIndex++];
1419 bool hasCommaPasting = Record[NextIndex++];
1420 MacroArgs.clear();
1421 unsigned NumArgs = Record[NextIndex++];
1422 for (unsigned i = 0; i != NumArgs; ++i)
1423 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1424
1425 // Install function-like macro info.
1426 MI->setIsFunctionLike();
1427 if (isC99VarArgs) MI->setIsC99Varargs();
1428 if (isGNUVarArgs) MI->setIsGNUVarargs();
1429 if (hasCommaPasting) MI->setHasCommaPasting();
1430 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1431 PP.getPreprocessorAllocator());
1432 }
1433
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 // Remember that we saw this macro last so that we add the tokens that
1435 // form its body to it.
1436 Macro = MI;
1437
1438 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1439 Record[NextIndex]) {
1440 // We have a macro definition. Register the association
1441 PreprocessedEntityID
1442 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1443 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001444 PreprocessingRecord::PPEntityID
1445 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1446 MacroDefinition *PPDef =
1447 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1448 if (PPDef)
1449 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 }
1451
1452 ++NumMacrosRead;
1453 break;
1454 }
1455
1456 case PP_TOKEN: {
1457 // If we see a TOKEN before a PP_MACRO_*, then the file is
1458 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001459 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001460
John McCallf413f5e2013-05-03 00:10:13 +00001461 unsigned Idx = 0;
1462 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 Macro->AddTokenToBody(Tok);
1464 break;
1465 }
1466 }
1467 }
1468}
1469
1470PreprocessedEntityID
1471ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1472 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1473 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1474 assert(I != M.PreprocessedEntityRemap.end()
1475 && "Invalid index into preprocessed entity index remap");
1476
1477 return LocalID + I->second;
1478}
1479
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1481 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001482}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001483
Guy Benyei11169dd2012-12-18 14:30:41 +00001484HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1486 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001487 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return ikey;
1489}
Guy Benyei11169dd2012-12-18 14:30:41 +00001490
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001491bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1492 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 return false;
1494
Richard Smith7ed1bc92014-12-05 22:42:13 +00001495 if (llvm::sys::path::is_absolute(a.Filename) &&
1496 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497 return true;
1498
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001500 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001501 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1502 if (!Key.Imported)
1503 return FileMgr.getFile(Key.Filename);
1504
1505 std::string Resolved = Key.Filename;
1506 Reader.ResolveImportedPath(M, Resolved);
1507 return FileMgr.getFile(Resolved);
1508 };
1509
1510 const FileEntry *FEA = GetFile(a);
1511 const FileEntry *FEB = GetFile(b);
1512 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001513}
1514
1515std::pair<unsigned, unsigned>
1516HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 using namespace llvm::support;
1518 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001521}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522
1523HeaderFileInfoTrait::internal_key_type
1524HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001525 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001526 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001527 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1528 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001529 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001530 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001531 return ikey;
1532}
1533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 unsigned DataLen) {
1537 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001538 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 HeaderFileInfo HFI;
1540 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001541 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1542 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 HFI.isImport = (Flags >> 5) & 0x01;
1544 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1545 HFI.DirInfo = (Flags >> 2) & 0x03;
1546 HFI.Resolved = (Flags >> 1) & 0x01;
1547 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001548 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1549 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1550 M, endian::readNext<uint32_t, little, unaligned>(d));
1551 if (unsigned FrameworkOffset =
1552 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 // The framework offset is 1 greater than the actual offset,
1554 // since 0 is used as an indicator for "no framework name".
1555 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1556 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1557 }
1558
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001561 if (LocalSMID) {
1562 // This header is part of a module. Associate it with the module to enable
1563 // implicit module import.
1564 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1565 Module *Mod = Reader.getSubmodule(GlobalSMID);
1566 HFI.isModuleHeader = true;
1567 FileManager &FileMgr = Reader.getFileManager();
1568 ModuleMap &ModMap =
1569 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001570 // FIXME: This information should be propagated through the
1571 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001572 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001573 std::string Filename = key.Filename;
1574 if (key.Imported)
1575 Reader.ResolveImportedPath(M, Filename);
1576 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001577 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001578 }
1579 }
1580
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1582 (void)End;
1583
1584 // This HeaderFileInfo was externally loaded.
1585 HFI.External = true;
1586 return HFI;
1587}
1588
Richard Smith49f906a2014-03-01 00:08:04 +00001589void
1590ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1591 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001592 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001594 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001595 if (!Overrides.empty()) {
1596 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1597 OverrideData[0] = Overrides.size();
1598 for (unsigned I = 0; I != Overrides.size(); ++I)
1599 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1600 }
1601 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001602}
1603
1604void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1605 ModuleFile *M,
1606 uint64_t MacroDirectivesOffset) {
1607 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1608 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001609}
1610
1611void ASTReader::ReadDefinedMacros() {
1612 // Note that we are loading defined macros.
1613 Deserializing Macros(this);
1614
1615 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1616 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001617 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001618
1619 // If there was no preprocessor block, skip this file.
1620 if (!MacroCursor.getBitStreamReader())
1621 continue;
1622
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001623 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 Cursor.JumpToBit((*I)->MacroStartOffset);
1625
1626 RecordData Record;
1627 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001628 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1629
1630 switch (E.Kind) {
1631 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1632 case llvm::BitstreamEntry::Error:
1633 Error("malformed block record in AST file");
1634 return;
1635 case llvm::BitstreamEntry::EndBlock:
1636 goto NextCursor;
1637
1638 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001640 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001641 default: // Default behavior: ignore.
1642 break;
1643
1644 case PP_MACRO_OBJECT_LIKE:
1645 case PP_MACRO_FUNCTION_LIKE:
1646 getLocalIdentifier(**I, Record[0]);
1647 break;
1648
1649 case PP_TOKEN:
1650 // Ignore tokens.
1651 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 break;
1654 }
1655 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001656 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 }
1658}
1659
1660namespace {
1661 /// \brief Visitor class used to look up identifirs in an AST file.
1662 class IdentifierLookupVisitor {
1663 StringRef Name;
1664 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 unsigned &NumIdentifierLookups;
1666 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001668
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001670 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1671 unsigned &NumIdentifierLookups,
1672 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001673 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001674 NumIdentifierLookups(NumIdentifierLookups),
1675 NumIdentifierLookupHits(NumIdentifierLookupHits),
1676 Found()
1677 {
1678 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001679
1680 static bool visit(ModuleFile &M, void *UserData) {
1681 IdentifierLookupVisitor *This
1682 = static_cast<IdentifierLookupVisitor *>(UserData);
1683
1684 // If we've already searched this module file, skip it now.
1685 if (M.Generation <= This->PriorGeneration)
1686 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 ASTIdentifierLookupTable *IdTable
1689 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1690 if (!IdTable)
1691 return false;
1692
1693 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1694 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001695 ++This->NumIdentifierLookups;
1696 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 if (Pos == IdTable->end())
1698 return false;
1699
1700 // Dereferencing the iterator has the effect of building the
1701 // IdentifierInfo node and populating it with the various
1702 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 This->Found = *Pos;
1705 return true;
1706 }
1707
1708 // \brief Retrieve the identifier info found within the module
1709 // files.
1710 IdentifierInfo *getIdentifierInfo() const { return Found; }
1711 };
1712}
1713
1714void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1715 // Note that we are loading an identifier.
1716 Deserializing AnIdentifier(this);
1717
1718 unsigned PriorGeneration = 0;
1719 if (getContext().getLangOpts().Modules)
1720 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001721
1722 // If there is a global index, look there first to determine which modules
1723 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001724 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001725 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001726 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001727 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1728 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001729 }
1730 }
1731
Douglas Gregor7211ac12013-01-25 23:32:03 +00001732 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001733 NumIdentifierLookups,
1734 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001735 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 markIdentifierUpToDate(&II);
1737}
1738
1739void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1740 if (!II)
1741 return;
1742
1743 II->setOutOfDate(false);
1744
1745 // Update the generation for this identifier.
1746 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001747 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001748}
1749
Richard Smith49f906a2014-03-01 00:08:04 +00001750struct ASTReader::ModuleMacroInfo {
1751 SubmoduleID SubModID;
1752 MacroInfo *MI;
1753 SubmoduleID *Overrides;
1754 // FIXME: Remove this.
1755 ModuleFile *F;
1756
1757 bool isDefine() const { return MI; }
1758
1759 SubmoduleID getSubmoduleID() const { return SubModID; }
1760
Craig Topper00bbdcf2014-06-28 23:22:23 +00001761 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001762 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001763 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001764 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1765 }
1766
Richard Smithdaa69e02014-07-25 04:40:03 +00001767 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001768 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001769 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1770 getOverriddenSubmodules());
1771 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1772 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001773 }
1774};
1775
1776ASTReader::ModuleMacroInfo *
1777ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1778 ModuleMacroInfo Info;
1779
1780 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1781 if (ID & 1) {
1782 // Macro undefinition.
1783 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001784 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001785 } else {
1786 // Macro definition.
1787 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1788 assert(GMacID);
1789
1790 // If this macro has already been loaded, don't do so again.
1791 // FIXME: This is highly dubious. Multiple macro definitions can have the
1792 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1793 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001794 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001795
1796 Info.MI = getMacro(GMacID);
1797 Info.SubModID = Info.MI->getOwningModuleID();
1798 }
1799 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1800 Info.F = PMInfo.M;
1801
1802 return new (Context) ModuleMacroInfo(Info);
1803}
1804
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1806 const PendingMacroInfo &PMInfo) {
1807 assert(II);
1808
Richard Smithe842a472014-10-22 02:05:46 +00001809 if (PMInfo.M->Kind != MK_ImplicitModule &&
1810 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 installPCHMacroDirectives(II, *PMInfo.M,
1812 PMInfo.PCHMacroData.MacroDirectivesOffset);
1813 return;
1814 }
Richard Smith49f906a2014-03-01 00:08:04 +00001815
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001816 // Module Macro.
1817
Richard Smith49f906a2014-03-01 00:08:04 +00001818 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1819 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 return;
1821
Richard Smith49f906a2014-03-01 00:08:04 +00001822 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1823 if (Owner && Owner->NameVisibility == Module::Hidden) {
1824 // Macros in the owning module are hidden. Just remember this macro to
1825 // install if we make this module visible.
1826 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1827 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001829 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001830}
1831
1832void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1833 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001834 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001835
1836 BitstreamCursor &Cursor = M.MacroCursor;
1837 SavedStreamPosition SavedPosition(Cursor);
1838 Cursor.JumpToBit(Offset);
1839
1840 llvm::BitstreamEntry Entry =
1841 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1842 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1843 Error("malformed block record in AST file");
1844 return;
1845 }
1846
1847 RecordData Record;
1848 PreprocessorRecordTypes RecType =
1849 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1850 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1851 Error("malformed block record in AST file");
1852 return;
1853 }
1854
1855 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001856 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001857 unsigned Idx = 0, N = Record.size();
1858 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001859 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001860 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001861 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1862 switch (K) {
1863 case MacroDirective::MD_Define: {
1864 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1865 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001866 SubmoduleID ImportedFrom = Record[Idx++];
1867 bool IsAmbiguous = Record[Idx++];
1868 llvm::SmallVector<unsigned, 4> Overrides;
1869 if (ImportedFrom) {
1870 Overrides.insert(Overrides.end(),
1871 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1872 Idx += Overrides.size() + 1;
1873 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001874 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001875 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1876 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001877 MD = DefMD;
1878 break;
1879 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001880 case MacroDirective::MD_Undefine: {
1881 SubmoduleID ImportedFrom = Record[Idx++];
1882 llvm::SmallVector<unsigned, 4> Overrides;
1883 if (ImportedFrom) {
1884 Overrides.insert(Overrides.end(),
1885 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1886 Idx += Overrides.size() + 1;
1887 }
1888 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001889 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001890 }
1891 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001892 bool isPublic = Record[Idx++];
1893 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1894 break;
1895 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001896
1897 if (!Latest)
1898 Latest = MD;
1899 if (Earliest)
1900 Earliest->setPrevious(MD);
1901 Earliest = MD;
1902 }
1903
1904 PP.setLoadedMacroDirective(II, Latest);
1905}
1906
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001907/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001908/// modules.
1909static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001910 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001911 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001912 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001913 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1914 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001915 SourceManager &SrcMgr = Reader.getSourceManager();
1916 bool PrevInSystem
1917 = PrevOwner? PrevOwner->IsSystem
1918 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1919 bool NewInSystem
1920 = NewOwner? NewOwner->IsSystem
1921 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1922 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001923 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001924 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001925}
1926
Richard Smith49f906a2014-03-01 00:08:04 +00001927void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001928 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001929 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001930 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001931 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1932 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933
Richard Smith49f906a2014-03-01 00:08:04 +00001934 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001935 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001936 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001937 auto HiddenIt = HiddenNamesMap.find(Owner);
1938 if (HiddenIt != HiddenNamesMap.end()) {
1939 HiddenNames &Hidden = HiddenIt->second;
1940 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1941 if (HI != Hidden.HiddenMacros.end()) {
1942 // Register the macro now so we don't lose it when we re-export.
1943 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001944
Richard Smithbb853c72014-08-13 01:23:33 +00001945 auto SubOverrides = HI->second->getOverriddenSubmodules();
1946 Hidden.HiddenMacros.erase(HI);
1947 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1948 }
Richard Smith49f906a2014-03-01 00:08:04 +00001949 }
1950
1951 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001952 Ambig.erase(
1953 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1954 return MD->getInfo()->getOwningModuleID() == OwnerID;
1955 }),
1956 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001957 }
1958}
1959
1960ASTReader::AmbiguousMacros *
1961ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001962 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001963 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001964 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001965 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001966 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001967
Craig Toppera13603a2014-05-22 05:54:18 +00001968 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1969 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001970 if (PrevDef && PrevDef->isAmbiguous()) {
1971 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1972 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1973 Ambig.push_back(PrevDef);
1974
Richard Smithdaa69e02014-07-25 04:40:03 +00001975 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001976
1977 if (!Ambig.empty())
1978 return &Ambig;
1979
1980 AmbiguousMacroDefs.erase(II);
1981 } else {
1982 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001983 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001984 if (PrevDef)
1985 Ambig.push_back(PrevDef);
1986
Richard Smithdaa69e02014-07-25 04:40:03 +00001987 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001988
1989 if (!Ambig.empty()) {
1990 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001991 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001992 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001993 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001994 }
Richard Smith49f906a2014-03-01 00:08:04 +00001995
1996 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001997 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001998}
1999
2000void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002001 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002002 assert(II && Owner);
2003
2004 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002005 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002006 // FIXME: If we made macros from this module visible but didn't provide a
2007 // source location for the import, we don't have a location for the macro.
2008 // Use the location at which the containing module file was first imported
2009 // for now.
2010 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002011 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002012 }
2013
Benjamin Kramer834652a2014-05-03 18:44:26 +00002014 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002015 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002016
Richard Smith49f906a2014-03-01 00:08:04 +00002017 // Create a synthetic macro definition corresponding to the import (or null
2018 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002019 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2020 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002021
2022 // If there's no ambiguity, just install the macro.
2023 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002024 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002025 return;
2026 }
2027 assert(!Prev->empty());
2028
2029 if (!MD) {
2030 // We imported a #undef that didn't remove all prior definitions. The most
2031 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002032 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002033 MacroInfo *NewMI = Prev->back()->getInfo();
2034 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002035 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2036
2037 // Install our #undef first so that we don't lose track of it. We'll replace
2038 // this with whichever macro definition ends up winning.
2039 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002040 }
2041
2042 // We're introducing a macro definition that creates or adds to an ambiguity.
2043 // We can resolve that ambiguity if this macro is token-for-token identical to
2044 // all of the existing definitions.
2045 MacroInfo *NewMI = MD->getInfo();
2046 assert(NewMI && "macro definition with no MacroInfo?");
2047 while (!Prev->empty()) {
2048 MacroInfo *PrevMI = Prev->back()->getInfo();
2049 assert(PrevMI && "macro definition with no MacroInfo?");
2050
2051 // Before marking the macros as ambiguous, check if this is a case where
2052 // both macros are in system headers. If so, we trust that the system
2053 // did not get it wrong. This also handles cases where Clang's own
2054 // headers have a different spelling of certain system macros:
2055 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2056 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2057 //
2058 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2059 // overrides the system limits.h's macros, so there's no conflict here.
2060 if (NewMI != PrevMI &&
2061 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2062 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2063 break;
2064
2065 // The previous definition is the same as this one (or both are defined in
2066 // system modules so we can assume they're equivalent); we don't need to
2067 // track it any more.
2068 Prev->pop_back();
2069 }
2070
2071 if (!Prev->empty())
2072 MD->setAmbiguous(true);
2073
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002074 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002075}
2076
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002077ASTReader::InputFileInfo
2078ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002079 // Go find this input file.
2080 BitstreamCursor &Cursor = F.InputFilesCursor;
2081 SavedStreamPosition SavedPosition(Cursor);
2082 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2083
2084 unsigned Code = Cursor.ReadCode();
2085 RecordData Record;
2086 StringRef Blob;
2087
2088 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2089 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2090 "invalid record type for input file");
2091 (void)Result;
2092
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002093 std::string Filename;
2094 off_t StoredSize;
2095 time_t StoredTime;
2096 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002097
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 assert(Record[0] == ID && "Bogus stored ID or offset");
2099 StoredSize = static_cast<off_t>(Record[1]);
2100 StoredTime = static_cast<time_t>(Record[2]);
2101 Overridden = static_cast<bool>(Record[3]);
2102 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002103 ResolveImportedPath(F, Filename);
2104
Hans Wennborg73945142014-03-14 17:45:06 +00002105 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2106 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002107}
2108
2109std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002110 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002111}
2112
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002113InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 // If this ID is bogus, just return an empty input file.
2115 if (ID == 0 || ID > F.InputFilesLoaded.size())
2116 return InputFile();
2117
2118 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002119 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 return F.InputFilesLoaded[ID-1];
2121
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002122 if (F.InputFilesLoaded[ID-1].isNotFound())
2123 return InputFile();
2124
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002126 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 SavedStreamPosition SavedPosition(Cursor);
2128 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2129
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002130 InputFileInfo FI = readInputFileInfo(F, ID);
2131 off_t StoredSize = FI.StoredSize;
2132 time_t StoredTime = FI.StoredTime;
2133 bool Overridden = FI.Overridden;
2134 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002135
Ben Langmuir198c1682014-03-07 07:27:49 +00002136 const FileEntry *File
2137 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2138 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2139
2140 // If we didn't find the file, resolve it relative to the
2141 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002142 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002143 F.OriginalDir != CurrentDir) {
2144 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2145 F.OriginalDir,
2146 CurrentDir);
2147 if (!Resolved.empty())
2148 File = FileMgr.getFile(Resolved);
2149 }
2150
2151 // For an overridden file, create a virtual file with the stored
2152 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002153 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2155 }
2156
Craig Toppera13603a2014-05-22 05:54:18 +00002157 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 if (Complain) {
2159 std::string ErrorStr = "could not find file '";
2160 ErrorStr += Filename;
2161 ErrorStr += "' referenced by AST file";
2162 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002164 // Record that we didn't find the file.
2165 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2166 return InputFile();
2167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002168
Ben Langmuir198c1682014-03-07 07:27:49 +00002169 // Check if there was a request to override the contents of the file
2170 // that was part of the precompiled header. Overridding such a file
2171 // can lead to problems when lexing using the source locations from the
2172 // PCH.
2173 SourceManager &SM = getSourceManager();
2174 if (!Overridden && SM.isFileOverridden(File)) {
2175 if (Complain)
2176 Error(diag::err_fe_pch_file_overridden, Filename);
2177 // After emitting the diagnostic, recover by disabling the override so
2178 // that the original file will be used.
2179 SM.disableFileContentsOverride(File);
2180 // The FileEntry is a virtual file entry with the size of the contents
2181 // that would override the original contents. Set it to the original's
2182 // size/time.
2183 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2184 StoredSize, StoredTime);
2185 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002186
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 bool IsOutOfDate = false;
2188
2189 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002190 if (!Overridden && //
2191 (StoredSize != File->getSize() ||
2192#if defined(LLVM_ON_WIN32)
2193 false
2194#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002195 // In our regression testing, the Windows file system seems to
2196 // have inconsistent modification times that sometimes
2197 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002198 //
2199 // This also happens in networked file systems, so disable this
2200 // check if validation is disabled or if we have an explicitly
2201 // built PCM file.
2202 //
2203 // FIXME: Should we also do this for PCH files? They could also
2204 // reasonably get shared across a network during a distributed build.
2205 (StoredTime != File->getModificationTime() && !DisableValidation &&
2206 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002207#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002208 )) {
2209 if (Complain) {
2210 // Build a list of the PCH imports that got us here (in reverse).
2211 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2212 while (ImportStack.back()->ImportedBy.size() > 0)
2213 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002214
Ben Langmuir198c1682014-03-07 07:27:49 +00002215 // The top-level PCH is stale.
2216 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2217 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002218
Ben Langmuir198c1682014-03-07 07:27:49 +00002219 // Print the import stack.
2220 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2221 Diag(diag::note_pch_required_by)
2222 << Filename << ImportStack[0]->FileName;
2223 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002224 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002225 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002226 }
2227
Ben Langmuir198c1682014-03-07 07:27:49 +00002228 if (!Diags.isDiagnosticInFlight())
2229 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 }
2231
Ben Langmuir198c1682014-03-07 07:27:49 +00002232 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 }
2234
Ben Langmuir198c1682014-03-07 07:27:49 +00002235 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2236
2237 // Note that we've loaded this input file.
2238 F.InputFilesLoaded[ID-1] = IF;
2239 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002240}
2241
Richard Smith7ed1bc92014-12-05 22:42:13 +00002242/// \brief If we are loading a relocatable PCH or module file, and the filename
2243/// is not an absolute path, add the system or module root to the beginning of
2244/// the file name.
2245void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2246 // Resolve relative to the base directory, if we have one.
2247 if (!M.BaseDirectory.empty())
2248 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002249}
2250
Richard Smith7ed1bc92014-12-05 22:42:13 +00002251void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2253 return;
2254
Richard Smith7ed1bc92014-12-05 22:42:13 +00002255 SmallString<128> Buffer;
2256 llvm::sys::path::append(Buffer, Prefix, Filename);
2257 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002258}
2259
2260ASTReader::ASTReadResult
2261ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002262 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002263 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002265 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266
2267 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2268 Error("malformed block record in AST file");
2269 return Failure;
2270 }
2271
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002272 // Should we allow the configuration of the module file to differ from the
2273 // configuration of the current translation unit in a compatible way?
2274 //
2275 // FIXME: Allow this for files explicitly specified with -include-pch too.
2276 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 // Read all of the records and blocks in the control block.
2279 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002280 unsigned NumInputs = 0;
2281 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002282 while (1) {
2283 llvm::BitstreamEntry Entry = Stream.advance();
2284
2285 switch (Entry.Kind) {
2286 case llvm::BitstreamEntry::Error:
2287 Error("malformed block record in AST file");
2288 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002289 case llvm::BitstreamEntry::EndBlock: {
2290 // Validate input files.
2291 const HeaderSearchOptions &HSOpts =
2292 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002293
Richard Smitha1825302014-10-23 22:18:29 +00002294 // All user input files reside at the index range [0, NumUserInputs), and
2295 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002296 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002298
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002299 // If we are reading a module, we will create a verification timestamp,
2300 // so we verify all input files. Otherwise, verify only user input
2301 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002302
2303 unsigned N = NumUserInputs;
2304 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002305 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002306 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002307 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002308 N = NumInputs;
2309
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002310 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002311 InputFile IF = getInputFile(F, I+1, Complain);
2312 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002316
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002317 if (Listener)
2318 Listener->visitModuleFile(F.FileName);
2319
Ben Langmuircb69b572014-03-07 06:40:32 +00002320 if (Listener && Listener->needsInputFileVisitation()) {
2321 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2322 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002323 for (unsigned I = 0; I < N; ++I) {
2324 bool IsSystem = I >= NumUserInputs;
2325 InputFileInfo FI = readInputFileInfo(F, I+1);
2326 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2327 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002328 }
2329
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002331 }
2332
Chris Lattnere7b154b2013-01-19 21:39:22 +00002333 case llvm::BitstreamEntry::SubBlock:
2334 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case INPUT_FILES_BLOCK_ID:
2336 F.InputFilesCursor = Stream;
2337 if (Stream.SkipBlock() || // Skip with the main cursor
2338 // Read the abbreviations
2339 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2340 Error("malformed block record in AST file");
2341 return Failure;
2342 }
2343 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002346 if (Stream.SkipBlock()) {
2347 Error("malformed block record in AST file");
2348 return Failure;
2349 }
2350 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352
2353 case llvm::BitstreamEntry::Record:
2354 // The interesting case.
2355 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 }
2357
2358 // Read and process a record.
2359 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002360 StringRef Blob;
2361 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 case METADATA: {
2363 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2364 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002365 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2366 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 return VersionMismatch;
2368 }
2369
2370 bool hasErrors = Record[5];
2371 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2372 Diag(diag::err_pch_with_compiler_errors);
2373 return HadErrors;
2374 }
2375
2376 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002377 // Relative paths in a relocatable PCH are relative to our sysroot.
2378 if (F.RelocatablePCH)
2379 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002380
2381 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002382 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2384 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002385 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 return VersionMismatch;
2387 }
2388 break;
2389 }
2390
Ben Langmuir487ea142014-10-23 18:05:36 +00002391 case SIGNATURE:
2392 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2393 F.Signature = Record[0];
2394 break;
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 case IMPORTS: {
2397 // Load each of the imported PCH files.
2398 unsigned Idx = 0, N = Record.size();
2399 while (Idx < N) {
2400 // Read information about the AST file.
2401 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2402 // The import location will be the local one for now; we will adjust
2403 // all import locations of module imports after the global source
2404 // location info are setup.
2405 SourceLocation ImportLoc =
2406 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002407 off_t StoredSize = (off_t)Record[Idx++];
2408 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002409 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002410 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002411
2412 // Load the AST file.
2413 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002414 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 ClientLoadCapabilities)) {
2416 case Failure: return Failure;
2417 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002418 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case OutOfDate: return OutOfDate;
2420 case VersionMismatch: return VersionMismatch;
2421 case ConfigurationMismatch: return ConfigurationMismatch;
2422 case HadErrors: return HadErrors;
2423 case Success: break;
2424 }
2425 }
2426 break;
2427 }
2428
2429 case LANGUAGE_OPTIONS: {
2430 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002431 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002433 ParseLanguageOptions(Record, Complain, *Listener,
2434 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002435 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return ConfigurationMismatch;
2437 break;
2438 }
2439
2440 case TARGET_OPTIONS: {
2441 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2442 if (Listener && &F == *ModuleMgr.begin() &&
2443 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002444 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 return ConfigurationMismatch;
2446 break;
2447 }
2448
2449 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002450 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002452 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002454 !DisableValidation)
2455 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 break;
2457 }
2458
2459 case FILE_SYSTEM_OPTIONS: {
2460 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2461 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002462 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002464 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 return ConfigurationMismatch;
2466 break;
2467 }
2468
2469 case HEADER_SEARCH_OPTIONS: {
2470 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2471 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002472 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002474 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 return ConfigurationMismatch;
2476 break;
2477 }
2478
2479 case PREPROCESSOR_OPTIONS: {
2480 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2481 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002482 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 ParsePreprocessorOptions(Record, Complain, *Listener,
2484 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002485 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 return ConfigurationMismatch;
2487 break;
2488 }
2489
2490 case ORIGINAL_FILE:
2491 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002492 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002494 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 break;
2496
2497 case ORIGINAL_FILE_ID:
2498 F.OriginalSourceFileID = FileID::get(Record[0]);
2499 break;
2500
2501 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002502 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 break;
2504
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002505 case MODULE_NAME:
2506 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002507 if (Listener)
2508 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002509 break;
2510
Richard Smith223d3f22014-12-06 03:21:08 +00002511 case MODULE_DIRECTORY: {
2512 assert(!F.ModuleName.empty() &&
2513 "MODULE_DIRECTORY found before MODULE_NAME");
2514 // If we've already loaded a module map file covering this module, we may
2515 // have a better path for it (relative to the current build).
2516 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2517 if (M && M->Directory) {
2518 // If we're implicitly loading a module, the base directory can't
2519 // change between the build and use.
2520 if (F.Kind != MK_ExplicitModule) {
2521 const DirectoryEntry *BuildDir =
2522 PP.getFileManager().getDirectory(Blob);
2523 if (!BuildDir || BuildDir != M->Directory) {
2524 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2525 Diag(diag::err_imported_module_relocated)
2526 << F.ModuleName << Blob << M->Directory->getName();
2527 return OutOfDate;
2528 }
2529 }
2530 F.BaseDirectory = M->Directory->getName();
2531 } else {
2532 F.BaseDirectory = Blob;
2533 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002534 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002535 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002536
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002537 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002538 if (ASTReadResult Result =
2539 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2540 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002541 break;
2542
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002544 NumInputs = Record[0];
2545 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002546 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002547 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 break;
2549 }
2550 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002551}
2552
Ben Langmuir2c9af442014-04-10 17:57:43 +00002553ASTReader::ASTReadResult
2554ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002555 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002556
2557 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2558 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002559 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 }
2561
2562 // Read all of the records and blocks for the AST file.
2563 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002564 while (1) {
2565 llvm::BitstreamEntry Entry = Stream.advance();
2566
2567 switch (Entry.Kind) {
2568 case llvm::BitstreamEntry::Error:
2569 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002570 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002571 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002572 // Outside of C++, we do not store a lookup map for the translation unit.
2573 // Instead, mark it as needing a lookup map to be built if this module
2574 // contains any declarations lexically within it (which it always does!).
2575 // This usually has no cost, since we very rarely need the lookup map for
2576 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002578 if (DC->hasExternalLexicalStorage() &&
2579 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581
Ben Langmuir2c9af442014-04-10 17:57:43 +00002582 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002584 case llvm::BitstreamEntry::SubBlock:
2585 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 case DECLTYPES_BLOCK_ID:
2587 // We lazily load the decls block, but we want to set up the
2588 // DeclsCursor cursor to point into it. Clone our current bitcode
2589 // cursor to it, enter the block and read the abbrevs in that block.
2590 // With the main cursor, we just skip over it.
2591 F.DeclsCursor = Stream;
2592 if (Stream.SkipBlock() || // Skip with the main cursor.
2593 // Read the abbrevs.
2594 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2595 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
2598 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002599
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 case PREPROCESSOR_BLOCK_ID:
2601 F.MacroCursor = Stream;
2602 if (!PP.getExternalSource())
2603 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 if (Stream.SkipBlock() ||
2606 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2607 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 }
2610 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2611 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 case PREPROCESSOR_DETAIL_BLOCK_ID:
2614 F.PreprocessorDetailCursor = Stream;
2615 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002616 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002618 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002622 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 if (!PP.getPreprocessingRecord())
2625 PP.createPreprocessingRecord();
2626 if (!PP.getPreprocessingRecord()->getExternalSource())
2627 PP.getPreprocessingRecord()->SetExternalSource(*this);
2628 break;
2629
2630 case SOURCE_MANAGER_BLOCK_ID:
2631 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002632 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2637 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002641 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 if (Stream.SkipBlock() ||
2643 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2644 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002645 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647 CommentsCursors.push_back(std::make_pair(C, &F));
2648 break;
2649 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002650
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002652 if (Stream.SkipBlock()) {
2653 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002654 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 }
2656 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 }
2658 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002659
2660 case llvm::BitstreamEntry::Record:
2661 // The interesting case.
2662 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 }
2664
2665 // Read and process a record.
2666 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002667 StringRef Blob;
2668 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 default: // Default behavior: ignore.
2670 break;
2671
2672 case TYPE_OFFSET: {
2673 if (F.LocalNumTypes != 0) {
2674 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002675 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002677 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 F.LocalNumTypes = Record[0];
2679 unsigned LocalBaseTypeIndex = Record[1];
2680 F.BaseTypeIndex = getTotalNumTypes();
2681
2682 if (F.LocalNumTypes > 0) {
2683 // Introduce the global -> local mapping for types within this module.
2684 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2685
2686 // Introduce the local -> global mapping for types within this module.
2687 F.TypeRemap.insertOrReplace(
2688 std::make_pair(LocalBaseTypeIndex,
2689 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002690
2691 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 }
2693 break;
2694 }
2695
2696 case DECL_OFFSET: {
2697 if (F.LocalNumDecls != 0) {
2698 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002699 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002701 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 F.LocalNumDecls = Record[0];
2703 unsigned LocalBaseDeclID = Record[1];
2704 F.BaseDeclID = getTotalNumDecls();
2705
2706 if (F.LocalNumDecls > 0) {
2707 // Introduce the global -> local mapping for declarations within this
2708 // module.
2709 GlobalDeclMap.insert(
2710 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2711
2712 // Introduce the local -> global mapping for declarations within this
2713 // module.
2714 F.DeclRemap.insertOrReplace(
2715 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2716
2717 // Introduce the global -> local mapping for declarations within this
2718 // module.
2719 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002720
Ben Langmuir52ca6782014-10-20 16:27:32 +00002721 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2722 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 break;
2724 }
2725
2726 case TU_UPDATE_LEXICAL: {
2727 DeclContext *TU = Context.getTranslationUnitDecl();
2728 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002731 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 TU->setHasExternalLexicalStorage(true);
2733 break;
2734 }
2735
2736 case UPDATE_VISIBLE: {
2737 unsigned Idx = 0;
2738 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2739 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002740 ASTDeclContextNameLookupTable::Create(
2741 (const unsigned char *)Blob.data() + Record[Idx++],
2742 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2743 (const unsigned char *)Blob.data(),
2744 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002745 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002746 auto *DC = cast<DeclContext>(D);
2747 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002748 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2749 delete LookupTable;
2750 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 } else
2752 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2753 break;
2754 }
2755
2756 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002757 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002759 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2760 (const unsigned char *)F.IdentifierTableData + Record[0],
2761 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2762 (const unsigned char *)F.IdentifierTableData,
2763 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002764
2765 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2766 }
2767 break;
2768
2769 case IDENTIFIER_OFFSET: {
2770 if (F.LocalNumIdentifiers != 0) {
2771 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002772 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002774 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 F.LocalNumIdentifiers = Record[0];
2776 unsigned LocalBaseIdentifierID = Record[1];
2777 F.BaseIdentifierID = getTotalNumIdentifiers();
2778
2779 if (F.LocalNumIdentifiers > 0) {
2780 // Introduce the global -> local mapping for identifiers within this
2781 // module.
2782 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2783 &F));
2784
2785 // Introduce the local -> global mapping for identifiers within this
2786 // module.
2787 F.IdentifierRemap.insertOrReplace(
2788 std::make_pair(LocalBaseIdentifierID,
2789 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002790
Ben Langmuir52ca6782014-10-20 16:27:32 +00002791 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2792 + F.LocalNumIdentifiers);
2793 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 break;
2795 }
2796
Ben Langmuir332aafe2014-01-31 01:06:56 +00002797 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002799 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 break;
2801
2802 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002803 if (SpecialTypes.empty()) {
2804 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2805 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2806 break;
2807 }
2808
2809 if (SpecialTypes.size() != Record.size()) {
2810 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002811 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002812 }
2813
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2815 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2816 if (!SpecialTypes[I])
2817 SpecialTypes[I] = ID;
2818 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2819 // merge step?
2820 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 break;
2822
2823 case STATISTICS:
2824 TotalNumStatements += Record[0];
2825 TotalNumMacros += Record[1];
2826 TotalLexicalDeclContexts += Record[2];
2827 TotalVisibleDeclContexts += Record[3];
2828 break;
2829
2830 case UNUSED_FILESCOPED_DECLS:
2831 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2832 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2833 break;
2834
2835 case DELEGATING_CTORS:
2836 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2837 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2838 break;
2839
2840 case WEAK_UNDECLARED_IDENTIFIERS:
2841 if (Record.size() % 4 != 0) {
2842 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002843 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 }
2845
2846 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2847 // files. This isn't the way to do it :)
2848 WeakUndeclaredIdentifiers.clear();
2849
2850 // Translate the weak, undeclared identifiers into global IDs.
2851 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2852 WeakUndeclaredIdentifiers.push_back(
2853 getGlobalIdentifierID(F, Record[I++]));
2854 WeakUndeclaredIdentifiers.push_back(
2855 getGlobalIdentifierID(F, Record[I++]));
2856 WeakUndeclaredIdentifiers.push_back(
2857 ReadSourceLocation(F, Record, I).getRawEncoding());
2858 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2859 }
2860 break;
2861
Richard Smith78165b52013-01-10 23:43:47 +00002862 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002864 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 break;
2866
2867 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002868 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 F.LocalNumSelectors = Record[0];
2870 unsigned LocalBaseSelectorID = Record[1];
2871 F.BaseSelectorID = getTotalNumSelectors();
2872
2873 if (F.LocalNumSelectors > 0) {
2874 // Introduce the global -> local mapping for selectors within this
2875 // module.
2876 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2877
2878 // Introduce the local -> global mapping for selectors within this
2879 // module.
2880 F.SelectorRemap.insertOrReplace(
2881 std::make_pair(LocalBaseSelectorID,
2882 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002883
2884 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 }
2886 break;
2887 }
2888
2889 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002890 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 if (Record[0])
2892 F.SelectorLookupTable
2893 = ASTSelectorLookupTable::Create(
2894 F.SelectorLookupTableData + Record[0],
2895 F.SelectorLookupTableData,
2896 ASTSelectorLookupTrait(*this, F));
2897 TotalNumMethodPoolEntries += Record[1];
2898 break;
2899
2900 case REFERENCED_SELECTOR_POOL:
2901 if (!Record.empty()) {
2902 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2903 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2904 Record[Idx++]));
2905 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2906 getRawEncoding());
2907 }
2908 }
2909 break;
2910
2911 case PP_COUNTER_VALUE:
2912 if (!Record.empty() && Listener)
2913 Listener->ReadCounter(F, Record[0]);
2914 break;
2915
2916 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002917 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 F.NumFileSortedDecls = Record[0];
2919 break;
2920
2921 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002922 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 F.LocalNumSLocEntries = Record[0];
2924 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002925 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002926 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 SLocSpaceSize);
2928 // Make our entry in the range map. BaseID is negative and growing, so
2929 // we invert it. Because we invert it, though, we need the other end of
2930 // the range.
2931 unsigned RangeStart =
2932 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2933 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2934 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2935
2936 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2937 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2938 GlobalSLocOffsetMap.insert(
2939 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2940 - SLocSpaceSize,&F));
2941
2942 // Initialize the remapping table.
2943 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002944 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002946 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2948
2949 TotalNumSLocEntries += F.LocalNumSLocEntries;
2950 break;
2951 }
2952
2953 case MODULE_OFFSET_MAP: {
2954 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002955 const unsigned char *Data = (const unsigned char*)Blob.data();
2956 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002957
2958 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2959 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2960 F.SLocRemap.insert(std::make_pair(0U, 0));
2961 F.SLocRemap.insert(std::make_pair(2U, 1));
2962 }
2963
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002965 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2966 RemapBuilder;
2967 RemapBuilder SLocRemap(F.SLocRemap);
2968 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2969 RemapBuilder MacroRemap(F.MacroRemap);
2970 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2971 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2972 RemapBuilder SelectorRemap(F.SelectorRemap);
2973 RemapBuilder DeclRemap(F.DeclRemap);
2974 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002975
2976 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002977 using namespace llvm::support;
2978 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 StringRef Name = StringRef((const char*)Data, Len);
2980 Data += Len;
2981 ModuleFile *OM = ModuleMgr.lookup(Name);
2982 if (!OM) {
2983 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002984 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 }
2986
Justin Bogner57ba0b22014-03-28 22:03:24 +00002987 uint32_t SLocOffset =
2988 endian::readNext<uint32_t, little, unaligned>(Data);
2989 uint32_t IdentifierIDOffset =
2990 endian::readNext<uint32_t, little, unaligned>(Data);
2991 uint32_t MacroIDOffset =
2992 endian::readNext<uint32_t, little, unaligned>(Data);
2993 uint32_t PreprocessedEntityIDOffset =
2994 endian::readNext<uint32_t, little, unaligned>(Data);
2995 uint32_t SubmoduleIDOffset =
2996 endian::readNext<uint32_t, little, unaligned>(Data);
2997 uint32_t SelectorIDOffset =
2998 endian::readNext<uint32_t, little, unaligned>(Data);
2999 uint32_t DeclIDOffset =
3000 endian::readNext<uint32_t, little, unaligned>(Data);
3001 uint32_t TypeIndexOffset =
3002 endian::readNext<uint32_t, little, unaligned>(Data);
3003
Ben Langmuir785180e2014-10-20 16:27:30 +00003004 uint32_t None = std::numeric_limits<uint32_t>::max();
3005
3006 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3007 RemapBuilder &Remap) {
3008 if (Offset != None)
3009 Remap.insert(std::make_pair(Offset,
3010 static_cast<int>(BaseOffset - Offset)));
3011 };
3012 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3013 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3014 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3015 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3016 PreprocessedEntityRemap);
3017 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3018 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3019 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3020 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003021
3022 // Global -> local mappings.
3023 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3024 }
3025 break;
3026 }
3027
3028 case SOURCE_MANAGER_LINE_TABLE:
3029 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003030 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 break;
3032
3033 case SOURCE_LOCATION_PRELOADS: {
3034 // Need to transform from the local view (1-based IDs) to the global view,
3035 // which is based off F.SLocEntryBaseID.
3036 if (!F.PreloadSLocEntries.empty()) {
3037 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
3040
3041 F.PreloadSLocEntries.swap(Record);
3042 break;
3043 }
3044
3045 case EXT_VECTOR_DECLS:
3046 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3047 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3048 break;
3049
3050 case VTABLE_USES:
3051 if (Record.size() % 3 != 0) {
3052 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003053 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 }
3055
3056 // Later tables overwrite earlier ones.
3057 // FIXME: Modules will have some trouble with this. This is clearly not
3058 // the right way to do this.
3059 VTableUses.clear();
3060
3061 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3062 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3063 VTableUses.push_back(
3064 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3065 VTableUses.push_back(Record[Idx++]);
3066 }
3067 break;
3068
3069 case DYNAMIC_CLASSES:
3070 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3071 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3072 break;
3073
3074 case PENDING_IMPLICIT_INSTANTIATIONS:
3075 if (PendingInstantiations.size() % 2 != 0) {
3076 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003077 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003078 }
3079
3080 if (Record.size() % 2 != 0) {
3081 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003082 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 }
3084
3085 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3086 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3087 PendingInstantiations.push_back(
3088 ReadSourceLocation(F, Record, I).getRawEncoding());
3089 }
3090 break;
3091
3092 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003093 if (Record.size() != 2) {
3094 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003095 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003096 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3098 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3099 break;
3100
3101 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003102 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3103 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3104 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003105
3106 unsigned LocalBasePreprocessedEntityID = Record[0];
3107
3108 unsigned StartingID;
3109 if (!PP.getPreprocessingRecord())
3110 PP.createPreprocessingRecord();
3111 if (!PP.getPreprocessingRecord()->getExternalSource())
3112 PP.getPreprocessingRecord()->SetExternalSource(*this);
3113 StartingID
3114 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003115 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 F.BasePreprocessedEntityID = StartingID;
3117
3118 if (F.NumPreprocessedEntities > 0) {
3119 // Introduce the global -> local mapping for preprocessed entities in
3120 // this module.
3121 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3122
3123 // Introduce the local -> global mapping for preprocessed entities in
3124 // this module.
3125 F.PreprocessedEntityRemap.insertOrReplace(
3126 std::make_pair(LocalBasePreprocessedEntityID,
3127 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3128 }
3129
3130 break;
3131 }
3132
3133 case DECL_UPDATE_OFFSETS: {
3134 if (Record.size() % 2 != 0) {
3135 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003136 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003138 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3139 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3140 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3141
3142 // If we've already loaded the decl, perform the updates when we finish
3143 // loading this block.
3144 if (Decl *D = GetExistingDecl(ID))
3145 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 break;
3148 }
3149
3150 case DECL_REPLACEMENTS: {
3151 if (Record.size() % 3 != 0) {
3152 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003153 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 }
3155 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3156 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3157 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3158 break;
3159 }
3160
3161 case OBJC_CATEGORIES_MAP: {
3162 if (F.LocalNumObjCCategoriesInMap != 0) {
3163 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003164 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
3166
3167 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003168 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 break;
3170 }
3171
3172 case OBJC_CATEGORIES:
3173 F.ObjCCategories.swap(Record);
3174 break;
3175
3176 case CXX_BASE_SPECIFIER_OFFSETS: {
3177 if (F.LocalNumCXXBaseSpecifiers != 0) {
3178 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003179 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 }
3181
3182 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003183 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3185 break;
3186 }
3187
3188 case DIAG_PRAGMA_MAPPINGS:
3189 if (F.PragmaDiagMappings.empty())
3190 F.PragmaDiagMappings.swap(Record);
3191 else
3192 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3193 Record.begin(), Record.end());
3194 break;
3195
3196 case CUDA_SPECIAL_DECL_REFS:
3197 // Later tables overwrite earlier ones.
3198 // FIXME: Modules will have trouble with this.
3199 CUDASpecialDeclRefs.clear();
3200 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3201 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3202 break;
3203
3204 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003205 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003206 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 if (Record[0]) {
3208 F.HeaderFileInfoTable
3209 = HeaderFileInfoLookupTable::Create(
3210 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3211 (const unsigned char *)F.HeaderFileInfoTableData,
3212 HeaderFileInfoTrait(*this, F,
3213 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003214 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003215
3216 PP.getHeaderSearchInfo().SetExternalSource(this);
3217 if (!PP.getHeaderSearchInfo().getExternalLookup())
3218 PP.getHeaderSearchInfo().SetExternalLookup(this);
3219 }
3220 break;
3221 }
3222
3223 case FP_PRAGMA_OPTIONS:
3224 // Later tables overwrite earlier ones.
3225 FPPragmaOptions.swap(Record);
3226 break;
3227
3228 case OPENCL_EXTENSIONS:
3229 // Later tables overwrite earlier ones.
3230 OpenCLExtensions.swap(Record);
3231 break;
3232
3233 case TENTATIVE_DEFINITIONS:
3234 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3235 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3236 break;
3237
3238 case KNOWN_NAMESPACES:
3239 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3240 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3241 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003242
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003243 case UNDEFINED_BUT_USED:
3244 if (UndefinedButUsed.size() % 2 != 0) {
3245 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003246 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003247 }
3248
3249 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003250 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003251 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003252 }
3253 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003254 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3255 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003256 ReadSourceLocation(F, Record, I).getRawEncoding());
3257 }
3258 break;
3259
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003261 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 // If we aren't loading a module (which has its own exports), make
3263 // all of the imported modules visible.
3264 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003265 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3266 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3267 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3268 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003269 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 }
3271 }
3272 break;
3273 }
3274
3275 case LOCAL_REDECLARATIONS: {
3276 F.RedeclarationChains.swap(Record);
3277 break;
3278 }
3279
3280 case LOCAL_REDECLARATIONS_MAP: {
3281 if (F.LocalNumRedeclarationsInMap != 0) {
3282 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003283 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 }
3285
3286 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003287 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 break;
3289 }
3290
3291 case MERGED_DECLARATIONS: {
3292 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3293 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3294 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3295 for (unsigned N = Record[Idx++]; N > 0; --N)
3296 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3297 }
3298 break;
3299 }
3300
3301 case MACRO_OFFSET: {
3302 if (F.LocalNumMacros != 0) {
3303 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003304 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003306 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 F.LocalNumMacros = Record[0];
3308 unsigned LocalBaseMacroID = Record[1];
3309 F.BaseMacroID = getTotalNumMacros();
3310
3311 if (F.LocalNumMacros > 0) {
3312 // Introduce the global -> local mapping for macros within this module.
3313 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3314
3315 // Introduce the local -> global mapping for macros within this module.
3316 F.MacroRemap.insertOrReplace(
3317 std::make_pair(LocalBaseMacroID,
3318 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003319
3320 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 }
3322 break;
3323 }
3324
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003325 case MACRO_TABLE: {
3326 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 break;
3328 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003329
3330 case LATE_PARSED_TEMPLATE: {
3331 LateParsedTemplates.append(Record.begin(), Record.end());
3332 break;
3333 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003334
3335 case OPTIMIZE_PRAGMA_OPTIONS:
3336 if (Record.size() != 1) {
3337 Error("invalid pragma optimize record");
3338 return Failure;
3339 }
3340 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3341 break;
Nico Weber72889432014-09-06 01:25:55 +00003342
3343 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3344 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3345 UnusedLocalTypedefNameCandidates.push_back(
3346 getGlobalDeclID(F, Record[I]));
3347 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348 }
3349 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003350}
3351
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003352ASTReader::ASTReadResult
3353ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3354 const ModuleFile *ImportedBy,
3355 unsigned ClientLoadCapabilities) {
3356 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003357 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003358
Richard Smithe842a472014-10-22 02:05:46 +00003359 if (F.Kind == MK_ExplicitModule) {
3360 // For an explicitly-loaded module, we don't care whether the original
3361 // module map file exists or matches.
3362 return Success;
3363 }
3364
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003365 // Try to resolve ModuleName in the current header search context and
3366 // verify that it is found in the same module map file as we saved. If the
3367 // top-level AST file is a main file, skip this check because there is no
3368 // usable header search context.
3369 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003370 "MODULE_NAME should come before MODULE_MAP_FILE");
3371 if (F.Kind == MK_ImplicitModule &&
3372 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3373 // An implicitly-loaded module file should have its module listed in some
3374 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003376 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3377 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3378 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003379 assert(ImportedBy && "top-level import should be verified");
3380 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003381 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3382 << ImportedBy->FileName
3383 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003384 return Missing;
3385 }
3386
Richard Smithe842a472014-10-22 02:05:46 +00003387 assert(M->Name == F.ModuleName && "found module with different name");
3388
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003389 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003390 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003391 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3392 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003393 assert(ImportedBy && "top-level import should be verified");
3394 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3395 Diag(diag::err_imported_module_modmap_changed)
3396 << F.ModuleName << ImportedBy->FileName
3397 << ModMap->getName() << F.ModuleMapPath;
3398 return OutOfDate;
3399 }
3400
3401 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3402 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3403 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003404 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003405 const FileEntry *F =
3406 FileMgr.getFile(Filename, false, false);
3407 if (F == nullptr) {
3408 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3409 Error("could not find file '" + Filename +"' referenced by AST file");
3410 return OutOfDate;
3411 }
3412 AdditionalStoredMaps.insert(F);
3413 }
3414
3415 // Check any additional module map files (e.g. module.private.modulemap)
3416 // that are not in the pcm.
3417 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3418 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3419 // Remove files that match
3420 // Note: SmallPtrSet::erase is really remove
3421 if (!AdditionalStoredMaps.erase(ModMap)) {
3422 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3423 Diag(diag::err_module_different_modmap)
3424 << F.ModuleName << /*new*/0 << ModMap->getName();
3425 return OutOfDate;
3426 }
3427 }
3428 }
3429
3430 // Check any additional module map files that are in the pcm, but not
3431 // found in header search. Cases that match are already removed.
3432 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3433 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3434 Diag(diag::err_module_different_modmap)
3435 << F.ModuleName << /*not new*/1 << ModMap->getName();
3436 return OutOfDate;
3437 }
Ben Langmuir18dd78a2015-02-12 21:51:31 +00003438
3439 // Check whether the 'IsSystem' bit changed.
3440 if (M->IsSystem != static_cast<bool>(Record[Idx])) {
3441 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3442 Diag(diag::err_module_system_change) << F.ModuleName << M->IsSystem;
3443 return OutOfDate;
3444 }
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003445 }
3446
3447 if (Listener)
3448 Listener->ReadModuleMapFile(F.ModuleMapPath);
3449 return Success;
3450}
3451
3452
Douglas Gregorc1489562013-02-12 23:36:21 +00003453/// \brief Move the given method to the back of the global list of methods.
3454static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3455 // Find the entry for this selector in the method pool.
3456 Sema::GlobalMethodPool::iterator Known
3457 = S.MethodPool.find(Method->getSelector());
3458 if (Known == S.MethodPool.end())
3459 return;
3460
3461 // Retrieve the appropriate method list.
3462 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3463 : Known->second.second;
3464 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003465 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003466 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003467 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003468 Found = true;
3469 } else {
3470 // Keep searching.
3471 continue;
3472 }
3473 }
3474
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003475 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003476 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003477 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003478 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003479 }
3480}
3481
Richard Smithe657bbd2014-07-18 22:13:40 +00003482void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3483 bool FromFinalization) {
3484 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003485 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003486 bool wasHidden = D->Hidden;
3487 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003488
Richard Smith49f906a2014-03-01 00:08:04 +00003489 if (wasHidden && SemaObj) {
3490 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3491 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003492 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003493 }
3494 }
Richard Smith49f906a2014-03-01 00:08:04 +00003495
Richard Smithe657bbd2014-07-18 22:13:40 +00003496 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3497 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003498 for (const auto &Macro : Names.HiddenMacros) {
3499 if (FromFinalization)
3500 PP.appendMacroDirective(Macro.first,
3501 Macro.second->import(PP, SourceLocation()));
3502 else
3503 installImportedMacro(Macro.first, Macro.second, Owner);
3504 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003505}
3506
Richard Smith49f906a2014-03-01 00:08:04 +00003507void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003508 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003509 SourceLocation ImportLoc,
3510 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003512 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003513 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003515 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003516
3517 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003518 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 // there is nothing more to do.
3520 continue;
3521 }
Richard Smith49f906a2014-03-01 00:08:04 +00003522
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 if (!Mod->isAvailable()) {
3524 // Modules that aren't available cannot be made visible.
3525 continue;
3526 }
3527
3528 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003529 if (NameVisibility >= Module::MacrosVisible &&
3530 Mod->NameVisibility < Module::MacrosVisible)
3531 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003533
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 // If we've already deserialized any names from this module,
3535 // mark them as visible.
3536 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3537 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003538 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003540 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3541 /*FromFinalization*/false);
3542 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3543 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003545
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003547 SmallVector<Module *, 16> Exports;
3548 Mod->getExportedModules(Exports);
3549 for (SmallVectorImpl<Module *>::iterator
3550 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3551 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003552 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003553 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003555
3556 // Detect any conflicts.
3557 if (Complain) {
3558 assert(ImportLoc.isValid() && "Missing import location");
3559 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3560 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3561 Diag(ImportLoc, diag::warn_module_conflict)
3562 << Mod->getFullModuleName()
3563 << Mod->Conflicts[I].Other->getFullModuleName()
3564 << Mod->Conflicts[I].Message;
3565 // FIXME: Need note where the other module was imported.
3566 }
3567 }
3568 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003569 }
3570}
3571
Douglas Gregore060e572013-01-25 01:03:03 +00003572bool ASTReader::loadGlobalIndex() {
3573 if (GlobalIndex)
3574 return false;
3575
3576 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3577 !Context.getLangOpts().Modules)
3578 return true;
3579
3580 // Try to load the global index.
3581 TriedLoadingGlobalIndex = true;
3582 StringRef ModuleCachePath
3583 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3584 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003585 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003586 if (!Result.first)
3587 return true;
3588
3589 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003590 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003591 return false;
3592}
3593
3594bool ASTReader::isGlobalIndexUnavailable() const {
3595 return Context.getLangOpts().Modules && UseGlobalIndex &&
3596 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3597}
3598
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003599static void updateModuleTimestamp(ModuleFile &MF) {
3600 // Overwrite the timestamp file contents so that file's mtime changes.
3601 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003602 std::error_code EC;
3603 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3604 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003605 return;
3606 OS << "Timestamp file\n";
3607}
3608
Guy Benyei11169dd2012-12-18 14:30:41 +00003609ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3610 ModuleKind Type,
3611 SourceLocation ImportLoc,
3612 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003613 llvm::SaveAndRestore<SourceLocation>
3614 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3615
Richard Smithd1c46742014-04-30 02:24:17 +00003616 // Defer any pending actions until we get to the end of reading the AST file.
3617 Deserializing AnASTFile(this);
3618
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003620 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003621
3622 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003623 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003625 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003626 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 ClientLoadCapabilities)) {
3628 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003629 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 case OutOfDate:
3631 case VersionMismatch:
3632 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003633 case HadErrors: {
3634 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3635 for (const ImportedModule &IM : Loaded)
3636 LoadedSet.insert(IM.Mod);
3637
Douglas Gregor7029ce12013-03-19 00:28:20 +00003638 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003639 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003640 Context.getLangOpts().Modules
3641 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003642 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003643
3644 // If we find that any modules are unusable, the global index is going
3645 // to be out-of-date. Just remove it.
3646 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003647 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 case Success:
3651 break;
3652 }
3653
3654 // Here comes stuff that we only do once the entire chain is loaded.
3655
3656 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003657 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3658 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 M != MEnd; ++M) {
3660 ModuleFile &F = *M->Mod;
3661
3662 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003663 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3664 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003665
3666 // Once read, set the ModuleFile bit base offset and update the size in
3667 // bits of all files we've seen.
3668 F.GlobalBitOffset = TotalModulesSizeInBits;
3669 TotalModulesSizeInBits += F.SizeInBits;
3670 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3671
3672 // Preload SLocEntries.
3673 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3674 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3675 // Load it through the SourceManager and don't call ReadSLocEntry()
3676 // directly because the entry may have already been loaded in which case
3677 // calling ReadSLocEntry() directly would trigger an assertion in
3678 // SourceManager.
3679 SourceMgr.getLoadedSLocEntryByID(Index);
3680 }
3681 }
3682
Douglas Gregor603cd862013-03-22 18:50:14 +00003683 // Setup the import locations and notify the module manager that we've
3684 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003685 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3686 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003687 M != MEnd; ++M) {
3688 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003689
3690 ModuleMgr.moduleFileAccepted(&F);
3691
3692 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003693 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 if (!M->ImportedBy)
3695 F.ImportLoc = M->ImportLoc;
3696 else
3697 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3698 M->ImportLoc.getRawEncoding());
3699 }
3700
3701 // Mark all of the identifiers in the identifier table as being out of date,
3702 // so that various accessors know to check the loaded modules when the
3703 // identifier is used.
3704 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3705 IdEnd = PP.getIdentifierTable().end();
3706 Id != IdEnd; ++Id)
3707 Id->second->setOutOfDate(true);
3708
3709 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003710 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3711 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3713 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003714
3715 switch (Unresolved.Kind) {
3716 case UnresolvedModuleRef::Conflict:
3717 if (ResolvedMod) {
3718 Module::Conflict Conflict;
3719 Conflict.Other = ResolvedMod;
3720 Conflict.Message = Unresolved.String.str();
3721 Unresolved.Mod->Conflicts.push_back(Conflict);
3722 }
3723 continue;
3724
3725 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 if (ResolvedMod)
3727 Unresolved.Mod->Imports.push_back(ResolvedMod);
3728 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003729
Douglas Gregorfb912652013-03-20 21:10:35 +00003730 case UnresolvedModuleRef::Export:
3731 if (ResolvedMod || Unresolved.IsWildcard)
3732 Unresolved.Mod->Exports.push_back(
3733 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3734 continue;
3735 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003737 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003738
3739 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3740 // Might be unnecessary as use declarations are only used to build the
3741 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003742
3743 InitializeContext();
3744
Richard Smith3d8e97e2013-10-18 06:54:39 +00003745 if (SemaObj)
3746 UpdateSema();
3747
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 if (DeserializationListener)
3749 DeserializationListener->ReaderInitialized(this);
3750
3751 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3752 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3753 PrimaryModule.OriginalSourceFileID
3754 = FileID::get(PrimaryModule.SLocEntryBaseID
3755 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3756
3757 // If this AST file is a precompiled preamble, then set the
3758 // preamble file ID of the source manager to the file source file
3759 // from which the preamble was built.
3760 if (Type == MK_Preamble) {
3761 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3762 } else if (Type == MK_MainFile) {
3763 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3764 }
3765 }
3766
3767 // For any Objective-C class definitions we have already loaded, make sure
3768 // that we load any additional categories.
3769 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3770 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3771 ObjCClassesLoaded[I],
3772 PreviousGeneration);
3773 }
Douglas Gregore060e572013-01-25 01:03:03 +00003774
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003775 if (PP.getHeaderSearchInfo()
3776 .getHeaderSearchOpts()
3777 .ModulesValidateOncePerBuildSession) {
3778 // Now we are certain that the module and all modules it depends on are
3779 // up to date. Create or update timestamp files for modules that are
3780 // located in the module cache (not for PCH files that could be anywhere
3781 // in the filesystem).
3782 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3783 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003784 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003785 updateModuleTimestamp(*M.Mod);
3786 }
3787 }
3788 }
3789
Guy Benyei11169dd2012-12-18 14:30:41 +00003790 return Success;
3791}
3792
Ben Langmuir487ea142014-10-23 18:05:36 +00003793static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3794
Guy Benyei11169dd2012-12-18 14:30:41 +00003795ASTReader::ASTReadResult
3796ASTReader::ReadASTCore(StringRef FileName,
3797 ModuleKind Type,
3798 SourceLocation ImportLoc,
3799 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003800 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003801 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003802 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 unsigned ClientLoadCapabilities) {
3804 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003805 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003806 ModuleManager::AddModuleResult AddResult
3807 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003808 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003809 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003810 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003811
Douglas Gregor7029ce12013-03-19 00:28:20 +00003812 switch (AddResult) {
3813 case ModuleManager::AlreadyLoaded:
3814 return Success;
3815
3816 case ModuleManager::NewlyLoaded:
3817 // Load module file below.
3818 break;
3819
3820 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003821 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003822 // it.
3823 if (ClientLoadCapabilities & ARR_Missing)
3824 return Missing;
3825
3826 // Otherwise, return an error.
3827 {
3828 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3829 + ErrorStr;
3830 Error(Msg);
3831 }
3832 return Failure;
3833
3834 case ModuleManager::OutOfDate:
3835 // We couldn't load the module file because it is out-of-date. If the
3836 // client can handle out-of-date, return it.
3837 if (ClientLoadCapabilities & ARR_OutOfDate)
3838 return OutOfDate;
3839
3840 // Otherwise, return an error.
3841 {
3842 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3843 + ErrorStr;
3844 Error(Msg);
3845 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 return Failure;
3847 }
3848
Douglas Gregor7029ce12013-03-19 00:28:20 +00003849 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003850
3851 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3852 // module?
3853 if (FileName != "-") {
3854 CurrentDir = llvm::sys::path::parent_path(FileName);
3855 if (CurrentDir.empty()) CurrentDir = ".";
3856 }
3857
3858 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003859 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003860 Stream.init(&F.StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003861 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3862
3863 // Sniff for the signature.
3864 if (Stream.Read(8) != 'C' ||
3865 Stream.Read(8) != 'P' ||
3866 Stream.Read(8) != 'C' ||
3867 Stream.Read(8) != 'H') {
3868 Diag(diag::err_not_a_pch_file) << FileName;
3869 return Failure;
3870 }
3871
3872 // This is used for compatibility with older PCH formats.
3873 bool HaveReadControlBlock = false;
3874
Chris Lattnerefa77172013-01-20 00:00:22 +00003875 while (1) {
3876 llvm::BitstreamEntry Entry = Stream.advance();
3877
3878 switch (Entry.Kind) {
3879 case llvm::BitstreamEntry::Error:
3880 case llvm::BitstreamEntry::EndBlock:
3881 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 Error("invalid record at top-level of AST file");
3883 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003884
3885 case llvm::BitstreamEntry::SubBlock:
3886 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 }
3888
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003890 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3892 if (Stream.ReadBlockInfoBlock()) {
3893 Error("malformed BlockInfoBlock in AST file");
3894 return Failure;
3895 }
3896 break;
3897 case CONTROL_BLOCK_ID:
3898 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003899 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003900 case Success:
3901 break;
3902
3903 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003904 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003905 case OutOfDate: return OutOfDate;
3906 case VersionMismatch: return VersionMismatch;
3907 case ConfigurationMismatch: return ConfigurationMismatch;
3908 case HadErrors: return HadErrors;
3909 }
3910 break;
3911 case AST_BLOCK_ID:
3912 if (!HaveReadControlBlock) {
3913 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003914 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 return VersionMismatch;
3916 }
3917
3918 // Record that we've loaded this module.
3919 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3920 return Success;
3921
3922 default:
3923 if (Stream.SkipBlock()) {
3924 Error("malformed block record in AST file");
3925 return Failure;
3926 }
3927 break;
3928 }
3929 }
3930
3931 return Success;
3932}
3933
3934void ASTReader::InitializeContext() {
3935 // If there's a listener, notify them that we "read" the translation unit.
3936 if (DeserializationListener)
3937 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3938 Context.getTranslationUnitDecl());
3939
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 // FIXME: Find a better way to deal with collisions between these
3941 // built-in types. Right now, we just ignore the problem.
3942
3943 // Load the special types.
3944 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3945 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3946 if (!Context.CFConstantStringTypeDecl)
3947 Context.setCFConstantStringType(GetType(String));
3948 }
3949
3950 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3951 QualType FileType = GetType(File);
3952 if (FileType.isNull()) {
3953 Error("FILE type is NULL");
3954 return;
3955 }
3956
3957 if (!Context.FILEDecl) {
3958 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3959 Context.setFILEDecl(Typedef->getDecl());
3960 else {
3961 const TagType *Tag = FileType->getAs<TagType>();
3962 if (!Tag) {
3963 Error("Invalid FILE type in AST file");
3964 return;
3965 }
3966 Context.setFILEDecl(Tag->getDecl());
3967 }
3968 }
3969 }
3970
3971 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3972 QualType Jmp_bufType = GetType(Jmp_buf);
3973 if (Jmp_bufType.isNull()) {
3974 Error("jmp_buf type is NULL");
3975 return;
3976 }
3977
3978 if (!Context.jmp_bufDecl) {
3979 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3980 Context.setjmp_bufDecl(Typedef->getDecl());
3981 else {
3982 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3983 if (!Tag) {
3984 Error("Invalid jmp_buf type in AST file");
3985 return;
3986 }
3987 Context.setjmp_bufDecl(Tag->getDecl());
3988 }
3989 }
3990 }
3991
3992 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3993 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3994 if (Sigjmp_bufType.isNull()) {
3995 Error("sigjmp_buf type is NULL");
3996 return;
3997 }
3998
3999 if (!Context.sigjmp_bufDecl) {
4000 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4001 Context.setsigjmp_bufDecl(Typedef->getDecl());
4002 else {
4003 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4004 assert(Tag && "Invalid sigjmp_buf type in AST file");
4005 Context.setsigjmp_bufDecl(Tag->getDecl());
4006 }
4007 }
4008 }
4009
4010 if (unsigned ObjCIdRedef
4011 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4012 if (Context.ObjCIdRedefinitionType.isNull())
4013 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4014 }
4015
4016 if (unsigned ObjCClassRedef
4017 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4018 if (Context.ObjCClassRedefinitionType.isNull())
4019 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4020 }
4021
4022 if (unsigned ObjCSelRedef
4023 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4024 if (Context.ObjCSelRedefinitionType.isNull())
4025 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4026 }
4027
4028 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4029 QualType Ucontext_tType = GetType(Ucontext_t);
4030 if (Ucontext_tType.isNull()) {
4031 Error("ucontext_t type is NULL");
4032 return;
4033 }
4034
4035 if (!Context.ucontext_tDecl) {
4036 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4037 Context.setucontext_tDecl(Typedef->getDecl());
4038 else {
4039 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4040 assert(Tag && "Invalid ucontext_t type in AST file");
4041 Context.setucontext_tDecl(Tag->getDecl());
4042 }
4043 }
4044 }
4045 }
4046
4047 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4048
4049 // If there were any CUDA special declarations, deserialize them.
4050 if (!CUDASpecialDeclRefs.empty()) {
4051 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4052 Context.setcudaConfigureCallDecl(
4053 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4054 }
Richard Smith56be7542014-03-21 00:33:59 +00004055
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004057 // FIXME: This does not make macro-only imports visible again. It also doesn't
4058 // make #includes mapped to module imports visible.
4059 for (auto &Import : ImportedModules) {
4060 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004061 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004062 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004063 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 }
4065 ImportedModules.clear();
4066}
4067
4068void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004069 while (!HiddenNamesMap.empty()) {
4070 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4071 HiddenNamesMap.erase(HiddenNamesMap.begin());
4072 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4073 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004075}
4076
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004077/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4078/// cursor into the start of the given block ID, returning false on success and
4079/// true on failure.
4080static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 while (1) {
4082 llvm::BitstreamEntry Entry = Cursor.advance();
4083 switch (Entry.Kind) {
4084 case llvm::BitstreamEntry::Error:
4085 case llvm::BitstreamEntry::EndBlock:
4086 return true;
4087
4088 case llvm::BitstreamEntry::Record:
4089 // Ignore top-level records.
4090 Cursor.skipRecord(Entry.ID);
4091 break;
4092
4093 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004094 if (Entry.ID == BlockID) {
4095 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 return true;
4097 // Found it!
4098 return false;
4099 }
4100
4101 if (Cursor.SkipBlock())
4102 return true;
4103 }
4104 }
4105}
4106
Ben Langmuir487ea142014-10-23 18:05:36 +00004107static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4108 BitstreamCursor Stream(StreamFile);
4109 if (Stream.Read(8) != 'C' ||
4110 Stream.Read(8) != 'P' ||
4111 Stream.Read(8) != 'C' ||
4112 Stream.Read(8) != 'H') {
4113 return 0;
4114 }
4115
4116 // Scan for the CONTROL_BLOCK_ID block.
4117 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4118 return 0;
4119
4120 // Scan for SIGNATURE inside the control block.
4121 ASTReader::RecordData Record;
4122 while (1) {
4123 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4124 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4125 Entry.Kind != llvm::BitstreamEntry::Record)
4126 return 0;
4127
4128 Record.clear();
4129 StringRef Blob;
4130 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4131 return Record[0];
4132 }
4133}
4134
Guy Benyei11169dd2012-12-18 14:30:41 +00004135/// \brief Retrieve the name of the original source file name
4136/// directly from the AST file, without actually loading the AST
4137/// file.
4138std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4139 FileManager &FileMgr,
4140 DiagnosticsEngine &Diags) {
4141 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004142 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004144 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4145 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 return std::string();
4147 }
4148
4149 // Initialize the stream
4150 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004151 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4152 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004153 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004154
4155 // Sniff for the signature.
4156 if (Stream.Read(8) != 'C' ||
4157 Stream.Read(8) != 'P' ||
4158 Stream.Read(8) != 'C' ||
4159 Stream.Read(8) != 'H') {
4160 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4161 return std::string();
4162 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004163
Chris Lattnere7b154b2013-01-19 21:39:22 +00004164 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004165 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004166 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4167 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004170 // Scan for ORIGINAL_FILE inside the control block.
4171 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004172 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004173 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004174 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4175 return std::string();
4176
4177 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4178 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4179 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004180 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004181
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004183 StringRef Blob;
4184 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4185 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004187}
4188
4189namespace {
4190 class SimplePCHValidator : public ASTReaderListener {
4191 const LangOptions &ExistingLangOpts;
4192 const TargetOptions &ExistingTargetOpts;
4193 const PreprocessorOptions &ExistingPPOpts;
4194 FileManager &FileMgr;
4195
4196 public:
4197 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4198 const TargetOptions &ExistingTargetOpts,
4199 const PreprocessorOptions &ExistingPPOpts,
4200 FileManager &FileMgr)
4201 : ExistingLangOpts(ExistingLangOpts),
4202 ExistingTargetOpts(ExistingTargetOpts),
4203 ExistingPPOpts(ExistingPPOpts),
4204 FileMgr(FileMgr)
4205 {
4206 }
4207
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004208 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4209 bool AllowCompatibleDifferences) override {
4210 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4211 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004213 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4214 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004215 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004217 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4218 bool Complain,
4219 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004220 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004221 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 }
4223 };
4224}
4225
4226bool ASTReader::readASTFileControlBlock(StringRef Filename,
4227 FileManager &FileMgr,
4228 ASTReaderListener &Listener) {
4229 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004230 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 if (!Buffer) {
4232 return true;
4233 }
4234
4235 // Initialize the stream
4236 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004237 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4238 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004239 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004240
4241 // Sniff for the signature.
4242 if (Stream.Read(8) != 'C' ||
4243 Stream.Read(8) != 'P' ||
4244 Stream.Read(8) != 'C' ||
4245 Stream.Read(8) != 'H') {
4246 return true;
4247 }
4248
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004249 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004250 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004251 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004252
4253 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004254 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004255 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004256 BitstreamCursor InputFilesCursor;
4257 if (NeedsInputFiles) {
4258 InputFilesCursor = Stream;
4259 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4260 return true;
4261
4262 // Read the abbreviations
4263 while (true) {
4264 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4265 unsigned Code = InputFilesCursor.ReadCode();
4266
4267 // We expect all abbrevs to be at the start of the block.
4268 if (Code != llvm::bitc::DEFINE_ABBREV) {
4269 InputFilesCursor.JumpToBit(Offset);
4270 break;
4271 }
4272 InputFilesCursor.ReadAbbrevRecord();
4273 }
4274 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004275
4276 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004278 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004279 while (1) {
4280 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4281 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4282 return false;
4283
4284 if (Entry.Kind != llvm::BitstreamEntry::Record)
4285 return true;
4286
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004288 StringRef Blob;
4289 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004290 switch ((ControlRecordTypes)RecCode) {
4291 case METADATA: {
4292 if (Record[0] != VERSION_MAJOR)
4293 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004295 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004296 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004297
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004298 break;
4299 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004300 case MODULE_NAME:
4301 Listener.ReadModuleName(Blob);
4302 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004303 case MODULE_DIRECTORY:
4304 ModuleDir = Blob;
4305 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004306 case MODULE_MAP_FILE: {
4307 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004308 auto Path = ReadString(Record, Idx);
4309 ResolveImportedPath(Path, ModuleDir);
4310 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004311 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004312 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004313 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004314 if (ParseLanguageOptions(Record, false, Listener,
4315 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004316 return true;
4317 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004318
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004319 case TARGET_OPTIONS:
4320 if (ParseTargetOptions(Record, false, Listener))
4321 return true;
4322 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004323
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004324 case DIAGNOSTIC_OPTIONS:
4325 if (ParseDiagnosticOptions(Record, false, Listener))
4326 return true;
4327 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004329 case FILE_SYSTEM_OPTIONS:
4330 if (ParseFileSystemOptions(Record, false, Listener))
4331 return true;
4332 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004333
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004334 case HEADER_SEARCH_OPTIONS:
4335 if (ParseHeaderSearchOptions(Record, false, Listener))
4336 return true;
4337 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004338
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004339 case PREPROCESSOR_OPTIONS: {
4340 std::string IgnoredSuggestedPredefines;
4341 if (ParsePreprocessorOptions(Record, false, Listener,
4342 IgnoredSuggestedPredefines))
4343 return true;
4344 break;
4345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004346
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004347 case INPUT_FILE_OFFSETS: {
4348 if (!NeedsInputFiles)
4349 break;
4350
4351 unsigned NumInputFiles = Record[0];
4352 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004353 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004354 for (unsigned I = 0; I != NumInputFiles; ++I) {
4355 // Go find this input file.
4356 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004357
4358 if (isSystemFile && !NeedsSystemInputFiles)
4359 break; // the rest are system input files
4360
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004361 BitstreamCursor &Cursor = InputFilesCursor;
4362 SavedStreamPosition SavedPosition(Cursor);
4363 Cursor.JumpToBit(InputFileOffs[I]);
4364
4365 unsigned Code = Cursor.ReadCode();
4366 RecordData Record;
4367 StringRef Blob;
4368 bool shouldContinue = false;
4369 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4370 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004371 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004372 std::string Filename = Blob;
4373 ResolveImportedPath(Filename, ModuleDir);
4374 shouldContinue =
4375 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004376 break;
4377 }
4378 if (!shouldContinue)
4379 break;
4380 }
4381 break;
4382 }
4383
Richard Smithd4b230b2014-10-27 23:01:16 +00004384 case IMPORTS: {
4385 if (!NeedsImports)
4386 break;
4387
4388 unsigned Idx = 0, N = Record.size();
4389 while (Idx < N) {
4390 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004391 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004392 std::string Filename = ReadString(Record, Idx);
4393 ResolveImportedPath(Filename, ModuleDir);
4394 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004395 }
4396 break;
4397 }
4398
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004399 default:
4400 // No other validation to perform.
4401 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 }
4403 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004404}
4405
4406
4407bool ASTReader::isAcceptableASTFile(StringRef Filename,
4408 FileManager &FileMgr,
4409 const LangOptions &LangOpts,
4410 const TargetOptions &TargetOpts,
4411 const PreprocessorOptions &PPOpts) {
4412 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4413 return !readASTFileControlBlock(Filename, FileMgr, validator);
4414}
4415
Ben Langmuir2c9af442014-04-10 17:57:43 +00004416ASTReader::ASTReadResult
4417ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 // Enter the submodule block.
4419 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4420 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
4423
4424 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4425 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004426 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 RecordData Record;
4428 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004429 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4430
4431 switch (Entry.Kind) {
4432 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4433 case llvm::BitstreamEntry::Error:
4434 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004435 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004436 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004437 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004438 case llvm::BitstreamEntry::Record:
4439 // The interesting case.
4440 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004444 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004446 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4447
4448 if ((Kind == SUBMODULE_METADATA) != First) {
4449 Error("submodule metadata record should be at beginning of block");
4450 return Failure;
4451 }
4452 First = false;
4453
4454 // Submodule information is only valid if we have a current module.
4455 // FIXME: Should we error on these cases?
4456 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4457 Kind != SUBMODULE_DEFINITION)
4458 continue;
4459
4460 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 default: // Default behavior: ignore.
4462 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463
Richard Smith03478d92014-10-23 22:12:14 +00004464 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004465 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004467 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 }
Richard Smith03478d92014-10-23 22:12:14 +00004469
Chris Lattner0e6c9402013-01-20 02:38:54 +00004470 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004471 unsigned Idx = 0;
4472 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4473 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4474 bool IsFramework = Record[Idx++];
4475 bool IsExplicit = Record[Idx++];
4476 bool IsSystem = Record[Idx++];
4477 bool IsExternC = Record[Idx++];
4478 bool InferSubmodules = Record[Idx++];
4479 bool InferExplicitSubmodules = Record[Idx++];
4480 bool InferExportWildcard = Record[Idx++];
4481 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004482
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004483 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004484 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 // Retrieve this (sub)module from the module map, creating it if
4488 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004489 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004491
4492 // FIXME: set the definition loc for CurrentModule, or call
4493 // ModMap.setInferredModuleAllowedBy()
4494
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4496 if (GlobalIndex >= SubmodulesLoaded.size() ||
4497 SubmodulesLoaded[GlobalIndex]) {
4498 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004499 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004501
Douglas Gregor7029ce12013-03-19 00:28:20 +00004502 if (!ParentModule) {
4503 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4504 if (CurFile != F.File) {
4505 if (!Diags.isDiagnosticInFlight()) {
4506 Diag(diag::err_module_file_conflict)
4507 << CurrentModule->getTopLevelModuleName()
4508 << CurFile->getName()
4509 << F.File->getName();
4510 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004511 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004512 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004513 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004514
4515 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004516 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004517
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 CurrentModule->IsFromModuleFile = true;
4519 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004520 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 CurrentModule->InferSubmodules = InferSubmodules;
4522 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4523 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004524 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 if (DeserializationListener)
4526 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4527
4528 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004529
Douglas Gregorfb912652013-03-20 21:10:35 +00004530 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004531 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004532 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004533 CurrentModule->UnresolvedConflicts.clear();
4534 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 break;
4536 }
4537
4538 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004539 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 if (!CurrentModule->getUmbrellaHeader())
4541 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4542 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004543 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4544 Error("mismatched umbrella headers in submodule");
4545 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547 }
4548 break;
4549 }
4550
Richard Smith202210b2014-10-24 20:23:01 +00004551 case SUBMODULE_HEADER:
4552 case SUBMODULE_EXCLUDED_HEADER:
4553 case SUBMODULE_PRIVATE_HEADER:
4554 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004555 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4556 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004557 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004558
Richard Smith202210b2014-10-24 20:23:01 +00004559 case SUBMODULE_TEXTUAL_HEADER:
4560 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4561 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4562 // them here.
4563 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004564
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004566 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004567 break;
4568 }
4569
4570 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004572 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004573 if (!CurrentModule->getUmbrellaDir())
4574 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4575 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004576 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4577 Error("mismatched umbrella directories in submodule");
4578 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 }
4580 }
4581 break;
4582 }
4583
4584 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 F.BaseSubmoduleID = getTotalNumSubmodules();
4586 F.LocalNumSubmodules = Record[0];
4587 unsigned LocalBaseSubmoduleID = Record[1];
4588 if (F.LocalNumSubmodules > 0) {
4589 // Introduce the global -> local mapping for submodules within this
4590 // module.
4591 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4592
4593 // Introduce the local -> global mapping for submodules within this
4594 // module.
4595 F.SubmoduleRemap.insertOrReplace(
4596 std::make_pair(LocalBaseSubmoduleID,
4597 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004598
Ben Langmuir52ca6782014-10-20 16:27:32 +00004599 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 break;
4602 }
4603
4604 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004606 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 Unresolved.File = &F;
4608 Unresolved.Mod = CurrentModule;
4609 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004610 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004612 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 }
4614 break;
4615 }
4616
4617 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004619 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 Unresolved.File = &F;
4621 Unresolved.Mod = CurrentModule;
4622 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004623 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004624 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004625 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627
4628 // Once we've loaded the set of exports, there's no reason to keep
4629 // the parsed, unresolved exports around.
4630 CurrentModule->UnresolvedExports.clear();
4631 break;
4632 }
4633 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004634 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 Context.getTargetInfo());
4636 break;
4637 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004638
4639 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004640 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004641 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004642 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004643
4644 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004645 CurrentModule->ConfigMacros.push_back(Blob.str());
4646 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004647
4648 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004649 UnresolvedModuleRef Unresolved;
4650 Unresolved.File = &F;
4651 Unresolved.Mod = CurrentModule;
4652 Unresolved.ID = Record[0];
4653 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4654 Unresolved.IsWildcard = false;
4655 Unresolved.String = Blob;
4656 UnresolvedModuleRefs.push_back(Unresolved);
4657 break;
4658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 }
4660 }
4661}
4662
4663/// \brief Parse the record that corresponds to a LangOptions data
4664/// structure.
4665///
4666/// This routine parses the language options from the AST file and then gives
4667/// them to the AST listener if one is set.
4668///
4669/// \returns true if the listener deems the file unacceptable, false otherwise.
4670bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4671 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004672 ASTReaderListener &Listener,
4673 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 LangOptions LangOpts;
4675 unsigned Idx = 0;
4676#define LANGOPT(Name, Bits, Default, Description) \
4677 LangOpts.Name = Record[Idx++];
4678#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4679 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4680#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004681#define SANITIZER(NAME, ID) \
4682 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004683#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004684
4685 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4686 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4687 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4688
4689 unsigned Length = Record[Idx++];
4690 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4691 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004692
4693 Idx += Length;
4694
4695 // Comment options.
4696 for (unsigned N = Record[Idx++]; N; --N) {
4697 LangOpts.CommentOpts.BlockCommandNames.push_back(
4698 ReadString(Record, Idx));
4699 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004700 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004701
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004702 return Listener.ReadLanguageOptions(LangOpts, Complain,
4703 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004704}
4705
4706bool ASTReader::ParseTargetOptions(const RecordData &Record,
4707 bool Complain,
4708 ASTReaderListener &Listener) {
4709 unsigned Idx = 0;
4710 TargetOptions TargetOpts;
4711 TargetOpts.Triple = ReadString(Record, Idx);
4712 TargetOpts.CPU = ReadString(Record, Idx);
4713 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 for (unsigned N = Record[Idx++]; N; --N) {
4715 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4716 }
4717 for (unsigned N = Record[Idx++]; N; --N) {
4718 TargetOpts.Features.push_back(ReadString(Record, Idx));
4719 }
4720
4721 return Listener.ReadTargetOptions(TargetOpts, Complain);
4722}
4723
4724bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4725 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004726 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004728#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004729#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004730 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004731#include "clang/Basic/DiagnosticOptions.def"
4732
Richard Smith3be1cb22014-08-07 00:24:21 +00004733 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004734 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004735 for (unsigned N = Record[Idx++]; N; --N)
4736 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004737
4738 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4739}
4740
4741bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4742 ASTReaderListener &Listener) {
4743 FileSystemOptions FSOpts;
4744 unsigned Idx = 0;
4745 FSOpts.WorkingDir = ReadString(Record, Idx);
4746 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4747}
4748
4749bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4750 bool Complain,
4751 ASTReaderListener &Listener) {
4752 HeaderSearchOptions HSOpts;
4753 unsigned Idx = 0;
4754 HSOpts.Sysroot = ReadString(Record, Idx);
4755
4756 // Include entries.
4757 for (unsigned N = Record[Idx++]; N; --N) {
4758 std::string Path = ReadString(Record, Idx);
4759 frontend::IncludeDirGroup Group
4760 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 bool IsFramework = Record[Idx++];
4762 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004764 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 }
4766
4767 // System header prefixes.
4768 for (unsigned N = Record[Idx++]; N; --N) {
4769 std::string Prefix = ReadString(Record, Idx);
4770 bool IsSystemHeader = Record[Idx++];
4771 HSOpts.SystemHeaderPrefixes.push_back(
4772 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4773 }
4774
4775 HSOpts.ResourceDir = ReadString(Record, Idx);
4776 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004777 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 HSOpts.DisableModuleHash = Record[Idx++];
4779 HSOpts.UseBuiltinIncludes = Record[Idx++];
4780 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4781 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4782 HSOpts.UseLibcxx = Record[Idx++];
4783
4784 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4785}
4786
4787bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4788 bool Complain,
4789 ASTReaderListener &Listener,
4790 std::string &SuggestedPredefines) {
4791 PreprocessorOptions PPOpts;
4792 unsigned Idx = 0;
4793
4794 // Macro definitions/undefs
4795 for (unsigned N = Record[Idx++]; N; --N) {
4796 std::string Macro = ReadString(Record, Idx);
4797 bool IsUndef = Record[Idx++];
4798 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4799 }
4800
4801 // Includes
4802 for (unsigned N = Record[Idx++]; N; --N) {
4803 PPOpts.Includes.push_back(ReadString(Record, Idx));
4804 }
4805
4806 // Macro Includes
4807 for (unsigned N = Record[Idx++]; N; --N) {
4808 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4809 }
4810
4811 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004812 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4814 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4815 PPOpts.ObjCXXARCStandardLibrary =
4816 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4817 SuggestedPredefines.clear();
4818 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4819 SuggestedPredefines);
4820}
4821
4822std::pair<ModuleFile *, unsigned>
4823ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4824 GlobalPreprocessedEntityMapType::iterator
4825 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4826 assert(I != GlobalPreprocessedEntityMap.end() &&
4827 "Corrupted global preprocessed entity map");
4828 ModuleFile *M = I->second;
4829 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4830 return std::make_pair(M, LocalIndex);
4831}
4832
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004833llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004834ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4835 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4836 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4837 Mod.NumPreprocessedEntities);
4838
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004839 return llvm::make_range(PreprocessingRecord::iterator(),
4840 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004841}
4842
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004843llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004844ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004845 return llvm::make_range(
4846 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4847 ModuleDeclIterator(this, &Mod,
4848 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004849}
4850
4851PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4852 PreprocessedEntityID PPID = Index+1;
4853 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4854 ModuleFile &M = *PPInfo.first;
4855 unsigned LocalIndex = PPInfo.second;
4856 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4857
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 if (!PP.getPreprocessingRecord()) {
4859 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004860 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 }
4862
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004863 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4864 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4865
4866 llvm::BitstreamEntry Entry =
4867 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4868 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004869 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004870
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 // Read the record.
4872 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4873 ReadSourceLocation(M, PPOffs.End));
4874 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004875 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 RecordData Record;
4877 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004878 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4879 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 switch (RecType) {
4881 case PPD_MACRO_EXPANSION: {
4882 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004883 IdentifierInfo *Name = nullptr;
4884 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 if (isBuiltin)
4886 Name = getLocalIdentifier(M, Record[1]);
4887 else {
4888 PreprocessedEntityID
4889 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4890 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4891 }
4892
4893 MacroExpansion *ME;
4894 if (isBuiltin)
4895 ME = new (PPRec) MacroExpansion(Name, Range);
4896 else
4897 ME = new (PPRec) MacroExpansion(Def, Range);
4898
4899 return ME;
4900 }
4901
4902 case PPD_MACRO_DEFINITION: {
4903 // Decode the identifier info and then check again; if the macro is
4904 // still defined and associated with the identifier,
4905 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4906 MacroDefinition *MD
4907 = new (PPRec) MacroDefinition(II, Range);
4908
4909 if (DeserializationListener)
4910 DeserializationListener->MacroDefinitionRead(PPID, MD);
4911
4912 return MD;
4913 }
4914
4915 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004916 const char *FullFileNameStart = Blob.data() + Record[0];
4917 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004918 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 if (!FullFileName.empty())
4920 File = PP.getFileManager().getFile(FullFileName);
4921
4922 // FIXME: Stable encoding
4923 InclusionDirective::InclusionKind Kind
4924 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4925 InclusionDirective *ID
4926 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004927 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 Record[1], Record[3],
4929 File,
4930 Range);
4931 return ID;
4932 }
4933 }
4934
4935 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4936}
4937
4938/// \brief \arg SLocMapI points at a chunk of a module that contains no
4939/// preprocessed entities or the entities it contains are not the ones we are
4940/// looking for. Find the next module that contains entities and return the ID
4941/// of the first entry.
4942PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4943 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4944 ++SLocMapI;
4945 for (GlobalSLocOffsetMapType::const_iterator
4946 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4947 ModuleFile &M = *SLocMapI->second;
4948 if (M.NumPreprocessedEntities)
4949 return M.BasePreprocessedEntityID;
4950 }
4951
4952 return getTotalNumPreprocessedEntities();
4953}
4954
4955namespace {
4956
4957template <unsigned PPEntityOffset::*PPLoc>
4958struct PPEntityComp {
4959 const ASTReader &Reader;
4960 ModuleFile &M;
4961
4962 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4963
4964 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4965 SourceLocation LHS = getLoc(L);
4966 SourceLocation RHS = getLoc(R);
4967 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4968 }
4969
4970 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4971 SourceLocation LHS = getLoc(L);
4972 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4973 }
4974
4975 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4976 SourceLocation RHS = getLoc(R);
4977 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4978 }
4979
4980 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4981 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4982 }
4983};
4984
4985}
4986
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004987PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4988 bool EndsAfter) const {
4989 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 return getTotalNumPreprocessedEntities();
4991
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004992 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4993 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004994 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4995 "Corrupted global sloc offset map");
4996
4997 if (SLocMapI->second->NumPreprocessedEntities == 0)
4998 return findNextPreprocessedEntity(SLocMapI);
4999
5000 ModuleFile &M = *SLocMapI->second;
5001 typedef const PPEntityOffset *pp_iterator;
5002 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5003 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5004
5005 size_t Count = M.NumPreprocessedEntities;
5006 size_t Half;
5007 pp_iterator First = pp_begin;
5008 pp_iterator PPI;
5009
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005010 if (EndsAfter) {
5011 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5012 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5013 } else {
5014 // Do a binary search manually instead of using std::lower_bound because
5015 // The end locations of entities may be unordered (when a macro expansion
5016 // is inside another macro argument), but for this case it is not important
5017 // whether we get the first macro expansion or its containing macro.
5018 while (Count > 0) {
5019 Half = Count / 2;
5020 PPI = First;
5021 std::advance(PPI, Half);
5022 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5023 Loc)) {
5024 First = PPI;
5025 ++First;
5026 Count = Count - Half - 1;
5027 } else
5028 Count = Half;
5029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 }
5031
5032 if (PPI == pp_end)
5033 return findNextPreprocessedEntity(SLocMapI);
5034
5035 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5036}
5037
Guy Benyei11169dd2012-12-18 14:30:41 +00005038/// \brief Returns a pair of [Begin, End) indices of preallocated
5039/// preprocessed entities that \arg Range encompasses.
5040std::pair<unsigned, unsigned>
5041 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5042 if (Range.isInvalid())
5043 return std::make_pair(0,0);
5044 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5045
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005046 PreprocessedEntityID BeginID =
5047 findPreprocessedEntity(Range.getBegin(), false);
5048 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 return std::make_pair(BeginID, EndID);
5050}
5051
5052/// \brief Optionally returns true or false if the preallocated preprocessed
5053/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005054Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 FileID FID) {
5056 if (FID.isInvalid())
5057 return false;
5058
5059 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5060 ModuleFile &M = *PPInfo.first;
5061 unsigned LocalIndex = PPInfo.second;
5062 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5063
5064 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5065 if (Loc.isInvalid())
5066 return false;
5067
5068 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5069 return true;
5070 else
5071 return false;
5072}
5073
5074namespace {
5075 /// \brief Visitor used to search for information about a header file.
5076 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 const FileEntry *FE;
5078
David Blaikie05785d12013-02-20 22:23:23 +00005079 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005080
5081 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005082 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5083 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005084
5085 static bool visit(ModuleFile &M, void *UserData) {
5086 HeaderFileInfoVisitor *This
5087 = static_cast<HeaderFileInfoVisitor *>(UserData);
5088
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 HeaderFileInfoLookupTable *Table
5090 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5091 if (!Table)
5092 return false;
5093
5094 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005095 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005096 if (Pos == Table->end())
5097 return false;
5098
5099 This->HFI = *Pos;
5100 return true;
5101 }
5102
David Blaikie05785d12013-02-20 22:23:23 +00005103 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 };
5105}
5106
5107HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005108 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005109 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005110 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005112
5113 return HeaderFileInfo();
5114}
5115
5116void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5117 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005118 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5120 ModuleFile &F = *(*I);
5121 unsigned Idx = 0;
5122 DiagStates.clear();
5123 assert(!Diag.DiagStates.empty());
5124 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5125 while (Idx < F.PragmaDiagMappings.size()) {
5126 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5127 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5128 if (DiagStateID != 0) {
5129 Diag.DiagStatePoints.push_back(
5130 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5131 FullSourceLoc(Loc, SourceMgr)));
5132 continue;
5133 }
5134
5135 assert(DiagStateID == 0);
5136 // A new DiagState was created here.
5137 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5138 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5139 DiagStates.push_back(NewState);
5140 Diag.DiagStatePoints.push_back(
5141 DiagnosticsEngine::DiagStatePoint(NewState,
5142 FullSourceLoc(Loc, SourceMgr)));
5143 while (1) {
5144 assert(Idx < F.PragmaDiagMappings.size() &&
5145 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5146 if (Idx >= F.PragmaDiagMappings.size()) {
5147 break; // Something is messed up but at least avoid infinite loop in
5148 // release build.
5149 }
5150 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5151 if (DiagID == (unsigned)-1) {
5152 break; // no more diag/map pairs for this location.
5153 }
Alp Tokerc726c362014-06-10 09:31:37 +00005154 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5155 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5156 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 }
5158 }
5159 }
5160}
5161
5162/// \brief Get the correct cursor and offset for loading a type.
5163ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5164 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5165 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5166 ModuleFile *M = I->second;
5167 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5168}
5169
5170/// \brief Read and return the type with the given index..
5171///
5172/// The index is the type ID, shifted and minus the number of predefs. This
5173/// routine actually reads the record corresponding to the type at the given
5174/// location. It is a helper routine for GetType, which deals with reading type
5175/// IDs.
5176QualType ASTReader::readTypeRecord(unsigned Index) {
5177 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005178 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005179
5180 // Keep track of where we are in the stream, then jump back there
5181 // after reading this type.
5182 SavedStreamPosition SavedPosition(DeclsCursor);
5183
5184 ReadingKindTracker ReadingKind(Read_Type, *this);
5185
5186 // Note that we are loading a type record.
5187 Deserializing AType(this);
5188
5189 unsigned Idx = 0;
5190 DeclsCursor.JumpToBit(Loc.Offset);
5191 RecordData Record;
5192 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005193 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005194 case TYPE_EXT_QUAL: {
5195 if (Record.size() != 2) {
5196 Error("Incorrect encoding of extended qualifier type");
5197 return QualType();
5198 }
5199 QualType Base = readType(*Loc.F, Record, Idx);
5200 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5201 return Context.getQualifiedType(Base, Quals);
5202 }
5203
5204 case TYPE_COMPLEX: {
5205 if (Record.size() != 1) {
5206 Error("Incorrect encoding of complex type");
5207 return QualType();
5208 }
5209 QualType ElemType = readType(*Loc.F, Record, Idx);
5210 return Context.getComplexType(ElemType);
5211 }
5212
5213 case TYPE_POINTER: {
5214 if (Record.size() != 1) {
5215 Error("Incorrect encoding of pointer type");
5216 return QualType();
5217 }
5218 QualType PointeeType = readType(*Loc.F, Record, Idx);
5219 return Context.getPointerType(PointeeType);
5220 }
5221
Reid Kleckner8a365022013-06-24 17:51:48 +00005222 case TYPE_DECAYED: {
5223 if (Record.size() != 1) {
5224 Error("Incorrect encoding of decayed type");
5225 return QualType();
5226 }
5227 QualType OriginalType = readType(*Loc.F, Record, Idx);
5228 QualType DT = Context.getAdjustedParameterType(OriginalType);
5229 if (!isa<DecayedType>(DT))
5230 Error("Decayed type does not decay");
5231 return DT;
5232 }
5233
Reid Kleckner0503a872013-12-05 01:23:43 +00005234 case TYPE_ADJUSTED: {
5235 if (Record.size() != 2) {
5236 Error("Incorrect encoding of adjusted type");
5237 return QualType();
5238 }
5239 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5240 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5241 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5242 }
5243
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 case TYPE_BLOCK_POINTER: {
5245 if (Record.size() != 1) {
5246 Error("Incorrect encoding of block pointer type");
5247 return QualType();
5248 }
5249 QualType PointeeType = readType(*Loc.F, Record, Idx);
5250 return Context.getBlockPointerType(PointeeType);
5251 }
5252
5253 case TYPE_LVALUE_REFERENCE: {
5254 if (Record.size() != 2) {
5255 Error("Incorrect encoding of lvalue reference type");
5256 return QualType();
5257 }
5258 QualType PointeeType = readType(*Loc.F, Record, Idx);
5259 return Context.getLValueReferenceType(PointeeType, Record[1]);
5260 }
5261
5262 case TYPE_RVALUE_REFERENCE: {
5263 if (Record.size() != 1) {
5264 Error("Incorrect encoding of rvalue reference type");
5265 return QualType();
5266 }
5267 QualType PointeeType = readType(*Loc.F, Record, Idx);
5268 return Context.getRValueReferenceType(PointeeType);
5269 }
5270
5271 case TYPE_MEMBER_POINTER: {
5272 if (Record.size() != 2) {
5273 Error("Incorrect encoding of member pointer type");
5274 return QualType();
5275 }
5276 QualType PointeeType = readType(*Loc.F, Record, Idx);
5277 QualType ClassType = readType(*Loc.F, Record, Idx);
5278 if (PointeeType.isNull() || ClassType.isNull())
5279 return QualType();
5280
5281 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5282 }
5283
5284 case TYPE_CONSTANT_ARRAY: {
5285 QualType ElementType = readType(*Loc.F, Record, Idx);
5286 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5287 unsigned IndexTypeQuals = Record[2];
5288 unsigned Idx = 3;
5289 llvm::APInt Size = ReadAPInt(Record, Idx);
5290 return Context.getConstantArrayType(ElementType, Size,
5291 ASM, IndexTypeQuals);
5292 }
5293
5294 case TYPE_INCOMPLETE_ARRAY: {
5295 QualType ElementType = readType(*Loc.F, Record, Idx);
5296 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5297 unsigned IndexTypeQuals = Record[2];
5298 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5299 }
5300
5301 case TYPE_VARIABLE_ARRAY: {
5302 QualType ElementType = readType(*Loc.F, Record, Idx);
5303 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5304 unsigned IndexTypeQuals = Record[2];
5305 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5306 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5307 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5308 ASM, IndexTypeQuals,
5309 SourceRange(LBLoc, RBLoc));
5310 }
5311
5312 case TYPE_VECTOR: {
5313 if (Record.size() != 3) {
5314 Error("incorrect encoding of vector type in AST file");
5315 return QualType();
5316 }
5317
5318 QualType ElementType = readType(*Loc.F, Record, Idx);
5319 unsigned NumElements = Record[1];
5320 unsigned VecKind = Record[2];
5321 return Context.getVectorType(ElementType, NumElements,
5322 (VectorType::VectorKind)VecKind);
5323 }
5324
5325 case TYPE_EXT_VECTOR: {
5326 if (Record.size() != 3) {
5327 Error("incorrect encoding of extended vector type in AST file");
5328 return QualType();
5329 }
5330
5331 QualType ElementType = readType(*Loc.F, Record, Idx);
5332 unsigned NumElements = Record[1];
5333 return Context.getExtVectorType(ElementType, NumElements);
5334 }
5335
5336 case TYPE_FUNCTION_NO_PROTO: {
5337 if (Record.size() != 6) {
5338 Error("incorrect encoding of no-proto function type");
5339 return QualType();
5340 }
5341 QualType ResultType = readType(*Loc.F, Record, Idx);
5342 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5343 (CallingConv)Record[4], Record[5]);
5344 return Context.getFunctionNoProtoType(ResultType, Info);
5345 }
5346
5347 case TYPE_FUNCTION_PROTO: {
5348 QualType ResultType = readType(*Loc.F, Record, Idx);
5349
5350 FunctionProtoType::ExtProtoInfo EPI;
5351 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5352 /*hasregparm*/ Record[2],
5353 /*regparm*/ Record[3],
5354 static_cast<CallingConv>(Record[4]),
5355 /*produces*/ Record[5]);
5356
5357 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005358
5359 EPI.Variadic = Record[Idx++];
5360 EPI.HasTrailingReturn = Record[Idx++];
5361 EPI.TypeQuals = Record[Idx++];
5362 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005363 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005364 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005365
5366 unsigned NumParams = Record[Idx++];
5367 SmallVector<QualType, 16> ParamTypes;
5368 for (unsigned I = 0; I != NumParams; ++I)
5369 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5370
Jordan Rose5c382722013-03-08 21:51:21 +00005371 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 }
5373
5374 case TYPE_UNRESOLVED_USING: {
5375 unsigned Idx = 0;
5376 return Context.getTypeDeclType(
5377 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5378 }
5379
5380 case TYPE_TYPEDEF: {
5381 if (Record.size() != 2) {
5382 Error("incorrect encoding of typedef type");
5383 return QualType();
5384 }
5385 unsigned Idx = 0;
5386 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5387 QualType Canonical = readType(*Loc.F, Record, Idx);
5388 if (!Canonical.isNull())
5389 Canonical = Context.getCanonicalType(Canonical);
5390 return Context.getTypedefType(Decl, Canonical);
5391 }
5392
5393 case TYPE_TYPEOF_EXPR:
5394 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5395
5396 case TYPE_TYPEOF: {
5397 if (Record.size() != 1) {
5398 Error("incorrect encoding of typeof(type) in AST file");
5399 return QualType();
5400 }
5401 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5402 return Context.getTypeOfType(UnderlyingType);
5403 }
5404
5405 case TYPE_DECLTYPE: {
5406 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5407 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5408 }
5409
5410 case TYPE_UNARY_TRANSFORM: {
5411 QualType BaseType = readType(*Loc.F, Record, Idx);
5412 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5413 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5414 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5415 }
5416
Richard Smith74aeef52013-04-26 16:15:35 +00005417 case TYPE_AUTO: {
5418 QualType Deduced = readType(*Loc.F, Record, Idx);
5419 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005420 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005421 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005423
5424 case TYPE_RECORD: {
5425 if (Record.size() != 2) {
5426 Error("incorrect encoding of record type");
5427 return QualType();
5428 }
5429 unsigned Idx = 0;
5430 bool IsDependent = Record[Idx++];
5431 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5432 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5433 QualType T = Context.getRecordType(RD);
5434 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5435 return T;
5436 }
5437
5438 case TYPE_ENUM: {
5439 if (Record.size() != 2) {
5440 Error("incorrect encoding of enum type");
5441 return QualType();
5442 }
5443 unsigned Idx = 0;
5444 bool IsDependent = Record[Idx++];
5445 QualType T
5446 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5447 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5448 return T;
5449 }
5450
5451 case TYPE_ATTRIBUTED: {
5452 if (Record.size() != 3) {
5453 Error("incorrect encoding of attributed type");
5454 return QualType();
5455 }
5456 QualType modifiedType = readType(*Loc.F, Record, Idx);
5457 QualType equivalentType = readType(*Loc.F, Record, Idx);
5458 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5459 return Context.getAttributedType(kind, modifiedType, equivalentType);
5460 }
5461
5462 case TYPE_PAREN: {
5463 if (Record.size() != 1) {
5464 Error("incorrect encoding of paren type");
5465 return QualType();
5466 }
5467 QualType InnerType = readType(*Loc.F, Record, Idx);
5468 return Context.getParenType(InnerType);
5469 }
5470
5471 case TYPE_PACK_EXPANSION: {
5472 if (Record.size() != 2) {
5473 Error("incorrect encoding of pack expansion type");
5474 return QualType();
5475 }
5476 QualType Pattern = readType(*Loc.F, Record, Idx);
5477 if (Pattern.isNull())
5478 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005479 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 if (Record[1])
5481 NumExpansions = Record[1] - 1;
5482 return Context.getPackExpansionType(Pattern, NumExpansions);
5483 }
5484
5485 case TYPE_ELABORATED: {
5486 unsigned Idx = 0;
5487 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5488 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5489 QualType NamedType = readType(*Loc.F, Record, Idx);
5490 return Context.getElaboratedType(Keyword, NNS, NamedType);
5491 }
5492
5493 case TYPE_OBJC_INTERFACE: {
5494 unsigned Idx = 0;
5495 ObjCInterfaceDecl *ItfD
5496 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5497 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5498 }
5499
5500 case TYPE_OBJC_OBJECT: {
5501 unsigned Idx = 0;
5502 QualType Base = readType(*Loc.F, Record, Idx);
5503 unsigned NumProtos = Record[Idx++];
5504 SmallVector<ObjCProtocolDecl*, 4> Protos;
5505 for (unsigned I = 0; I != NumProtos; ++I)
5506 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5507 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5508 }
5509
5510 case TYPE_OBJC_OBJECT_POINTER: {
5511 unsigned Idx = 0;
5512 QualType Pointee = readType(*Loc.F, Record, Idx);
5513 return Context.getObjCObjectPointerType(Pointee);
5514 }
5515
5516 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5517 unsigned Idx = 0;
5518 QualType Parm = readType(*Loc.F, Record, Idx);
5519 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005520 return Context.getSubstTemplateTypeParmType(
5521 cast<TemplateTypeParmType>(Parm),
5522 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 }
5524
5525 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5526 unsigned Idx = 0;
5527 QualType Parm = readType(*Loc.F, Record, Idx);
5528 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5529 return Context.getSubstTemplateTypeParmPackType(
5530 cast<TemplateTypeParmType>(Parm),
5531 ArgPack);
5532 }
5533
5534 case TYPE_INJECTED_CLASS_NAME: {
5535 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5536 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5537 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5538 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005539 const Type *T = nullptr;
5540 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5541 if (const Type *Existing = DI->getTypeForDecl()) {
5542 T = Existing;
5543 break;
5544 }
5545 }
5546 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005547 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005548 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5549 DI->setTypeForDecl(T);
5550 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005551 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005552 }
5553
5554 case TYPE_TEMPLATE_TYPE_PARM: {
5555 unsigned Idx = 0;
5556 unsigned Depth = Record[Idx++];
5557 unsigned Index = Record[Idx++];
5558 bool Pack = Record[Idx++];
5559 TemplateTypeParmDecl *D
5560 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5561 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5562 }
5563
5564 case TYPE_DEPENDENT_NAME: {
5565 unsigned Idx = 0;
5566 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5567 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5568 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5569 QualType Canon = readType(*Loc.F, Record, Idx);
5570 if (!Canon.isNull())
5571 Canon = Context.getCanonicalType(Canon);
5572 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5573 }
5574
5575 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5576 unsigned Idx = 0;
5577 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5578 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5579 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5580 unsigned NumArgs = Record[Idx++];
5581 SmallVector<TemplateArgument, 8> Args;
5582 Args.reserve(NumArgs);
5583 while (NumArgs--)
5584 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5585 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5586 Args.size(), Args.data());
5587 }
5588
5589 case TYPE_DEPENDENT_SIZED_ARRAY: {
5590 unsigned Idx = 0;
5591
5592 // ArrayType
5593 QualType ElementType = readType(*Loc.F, Record, Idx);
5594 ArrayType::ArraySizeModifier ASM
5595 = (ArrayType::ArraySizeModifier)Record[Idx++];
5596 unsigned IndexTypeQuals = Record[Idx++];
5597
5598 // DependentSizedArrayType
5599 Expr *NumElts = ReadExpr(*Loc.F);
5600 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5601
5602 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5603 IndexTypeQuals, Brackets);
5604 }
5605
5606 case TYPE_TEMPLATE_SPECIALIZATION: {
5607 unsigned Idx = 0;
5608 bool IsDependent = Record[Idx++];
5609 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5610 SmallVector<TemplateArgument, 8> Args;
5611 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5612 QualType Underlying = readType(*Loc.F, Record, Idx);
5613 QualType T;
5614 if (Underlying.isNull())
5615 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5616 Args.size());
5617 else
5618 T = Context.getTemplateSpecializationType(Name, Args.data(),
5619 Args.size(), Underlying);
5620 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5621 return T;
5622 }
5623
5624 case TYPE_ATOMIC: {
5625 if (Record.size() != 1) {
5626 Error("Incorrect encoding of atomic type");
5627 return QualType();
5628 }
5629 QualType ValueType = readType(*Loc.F, Record, Idx);
5630 return Context.getAtomicType(ValueType);
5631 }
5632 }
5633 llvm_unreachable("Invalid TypeCode!");
5634}
5635
Richard Smith564417a2014-03-20 21:47:22 +00005636void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5637 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005638 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005639 const RecordData &Record, unsigned &Idx) {
5640 ExceptionSpecificationType EST =
5641 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005642 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005643 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005644 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005645 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005646 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005647 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005648 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005649 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005650 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5651 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005652 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005653 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005654 }
5655}
5656
Guy Benyei11169dd2012-12-18 14:30:41 +00005657class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5658 ASTReader &Reader;
5659 ModuleFile &F;
5660 const ASTReader::RecordData &Record;
5661 unsigned &Idx;
5662
5663 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5664 unsigned &I) {
5665 return Reader.ReadSourceLocation(F, R, I);
5666 }
5667
5668 template<typename T>
5669 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5670 return Reader.ReadDeclAs<T>(F, Record, Idx);
5671 }
5672
5673public:
5674 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5675 const ASTReader::RecordData &Record, unsigned &Idx)
5676 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5677 { }
5678
5679 // We want compile-time assurance that we've enumerated all of
5680 // these, so unfortunately we have to declare them first, then
5681 // define them out-of-line.
5682#define ABSTRACT_TYPELOC(CLASS, PARENT)
5683#define TYPELOC(CLASS, PARENT) \
5684 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5685#include "clang/AST/TypeLocNodes.def"
5686
5687 void VisitFunctionTypeLoc(FunctionTypeLoc);
5688 void VisitArrayTypeLoc(ArrayTypeLoc);
5689};
5690
5691void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5692 // nothing to do
5693}
5694void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5695 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5696 if (TL.needsExtraLocalData()) {
5697 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5698 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5699 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5700 TL.setModeAttr(Record[Idx++]);
5701 }
5702}
5703void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5704 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5705}
5706void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5707 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5708}
Reid Kleckner8a365022013-06-24 17:51:48 +00005709void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5710 // nothing to do
5711}
Reid Kleckner0503a872013-12-05 01:23:43 +00005712void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5713 // nothing to do
5714}
Guy Benyei11169dd2012-12-18 14:30:41 +00005715void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5716 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5717}
5718void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5719 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5720}
5721void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5722 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5723}
5724void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5725 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5726 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5727}
5728void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5729 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5730 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5731 if (Record[Idx++])
5732 TL.setSizeExpr(Reader.ReadExpr(F));
5733 else
Craig Toppera13603a2014-05-22 05:54:18 +00005734 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005735}
5736void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5737 VisitArrayTypeLoc(TL);
5738}
5739void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5740 VisitArrayTypeLoc(TL);
5741}
5742void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5743 VisitArrayTypeLoc(TL);
5744}
5745void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5746 DependentSizedArrayTypeLoc TL) {
5747 VisitArrayTypeLoc(TL);
5748}
5749void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5750 DependentSizedExtVectorTypeLoc TL) {
5751 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5752}
5753void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5754 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5755}
5756void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5757 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5758}
5759void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5760 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5761 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5762 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5763 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005764 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5765 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005766 }
5767}
5768void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5769 VisitFunctionTypeLoc(TL);
5770}
5771void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5772 VisitFunctionTypeLoc(TL);
5773}
5774void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5775 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5776}
5777void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5778 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5781 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5782 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5783 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5784}
5785void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5786 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5787 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5788 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5789 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5790}
5791void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5792 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5793}
5794void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5795 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5796 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5797 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5798 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5799}
5800void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5801 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5802}
5803void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5804 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5805}
5806void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5807 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5808}
5809void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5810 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5811 if (TL.hasAttrOperand()) {
5812 SourceRange range;
5813 range.setBegin(ReadSourceLocation(Record, Idx));
5814 range.setEnd(ReadSourceLocation(Record, Idx));
5815 TL.setAttrOperandParensRange(range);
5816 }
5817 if (TL.hasAttrExprOperand()) {
5818 if (Record[Idx++])
5819 TL.setAttrExprOperand(Reader.ReadExpr(F));
5820 else
Craig Toppera13603a2014-05-22 05:54:18 +00005821 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005822 } else if (TL.hasAttrEnumOperand())
5823 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5826 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5829 SubstTemplateTypeParmTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5831}
5832void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5833 SubstTemplateTypeParmPackTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5835}
5836void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5837 TemplateSpecializationTypeLoc TL) {
5838 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5839 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5840 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5841 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5842 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5843 TL.setArgLocInfo(i,
5844 Reader.GetTemplateArgumentLocInfo(F,
5845 TL.getTypePtr()->getArg(i).getKind(),
5846 Record, Idx));
5847}
5848void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5849 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5850 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5851}
5852void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5853 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5854 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5855}
5856void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5857 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5858}
5859void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5860 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5861 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5862 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5863}
5864void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5865 DependentTemplateSpecializationTypeLoc TL) {
5866 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5867 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5868 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5869 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5870 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5871 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5872 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5873 TL.setArgLocInfo(I,
5874 Reader.GetTemplateArgumentLocInfo(F,
5875 TL.getTypePtr()->getArg(I).getKind(),
5876 Record, Idx));
5877}
5878void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5879 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5880}
5881void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5882 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5883}
5884void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5885 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5886 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5887 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5888 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5889 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5890}
5891void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5892 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5893}
5894void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5895 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5896 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5897 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5898}
5899
5900TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5901 const RecordData &Record,
5902 unsigned &Idx) {
5903 QualType InfoTy = readType(F, Record, Idx);
5904 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005905 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005906
5907 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5908 TypeLocReader TLR(*this, F, Record, Idx);
5909 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5910 TLR.Visit(TL);
5911 return TInfo;
5912}
5913
5914QualType ASTReader::GetType(TypeID ID) {
5915 unsigned FastQuals = ID & Qualifiers::FastMask;
5916 unsigned Index = ID >> Qualifiers::FastWidth;
5917
5918 if (Index < NUM_PREDEF_TYPE_IDS) {
5919 QualType T;
5920 switch ((PredefinedTypeIDs)Index) {
5921 case PREDEF_TYPE_NULL_ID: return QualType();
5922 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5923 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5924
5925 case PREDEF_TYPE_CHAR_U_ID:
5926 case PREDEF_TYPE_CHAR_S_ID:
5927 // FIXME: Check that the signedness of CharTy is correct!
5928 T = Context.CharTy;
5929 break;
5930
5931 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5932 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5933 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5934 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5935 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5936 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5937 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5938 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5939 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5940 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5941 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5942 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5943 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5944 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5945 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5946 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5947 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5948 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5949 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5950 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5951 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5952 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5953 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5954 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5955 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5956 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5957 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5958 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005959 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5960 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5961 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5962 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5963 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5964 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005965 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005966 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5968
5969 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5970 T = Context.getAutoRRefDeductType();
5971 break;
5972
5973 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5974 T = Context.ARCUnbridgedCastTy;
5975 break;
5976
5977 case PREDEF_TYPE_VA_LIST_TAG:
5978 T = Context.getVaListTagType();
5979 break;
5980
5981 case PREDEF_TYPE_BUILTIN_FN:
5982 T = Context.BuiltinFnTy;
5983 break;
5984 }
5985
5986 assert(!T.isNull() && "Unknown predefined type");
5987 return T.withFastQualifiers(FastQuals);
5988 }
5989
5990 Index -= NUM_PREDEF_TYPE_IDS;
5991 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5992 if (TypesLoaded[Index].isNull()) {
5993 TypesLoaded[Index] = readTypeRecord(Index);
5994 if (TypesLoaded[Index].isNull())
5995 return QualType();
5996
5997 TypesLoaded[Index]->setFromAST();
5998 if (DeserializationListener)
5999 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6000 TypesLoaded[Index]);
6001 }
6002
6003 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6004}
6005
6006QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6007 return GetType(getGlobalTypeID(F, LocalID));
6008}
6009
6010serialization::TypeID
6011ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6012 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6013 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6014
6015 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6016 return LocalID;
6017
6018 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6019 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6020 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6021
6022 unsigned GlobalIndex = LocalIndex + I->second;
6023 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6024}
6025
6026TemplateArgumentLocInfo
6027ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6028 TemplateArgument::ArgKind Kind,
6029 const RecordData &Record,
6030 unsigned &Index) {
6031 switch (Kind) {
6032 case TemplateArgument::Expression:
6033 return ReadExpr(F);
6034 case TemplateArgument::Type:
6035 return GetTypeSourceInfo(F, Record, Index);
6036 case TemplateArgument::Template: {
6037 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6038 Index);
6039 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6040 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6041 SourceLocation());
6042 }
6043 case TemplateArgument::TemplateExpansion: {
6044 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6045 Index);
6046 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6047 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6048 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6049 EllipsisLoc);
6050 }
6051 case TemplateArgument::Null:
6052 case TemplateArgument::Integral:
6053 case TemplateArgument::Declaration:
6054 case TemplateArgument::NullPtr:
6055 case TemplateArgument::Pack:
6056 // FIXME: Is this right?
6057 return TemplateArgumentLocInfo();
6058 }
6059 llvm_unreachable("unexpected template argument loc");
6060}
6061
6062TemplateArgumentLoc
6063ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6064 const RecordData &Record, unsigned &Index) {
6065 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6066
6067 if (Arg.getKind() == TemplateArgument::Expression) {
6068 if (Record[Index++]) // bool InfoHasSameExpr.
6069 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6070 }
6071 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6072 Record, Index));
6073}
6074
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006075const ASTTemplateArgumentListInfo*
6076ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6077 const RecordData &Record,
6078 unsigned &Index) {
6079 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6080 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6081 unsigned NumArgsAsWritten = Record[Index++];
6082 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6083 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6084 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6085 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6086}
6087
Guy Benyei11169dd2012-12-18 14:30:41 +00006088Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6089 return GetDecl(ID);
6090}
6091
Richard Smith50895422015-01-31 03:04:55 +00006092template<typename TemplateSpecializationDecl>
6093static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6094 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6095 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6096}
6097
Richard Smith053f6c62014-05-16 23:01:30 +00006098void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006099 if (NumCurrentElementsDeserializing) {
6100 // We arrange to not care about the complete redeclaration chain while we're
6101 // deserializing. Just remember that the AST has marked this one as complete
6102 // but that it's not actually complete yet, so we know we still need to
6103 // complete it later.
6104 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6105 return;
6106 }
6107
Richard Smith053f6c62014-05-16 23:01:30 +00006108 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6109
Richard Smith053f6c62014-05-16 23:01:30 +00006110 // If this is a named declaration, complete it by looking it up
6111 // within its context.
6112 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006113 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006114 // all mergeable entities within it.
6115 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6116 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6117 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6118 auto *II = Name.getAsIdentifierInfo();
6119 if (isa<TranslationUnitDecl>(DC) && II) {
6120 // Outside of C++, we don't have a lookup table for the TU, so update
6121 // the identifier instead. In C++, either way should work fine.
6122 if (II->isOutOfDate())
6123 updateOutOfDateIdentifier(*II);
6124 } else
6125 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006126 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6127 // FIXME: It'd be nice to do something a bit more targeted here.
6128 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006129 }
6130 }
Richard Smith50895422015-01-31 03:04:55 +00006131
6132 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6133 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6134 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6135 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6136 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6137 if (auto *Template = FD->getPrimaryTemplate())
6138 Template->LoadLazySpecializations();
6139 }
Richard Smith053f6c62014-05-16 23:01:30 +00006140}
6141
Richard Smithcd45dbc2014-04-19 03:48:30 +00006142uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6143 const RecordData &Record,
6144 unsigned &Idx) {
6145 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6146 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006148 }
6149
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 unsigned LocalID = Record[Idx++];
6151 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6152}
6153
6154CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6155 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006156 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 SavedStreamPosition SavedPosition(Cursor);
6158 Cursor.JumpToBit(Loc.Offset);
6159 ReadingKindTracker ReadingKind(Read_Decl, *this);
6160 RecordData Record;
6161 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006162 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006164 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006165 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 }
6167
6168 unsigned Idx = 0;
6169 unsigned NumBases = Record[Idx++];
6170 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6171 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6172 for (unsigned I = 0; I != NumBases; ++I)
6173 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6174 return Bases;
6175}
6176
6177serialization::DeclID
6178ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6179 if (LocalID < NUM_PREDEF_DECL_IDS)
6180 return LocalID;
6181
6182 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6183 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6184 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6185
6186 return LocalID + I->second;
6187}
6188
6189bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6190 ModuleFile &M) const {
6191 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6192 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6193 return &M == I->second;
6194}
6195
Douglas Gregor9f782892013-01-21 15:25:38 +00006196ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006198 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6200 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6201 return I->second;
6202}
6203
6204SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6205 if (ID < NUM_PREDEF_DECL_IDS)
6206 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006207
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6209
6210 if (Index > DeclsLoaded.size()) {
6211 Error("declaration ID out-of-range for AST file");
6212 return SourceLocation();
6213 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006214
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 if (Decl *D = DeclsLoaded[Index])
6216 return D->getLocation();
6217
6218 unsigned RawLocation = 0;
6219 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6220 return ReadSourceLocation(*Rec.F, RawLocation);
6221}
6222
Richard Smithcd45dbc2014-04-19 03:48:30 +00006223Decl *ASTReader::GetExistingDecl(DeclID ID) {
6224 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 switch ((PredefinedDeclIDs)ID) {
6226 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006227 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006228
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6230 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006231
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 case PREDEF_DECL_OBJC_ID_ID:
6233 return Context.getObjCIdDecl();
6234
6235 case PREDEF_DECL_OBJC_SEL_ID:
6236 return Context.getObjCSelDecl();
6237
6238 case PREDEF_DECL_OBJC_CLASS_ID:
6239 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006240
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6242 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006243
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 case PREDEF_DECL_INT_128_ID:
6245 return Context.getInt128Decl();
6246
6247 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6248 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006249
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6251 return Context.getObjCInstanceTypeDecl();
6252
6253 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6254 return Context.getBuiltinVaListDecl();
6255 }
6256 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006257
Guy Benyei11169dd2012-12-18 14:30:41 +00006258 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6259
6260 if (Index >= DeclsLoaded.size()) {
6261 assert(0 && "declaration ID out-of-range for AST file");
6262 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006263 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006264 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006265
6266 return DeclsLoaded[Index];
6267}
6268
6269Decl *ASTReader::GetDecl(DeclID ID) {
6270 if (ID < NUM_PREDEF_DECL_IDS)
6271 return GetExistingDecl(ID);
6272
6273 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6274
6275 if (Index >= DeclsLoaded.size()) {
6276 assert(0 && "declaration ID out-of-range for AST file");
6277 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006278 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006279 }
6280
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 if (!DeclsLoaded[Index]) {
6282 ReadDeclRecord(ID);
6283 if (DeserializationListener)
6284 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6285 }
6286
6287 return DeclsLoaded[Index];
6288}
6289
6290DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6291 DeclID GlobalID) {
6292 if (GlobalID < NUM_PREDEF_DECL_IDS)
6293 return GlobalID;
6294
6295 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6296 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6297 ModuleFile *Owner = I->second;
6298
6299 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6300 = M.GlobalToLocalDeclIDs.find(Owner);
6301 if (Pos == M.GlobalToLocalDeclIDs.end())
6302 return 0;
6303
6304 return GlobalID - Owner->BaseDeclID + Pos->second;
6305}
6306
6307serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6308 const RecordData &Record,
6309 unsigned &Idx) {
6310 if (Idx >= Record.size()) {
6311 Error("Corrupted AST file");
6312 return 0;
6313 }
6314
6315 return getGlobalDeclID(F, Record[Idx++]);
6316}
6317
6318/// \brief Resolve the offset of a statement into a statement.
6319///
6320/// This operation will read a new statement from the external
6321/// source each time it is called, and is meant to be used via a
6322/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6323Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6324 // Switch case IDs are per Decl.
6325 ClearSwitchCaseIDs();
6326
6327 // Offset here is a global offset across the entire chain.
6328 RecordLocation Loc = getLocalBitOffset(Offset);
6329 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6330 return ReadStmtFromStream(*Loc.F);
6331}
6332
6333namespace {
6334 class FindExternalLexicalDeclsVisitor {
6335 ASTReader &Reader;
6336 const DeclContext *DC;
6337 bool (*isKindWeWant)(Decl::Kind);
6338
6339 SmallVectorImpl<Decl*> &Decls;
6340 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6341
6342 public:
6343 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6344 bool (*isKindWeWant)(Decl::Kind),
6345 SmallVectorImpl<Decl*> &Decls)
6346 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6347 {
6348 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6349 PredefsVisited[I] = false;
6350 }
6351
6352 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6353 if (Preorder)
6354 return false;
6355
6356 FindExternalLexicalDeclsVisitor *This
6357 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6358
6359 ModuleFile::DeclContextInfosMap::iterator Info
6360 = M.DeclContextInfos.find(This->DC);
6361 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6362 return false;
6363
6364 // Load all of the declaration IDs
6365 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6366 *IDE = ID + Info->second.NumLexicalDecls;
6367 ID != IDE; ++ID) {
6368 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6369 continue;
6370
6371 // Don't add predefined declarations to the lexical context more
6372 // than once.
6373 if (ID->second < NUM_PREDEF_DECL_IDS) {
6374 if (This->PredefsVisited[ID->second])
6375 continue;
6376
6377 This->PredefsVisited[ID->second] = true;
6378 }
6379
6380 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6381 if (!This->DC->isDeclInLexicalTraversal(D))
6382 This->Decls.push_back(D);
6383 }
6384 }
6385
6386 return false;
6387 }
6388 };
6389}
6390
6391ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6392 bool (*isKindWeWant)(Decl::Kind),
6393 SmallVectorImpl<Decl*> &Decls) {
6394 // There might be lexical decls in multiple modules, for the TU at
6395 // least. Walk all of the modules in the order they were loaded.
6396 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6397 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6398 ++NumLexicalDeclContextsRead;
6399 return ELR_Success;
6400}
6401
6402namespace {
6403
6404class DeclIDComp {
6405 ASTReader &Reader;
6406 ModuleFile &Mod;
6407
6408public:
6409 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6410
6411 bool operator()(LocalDeclID L, LocalDeclID R) const {
6412 SourceLocation LHS = getLocation(L);
6413 SourceLocation RHS = getLocation(R);
6414 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6415 }
6416
6417 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6418 SourceLocation RHS = getLocation(R);
6419 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6420 }
6421
6422 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6423 SourceLocation LHS = getLocation(L);
6424 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6425 }
6426
6427 SourceLocation getLocation(LocalDeclID ID) const {
6428 return Reader.getSourceManager().getFileLoc(
6429 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6430 }
6431};
6432
6433}
6434
6435void ASTReader::FindFileRegionDecls(FileID File,
6436 unsigned Offset, unsigned Length,
6437 SmallVectorImpl<Decl *> &Decls) {
6438 SourceManager &SM = getSourceManager();
6439
6440 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6441 if (I == FileDeclIDs.end())
6442 return;
6443
6444 FileDeclsInfo &DInfo = I->second;
6445 if (DInfo.Decls.empty())
6446 return;
6447
6448 SourceLocation
6449 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6450 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6451
6452 DeclIDComp DIDComp(*this, *DInfo.Mod);
6453 ArrayRef<serialization::LocalDeclID>::iterator
6454 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6455 BeginLoc, DIDComp);
6456 if (BeginIt != DInfo.Decls.begin())
6457 --BeginIt;
6458
6459 // If we are pointing at a top-level decl inside an objc container, we need
6460 // to backtrack until we find it otherwise we will fail to report that the
6461 // region overlaps with an objc container.
6462 while (BeginIt != DInfo.Decls.begin() &&
6463 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6464 ->isTopLevelDeclInObjCContainer())
6465 --BeginIt;
6466
6467 ArrayRef<serialization::LocalDeclID>::iterator
6468 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6469 EndLoc, DIDComp);
6470 if (EndIt != DInfo.Decls.end())
6471 ++EndIt;
6472
6473 for (ArrayRef<serialization::LocalDeclID>::iterator
6474 DIt = BeginIt; DIt != EndIt; ++DIt)
6475 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6476}
6477
6478namespace {
6479 /// \brief ModuleFile visitor used to perform name lookup into a
6480 /// declaration context.
6481 class DeclContextNameLookupVisitor {
6482 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006483 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 DeclarationName Name;
6485 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006486 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006487
6488 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006489 DeclContextNameLookupVisitor(ASTReader &Reader,
6490 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006492 SmallVectorImpl<NamedDecl *> &Decls,
6493 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6494 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6495 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006496
6497 static bool visit(ModuleFile &M, void *UserData) {
6498 DeclContextNameLookupVisitor *This
6499 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6500
6501 // Check whether we have any visible declaration information for
6502 // this context in this module.
6503 ModuleFile::DeclContextInfosMap::iterator Info;
6504 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006505 for (auto *DC : This->Contexts) {
6506 Info = M.DeclContextInfos.find(DC);
6507 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 Info->second.NameLookupTableData) {
6509 FoundInfo = true;
6510 break;
6511 }
6512 }
6513
6514 if (!FoundInfo)
6515 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006516
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006518 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 Info->second.NameLookupTableData;
6520 ASTDeclContextNameLookupTable::iterator Pos
6521 = LookupTable->find(This->Name);
6522 if (Pos == LookupTable->end())
6523 return false;
6524
6525 bool FoundAnything = false;
6526 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6527 for (; Data.first != Data.second; ++Data.first) {
6528 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6529 if (!ND)
6530 continue;
6531
6532 if (ND->getDeclName() != This->Name) {
6533 // A name might be null because the decl's redeclarable part is
6534 // currently read before reading its name. The lookup is triggered by
6535 // building that decl (likely indirectly), and so it is later in the
6536 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006537 // FIXME: This should not happen; deserializing declarations should
6538 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 continue;
6540 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006541
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 // Record this declaration.
6543 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006544 if (This->DeclSet.insert(ND).second)
6545 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 }
6547
6548 return FoundAnything;
6549 }
6550 };
6551}
6552
Douglas Gregor9f782892013-01-21 15:25:38 +00006553/// \brief Retrieve the "definitive" module file for the definition of the
6554/// given declaration context, if there is one.
6555///
6556/// The "definitive" module file is the only place where we need to look to
6557/// find information about the declarations within the given declaration
6558/// context. For example, C++ and Objective-C classes, C structs/unions, and
6559/// Objective-C protocols, categories, and extensions are all defined in a
6560/// single place in the source code, so they have definitive module files
6561/// associated with them. C++ namespaces, on the other hand, can have
6562/// definitions in multiple different module files.
6563///
6564/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6565/// NDEBUG checking.
6566static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6567 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006568 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6569 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006570
Craig Toppera13603a2014-05-22 05:54:18 +00006571 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006572}
6573
Richard Smith9ce12e32013-02-07 03:30:24 +00006574bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006575ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6576 DeclarationName Name) {
6577 assert(DC->hasExternalVisibleStorage() &&
6578 "DeclContext has no visible decls in storage");
6579 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006580 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006581
Richard Smith8c913ec2014-08-14 02:21:01 +00006582 Deserializing LookupResults(this);
6583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006585 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006586
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 // Compute the declaration contexts we need to look into. Multiple such
6588 // declaration contexts occur when two declaration contexts from disjoint
6589 // modules get merged, e.g., when two namespaces with the same name are
6590 // independently defined in separate modules.
6591 SmallVector<const DeclContext *, 2> Contexts;
6592 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006593
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006595 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 if (Merged != MergedDecls.end()) {
6597 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6598 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6599 }
6600 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006601
6602 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006603 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006604
6605 // If we can definitively determine which module file to look into,
6606 // only look there. Otherwise, look in all module files.
6607 ModuleFile *Definitive;
6608 if (Contexts.size() == 1 &&
6609 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6610 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6611 } else {
6612 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6613 }
6614 };
6615
6616 LookUpInContexts(Contexts);
6617
6618 // If this might be an implicit special member function, then also search
6619 // all merged definitions of the surrounding class. We need to search them
6620 // individually, because finding an entity in one of them doesn't imply that
6621 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006622 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006623 auto Kind = Name.getNameKind();
6624 if (Kind == DeclarationName::CXXConstructorName ||
6625 Kind == DeclarationName::CXXDestructorName ||
6626 (Kind == DeclarationName::CXXOperatorName &&
6627 Name.getCXXOverloadedOperator() == OO_Equal)) {
6628 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006629 if (Merged != MergedLookups.end()) {
6630 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6631 LookUpInContexts(Merged->second[I]);
6632 // We might have just added some more merged lookups. If so, our
6633 // iterator is now invalid, so grab a fresh one before continuing.
6634 Merged = MergedLookups.find(DC);
6635 }
6636 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006637 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006638 }
6639
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 ++NumVisibleDeclContextsRead;
6641 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006642 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
6644
6645namespace {
6646 /// \brief ModuleFile visitor used to retrieve all visible names in a
6647 /// declaration context.
6648 class DeclContextAllNamesVisitor {
6649 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006650 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006651 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006652 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006653 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006654
6655 public:
6656 DeclContextAllNamesVisitor(ASTReader &Reader,
6657 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006658 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006659 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006660
6661 static bool visit(ModuleFile &M, void *UserData) {
6662 DeclContextAllNamesVisitor *This
6663 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6664
6665 // Check whether we have any visible declaration information for
6666 // this context in this module.
6667 ModuleFile::DeclContextInfosMap::iterator Info;
6668 bool FoundInfo = false;
6669 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6670 Info = M.DeclContextInfos.find(This->Contexts[I]);
6671 if (Info != M.DeclContextInfos.end() &&
6672 Info->second.NameLookupTableData) {
6673 FoundInfo = true;
6674 break;
6675 }
6676 }
6677
6678 if (!FoundInfo)
6679 return false;
6680
Richard Smith52e3fba2014-03-11 07:17:35 +00006681 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 Info->second.NameLookupTableData;
6683 bool FoundAnything = false;
6684 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006685 I = LookupTable->data_begin(), E = LookupTable->data_end();
6686 I != E;
6687 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 ASTDeclContextNameLookupTrait::data_type Data = *I;
6689 for (; Data.first != Data.second; ++Data.first) {
6690 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6691 *Data.first);
6692 if (!ND)
6693 continue;
6694
6695 // Record this declaration.
6696 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006697 if (This->DeclSet.insert(ND).second)
6698 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006699 }
6700 }
6701
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006702 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 }
6704 };
6705}
6706
6707void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6708 if (!DC->hasExternalVisibleStorage())
6709 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006710 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006711
6712 // Compute the declaration contexts we need to look into. Multiple such
6713 // declaration contexts occur when two declaration contexts from disjoint
6714 // modules get merged, e.g., when two namespaces with the same name are
6715 // independently defined in separate modules.
6716 SmallVector<const DeclContext *, 2> Contexts;
6717 Contexts.push_back(DC);
6718
6719 if (DC->isNamespace()) {
6720 MergedDeclsMap::iterator Merged
6721 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6722 if (Merged != MergedDecls.end()) {
6723 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6724 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6725 }
6726 }
6727
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006728 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6729 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6731 ++NumVisibleDeclContextsRead;
6732
Craig Topper79be4cd2013-07-05 04:33:53 +00006733 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6735 }
6736 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6737}
6738
6739/// \brief Under non-PCH compilation the consumer receives the objc methods
6740/// before receiving the implementation, and codegen depends on this.
6741/// We simulate this by deserializing and passing to consumer the methods of the
6742/// implementation before passing the deserialized implementation decl.
6743static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6744 ASTConsumer *Consumer) {
6745 assert(ImplD && Consumer);
6746
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006747 for (auto *I : ImplD->methods())
6748 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006749
6750 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6751}
6752
6753void ASTReader::PassInterestingDeclsToConsumer() {
6754 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006755
6756 if (PassingDeclsToConsumer)
6757 return;
6758
6759 // Guard variable to avoid recursively redoing the process of passing
6760 // decls to consumer.
6761 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6762 true);
6763
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 while (!InterestingDecls.empty()) {
6765 Decl *D = InterestingDecls.front();
6766 InterestingDecls.pop_front();
6767
6768 PassInterestingDeclToConsumer(D);
6769 }
6770}
6771
6772void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6773 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6774 PassObjCImplDeclToConsumer(ImplD, Consumer);
6775 else
6776 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6777}
6778
6779void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6780 this->Consumer = Consumer;
6781
6782 if (!Consumer)
6783 return;
6784
Ben Langmuir332aafe2014-01-31 01:06:56 +00006785 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 // Force deserialization of this decl, which will cause it to be queued for
6787 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006788 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006790 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006791
6792 PassInterestingDeclsToConsumer();
6793}
6794
6795void ASTReader::PrintStats() {
6796 std::fprintf(stderr, "*** AST File Statistics:\n");
6797
6798 unsigned NumTypesLoaded
6799 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6800 QualType());
6801 unsigned NumDeclsLoaded
6802 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006803 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006804 unsigned NumIdentifiersLoaded
6805 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6806 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006807 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 unsigned NumMacrosLoaded
6809 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6810 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006811 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 unsigned NumSelectorsLoaded
6813 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6814 SelectorsLoaded.end(),
6815 Selector());
6816
6817 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6818 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6819 NumSLocEntriesRead, TotalNumSLocEntries,
6820 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6821 if (!TypesLoaded.empty())
6822 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6823 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6824 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6825 if (!DeclsLoaded.empty())
6826 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6827 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6828 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6829 if (!IdentifiersLoaded.empty())
6830 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6831 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6832 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6833 if (!MacrosLoaded.empty())
6834 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6835 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6836 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6837 if (!SelectorsLoaded.empty())
6838 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6839 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6840 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6841 if (TotalNumStatements)
6842 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6843 NumStatementsRead, TotalNumStatements,
6844 ((float)NumStatementsRead/TotalNumStatements * 100));
6845 if (TotalNumMacros)
6846 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6847 NumMacrosRead, TotalNumMacros,
6848 ((float)NumMacrosRead/TotalNumMacros * 100));
6849 if (TotalLexicalDeclContexts)
6850 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6851 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6852 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6853 * 100));
6854 if (TotalVisibleDeclContexts)
6855 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6856 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6857 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6858 * 100));
6859 if (TotalNumMethodPoolEntries) {
6860 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6861 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6862 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6863 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006865 if (NumMethodPoolLookups) {
6866 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6867 NumMethodPoolHits, NumMethodPoolLookups,
6868 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6869 }
6870 if (NumMethodPoolTableLookups) {
6871 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6872 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6873 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6874 * 100.0));
6875 }
6876
Douglas Gregor00a50f72013-01-25 00:38:33 +00006877 if (NumIdentifierLookupHits) {
6878 std::fprintf(stderr,
6879 " %u / %u identifier table lookups succeeded (%f%%)\n",
6880 NumIdentifierLookupHits, NumIdentifierLookups,
6881 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6882 }
6883
Douglas Gregore060e572013-01-25 01:03:03 +00006884 if (GlobalIndex) {
6885 std::fprintf(stderr, "\n");
6886 GlobalIndex->printStats();
6887 }
6888
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 std::fprintf(stderr, "\n");
6890 dump();
6891 std::fprintf(stderr, "\n");
6892}
6893
6894template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6895static void
6896dumpModuleIDMap(StringRef Name,
6897 const ContinuousRangeMap<Key, ModuleFile *,
6898 InitialCapacity> &Map) {
6899 if (Map.begin() == Map.end())
6900 return;
6901
6902 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6903 llvm::errs() << Name << ":\n";
6904 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6905 I != IEnd; ++I) {
6906 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6907 << "\n";
6908 }
6909}
6910
6911void ASTReader::dump() {
6912 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6913 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6914 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6915 dumpModuleIDMap("Global type map", GlobalTypeMap);
6916 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6917 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6918 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6919 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6920 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6921 dumpModuleIDMap("Global preprocessed entity map",
6922 GlobalPreprocessedEntityMap);
6923
6924 llvm::errs() << "\n*** PCH/Modules Loaded:";
6925 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6926 MEnd = ModuleMgr.end();
6927 M != MEnd; ++M)
6928 (*M)->dump();
6929}
6930
6931/// Return the amount of memory used by memory buffers, breaking down
6932/// by heap-backed versus mmap'ed memory.
6933void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6934 for (ModuleConstIterator I = ModuleMgr.begin(),
6935 E = ModuleMgr.end(); I != E; ++I) {
6936 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6937 size_t bytes = buf->getBufferSize();
6938 switch (buf->getBufferKind()) {
6939 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6940 sizes.malloc_bytes += bytes;
6941 break;
6942 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6943 sizes.mmap_bytes += bytes;
6944 break;
6945 }
6946 }
6947 }
6948}
6949
6950void ASTReader::InitializeSema(Sema &S) {
6951 SemaObj = &S;
6952 S.addExternalSource(this);
6953
6954 // Makes sure any declarations that were deserialized "too early"
6955 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006956 for (uint64_t ID : PreloadedDeclIDs) {
6957 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6958 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006960 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006961
Richard Smith3d8e97e2013-10-18 06:54:39 +00006962 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 if (!FPPragmaOptions.empty()) {
6964 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6965 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6966 }
6967
Richard Smith3d8e97e2013-10-18 06:54:39 +00006968 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 if (!OpenCLExtensions.empty()) {
6970 unsigned I = 0;
6971#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6972#include "clang/Basic/OpenCLExtensions.def"
6973
6974 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6975 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006976
6977 UpdateSema();
6978}
6979
6980void ASTReader::UpdateSema() {
6981 assert(SemaObj && "no Sema to update");
6982
6983 // Load the offsets of the declarations that Sema references.
6984 // They will be lazily deserialized when needed.
6985 if (!SemaDeclRefs.empty()) {
6986 assert(SemaDeclRefs.size() % 2 == 0);
6987 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6988 if (!SemaObj->StdNamespace)
6989 SemaObj->StdNamespace = SemaDeclRefs[I];
6990 if (!SemaObj->StdBadAlloc)
6991 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6992 }
6993 SemaDeclRefs.clear();
6994 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006995
6996 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6997 // encountered the pragma in the source.
6998 if(OptimizeOffPragmaLocation.isValid())
6999 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007000}
7001
7002IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7003 // Note that we are loading an identifier.
7004 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007005 StringRef Name(NameStart, NameEnd - NameStart);
7006
7007 // If there is a global index, look there first to determine which modules
7008 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007009 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007010 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007011 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007012 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7013 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007014 }
7015 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007016 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007017 NumIdentifierLookups,
7018 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007019 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007020 IdentifierInfo *II = Visitor.getIdentifierInfo();
7021 markIdentifierUpToDate(II);
7022 return II;
7023}
7024
7025namespace clang {
7026 /// \brief An identifier-lookup iterator that enumerates all of the
7027 /// identifiers stored within a set of AST files.
7028 class ASTIdentifierIterator : public IdentifierIterator {
7029 /// \brief The AST reader whose identifiers are being enumerated.
7030 const ASTReader &Reader;
7031
7032 /// \brief The current index into the chain of AST files stored in
7033 /// the AST reader.
7034 unsigned Index;
7035
7036 /// \brief The current position within the identifier lookup table
7037 /// of the current AST file.
7038 ASTIdentifierLookupTable::key_iterator Current;
7039
7040 /// \brief The end position within the identifier lookup table of
7041 /// the current AST file.
7042 ASTIdentifierLookupTable::key_iterator End;
7043
7044 public:
7045 explicit ASTIdentifierIterator(const ASTReader &Reader);
7046
Craig Topper3e89dfe2014-03-13 02:13:41 +00007047 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007048 };
7049}
7050
7051ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7052 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7053 ASTIdentifierLookupTable *IdTable
7054 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7055 Current = IdTable->key_begin();
7056 End = IdTable->key_end();
7057}
7058
7059StringRef ASTIdentifierIterator::Next() {
7060 while (Current == End) {
7061 // If we have exhausted all of our AST files, we're done.
7062 if (Index == 0)
7063 return StringRef();
7064
7065 --Index;
7066 ASTIdentifierLookupTable *IdTable
7067 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7068 IdentifierLookupTable;
7069 Current = IdTable->key_begin();
7070 End = IdTable->key_end();
7071 }
7072
7073 // We have any identifiers remaining in the current AST file; return
7074 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007075 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007077 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007078}
7079
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007080IdentifierIterator *ASTReader::getIdentifiers() {
7081 if (!loadGlobalIndex())
7082 return GlobalIndex->createIdentifierIterator();
7083
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 return new ASTIdentifierIterator(*this);
7085}
7086
7087namespace clang { namespace serialization {
7088 class ReadMethodPoolVisitor {
7089 ASTReader &Reader;
7090 Selector Sel;
7091 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007092 unsigned InstanceBits;
7093 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007094 bool InstanceHasMoreThanOneDecl;
7095 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007096 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7097 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007098
7099 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007100 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007101 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007102 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007103 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7104 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007105
Guy Benyei11169dd2012-12-18 14:30:41 +00007106 static bool visit(ModuleFile &M, void *UserData) {
7107 ReadMethodPoolVisitor *This
7108 = static_cast<ReadMethodPoolVisitor *>(UserData);
7109
7110 if (!M.SelectorLookupTable)
7111 return false;
7112
7113 // If we've already searched this module file, skip it now.
7114 if (M.Generation <= This->PriorGeneration)
7115 return true;
7116
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007117 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 ASTSelectorLookupTable *PoolTable
7119 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7120 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7121 if (Pos == PoolTable->end())
7122 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007123
7124 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007125 ++This->Reader.NumSelectorsRead;
7126 // FIXME: Not quite happy with the statistics here. We probably should
7127 // disable this tracking when called via LoadSelector.
7128 // Also, should entries without methods count as misses?
7129 ++This->Reader.NumMethodPoolEntriesRead;
7130 ASTSelectorLookupTrait::data_type Data = *Pos;
7131 if (This->Reader.DeserializationListener)
7132 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7133 This->Sel);
7134
7135 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7136 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007137 This->InstanceBits = Data.InstanceBits;
7138 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007139 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7140 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007141 return true;
7142 }
7143
7144 /// \brief Retrieve the instance methods found by this visitor.
7145 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7146 return InstanceMethods;
7147 }
7148
7149 /// \brief Retrieve the instance methods found by this visitor.
7150 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7151 return FactoryMethods;
7152 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007153
7154 unsigned getInstanceBits() const { return InstanceBits; }
7155 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007156 bool instanceHasMoreThanOneDecl() const {
7157 return InstanceHasMoreThanOneDecl;
7158 }
7159 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 };
7161} } // end namespace clang::serialization
7162
7163/// \brief Add the given set of methods to the method list.
7164static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7165 ObjCMethodList &List) {
7166 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7167 S.addMethodToGlobalList(&List, Methods[I]);
7168 }
7169}
7170
7171void ASTReader::ReadMethodPool(Selector Sel) {
7172 // Get the selector generation and update it to the current generation.
7173 unsigned &Generation = SelectorGeneration[Sel];
7174 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007175 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007176
7177 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007178 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007179 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7180 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7181
7182 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007183 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007185
7186 ++NumMethodPoolHits;
7187
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 if (!getSema())
7189 return;
7190
7191 Sema &S = *getSema();
7192 Sema::GlobalMethodPool::iterator Pos
7193 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007194
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007195 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007196 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007197 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007198 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007199
7200 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7201 // when building a module we keep every method individually and may need to
7202 // update hasMoreThanOneDecl as we add the methods.
7203 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7204 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007205}
7206
7207void ASTReader::ReadKnownNamespaces(
7208 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7209 Namespaces.clear();
7210
7211 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7212 if (NamespaceDecl *Namespace
7213 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7214 Namespaces.push_back(Namespace);
7215 }
7216}
7217
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007218void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007219 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007220 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7221 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007222 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007223 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007224 Undefined.insert(std::make_pair(D, Loc));
7225 }
7226}
Nick Lewycky8334af82013-01-26 00:35:08 +00007227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228void ASTReader::ReadTentativeDefinitions(
7229 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7230 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7231 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7232 if (Var)
7233 TentativeDefs.push_back(Var);
7234 }
7235 TentativeDefinitions.clear();
7236}
7237
7238void ASTReader::ReadUnusedFileScopedDecls(
7239 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7240 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7241 DeclaratorDecl *D
7242 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7243 if (D)
7244 Decls.push_back(D);
7245 }
7246 UnusedFileScopedDecls.clear();
7247}
7248
7249void ASTReader::ReadDelegatingConstructors(
7250 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7251 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7252 CXXConstructorDecl *D
7253 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7254 if (D)
7255 Decls.push_back(D);
7256 }
7257 DelegatingCtorDecls.clear();
7258}
7259
7260void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7261 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7262 TypedefNameDecl *D
7263 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7264 if (D)
7265 Decls.push_back(D);
7266 }
7267 ExtVectorDecls.clear();
7268}
7269
7270void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7271 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7272 CXXRecordDecl *D
7273 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7274 if (D)
7275 Decls.push_back(D);
7276 }
7277 DynamicClasses.clear();
7278}
7279
Nico Weber72889432014-09-06 01:25:55 +00007280void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7281 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7282 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7283 ++I) {
7284 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7285 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7286 if (D)
7287 Decls.insert(D);
7288 }
7289 UnusedLocalTypedefNameCandidates.clear();
7290}
7291
Guy Benyei11169dd2012-12-18 14:30:41 +00007292void
Richard Smith78165b52013-01-10 23:43:47 +00007293ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7294 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7295 NamedDecl *D
7296 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 if (D)
7298 Decls.push_back(D);
7299 }
Richard Smith78165b52013-01-10 23:43:47 +00007300 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007301}
7302
7303void ASTReader::ReadReferencedSelectors(
7304 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7305 if (ReferencedSelectorsData.empty())
7306 return;
7307
7308 // If there are @selector references added them to its pool. This is for
7309 // implementation of -Wselector.
7310 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7311 unsigned I = 0;
7312 while (I < DataSize) {
7313 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7314 SourceLocation SelLoc
7315 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7316 Sels.push_back(std::make_pair(Sel, SelLoc));
7317 }
7318 ReferencedSelectorsData.clear();
7319}
7320
7321void ASTReader::ReadWeakUndeclaredIdentifiers(
7322 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7323 if (WeakUndeclaredIdentifiers.empty())
7324 return;
7325
7326 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7327 IdentifierInfo *WeakId
7328 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7329 IdentifierInfo *AliasId
7330 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7331 SourceLocation Loc
7332 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7333 bool Used = WeakUndeclaredIdentifiers[I++];
7334 WeakInfo WI(AliasId, Loc);
7335 WI.setUsed(Used);
7336 WeakIDs.push_back(std::make_pair(WeakId, WI));
7337 }
7338 WeakUndeclaredIdentifiers.clear();
7339}
7340
7341void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7342 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7343 ExternalVTableUse VT;
7344 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7345 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7346 VT.DefinitionRequired = VTableUses[Idx++];
7347 VTables.push_back(VT);
7348 }
7349
7350 VTableUses.clear();
7351}
7352
7353void ASTReader::ReadPendingInstantiations(
7354 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7355 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7356 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7357 SourceLocation Loc
7358 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7359
7360 Pending.push_back(std::make_pair(D, Loc));
7361 }
7362 PendingInstantiations.clear();
7363}
7364
Richard Smithe40f2ba2013-08-07 21:41:30 +00007365void ASTReader::ReadLateParsedTemplates(
7366 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7367 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7368 /* In loop */) {
7369 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7370
7371 LateParsedTemplate *LT = new LateParsedTemplate;
7372 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7373
7374 ModuleFile *F = getOwningModuleFile(LT->D);
7375 assert(F && "No module");
7376
7377 unsigned TokN = LateParsedTemplates[Idx++];
7378 LT->Toks.reserve(TokN);
7379 for (unsigned T = 0; T < TokN; ++T)
7380 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7381
7382 LPTMap[FD] = LT;
7383 }
7384
7385 LateParsedTemplates.clear();
7386}
7387
Guy Benyei11169dd2012-12-18 14:30:41 +00007388void ASTReader::LoadSelector(Selector Sel) {
7389 // It would be complicated to avoid reading the methods anyway. So don't.
7390 ReadMethodPool(Sel);
7391}
7392
7393void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7394 assert(ID && "Non-zero identifier ID required");
7395 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7396 IdentifiersLoaded[ID - 1] = II;
7397 if (DeserializationListener)
7398 DeserializationListener->IdentifierRead(ID, II);
7399}
7400
7401/// \brief Set the globally-visible declarations associated with the given
7402/// identifier.
7403///
7404/// If the AST reader is currently in a state where the given declaration IDs
7405/// cannot safely be resolved, they are queued until it is safe to resolve
7406/// them.
7407///
7408/// \param II an IdentifierInfo that refers to one or more globally-visible
7409/// declarations.
7410///
7411/// \param DeclIDs the set of declaration IDs with the name @p II that are
7412/// visible at global scope.
7413///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007414/// \param Decls if non-null, this vector will be populated with the set of
7415/// deserialized declarations. These declarations will not be pushed into
7416/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007417void
7418ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7419 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007420 SmallVectorImpl<Decl *> *Decls) {
7421 if (NumCurrentElementsDeserializing && !Decls) {
7422 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 return;
7424 }
7425
7426 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007427 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 // Queue this declaration so that it will be added to the
7429 // translation unit scope and identifier's declaration chain
7430 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007431 PreloadedDeclIDs.push_back(DeclIDs[I]);
7432 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007434
7435 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7436
7437 // If we're simply supposed to record the declarations, do so now.
7438 if (Decls) {
7439 Decls->push_back(D);
7440 continue;
7441 }
7442
7443 // Introduce this declaration into the translation-unit scope
7444 // and add it to the declaration chain for this identifier, so
7445 // that (unqualified) name lookup will find it.
7446 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 }
7448}
7449
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007450IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007451 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007452 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007453
7454 if (IdentifiersLoaded.empty()) {
7455 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007456 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 }
7458
7459 ID -= 1;
7460 if (!IdentifiersLoaded[ID]) {
7461 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7462 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7463 ModuleFile *M = I->second;
7464 unsigned Index = ID - M->BaseIdentifierID;
7465 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7466
7467 // All of the strings in the AST file are preceded by a 16-bit length.
7468 // Extract that 16-bit length to avoid having to execute strlen().
7469 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7470 // unsigned integers. This is important to avoid integer overflow when
7471 // we cast them to 'unsigned'.
7472 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7473 unsigned StrLen = (((unsigned) StrLenPtr[0])
7474 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007475 IdentifiersLoaded[ID]
7476 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 if (DeserializationListener)
7478 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7479 }
7480
7481 return IdentifiersLoaded[ID];
7482}
7483
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007484IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7485 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007486}
7487
7488IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7489 if (LocalID < NUM_PREDEF_IDENT_IDS)
7490 return LocalID;
7491
7492 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7493 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7494 assert(I != M.IdentifierRemap.end()
7495 && "Invalid index into identifier index remap");
7496
7497 return LocalID + I->second;
7498}
7499
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007500MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007501 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007502 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007503
7504 if (MacrosLoaded.empty()) {
7505 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007506 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 }
7508
7509 ID -= NUM_PREDEF_MACRO_IDS;
7510 if (!MacrosLoaded[ID]) {
7511 GlobalMacroMapType::iterator I
7512 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7513 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7514 ModuleFile *M = I->second;
7515 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007516 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7517
7518 if (DeserializationListener)
7519 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7520 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007521 }
7522
7523 return MacrosLoaded[ID];
7524}
7525
7526MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7527 if (LocalID < NUM_PREDEF_MACRO_IDS)
7528 return LocalID;
7529
7530 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7531 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7532 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7533
7534 return LocalID + I->second;
7535}
7536
7537serialization::SubmoduleID
7538ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7539 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7540 return LocalID;
7541
7542 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7543 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7544 assert(I != M.SubmoduleRemap.end()
7545 && "Invalid index into submodule index remap");
7546
7547 return LocalID + I->second;
7548}
7549
7550Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7551 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7552 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007553 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007554 }
7555
7556 if (GlobalID > SubmodulesLoaded.size()) {
7557 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007558 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007559 }
7560
7561 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7562}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007563
7564Module *ASTReader::getModule(unsigned ID) {
7565 return getSubmodule(ID);
7566}
7567
Guy Benyei11169dd2012-12-18 14:30:41 +00007568Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7569 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7570}
7571
7572Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7573 if (ID == 0)
7574 return Selector();
7575
7576 if (ID > SelectorsLoaded.size()) {
7577 Error("selector ID out of range in AST file");
7578 return Selector();
7579 }
7580
Craig Toppera13603a2014-05-22 05:54:18 +00007581 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007582 // Load this selector from the selector table.
7583 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7584 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7585 ModuleFile &M = *I->second;
7586 ASTSelectorLookupTrait Trait(*this, M);
7587 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7588 SelectorsLoaded[ID - 1] =
7589 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7590 if (DeserializationListener)
7591 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7592 }
7593
7594 return SelectorsLoaded[ID - 1];
7595}
7596
7597Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7598 return DecodeSelector(ID);
7599}
7600
7601uint32_t ASTReader::GetNumExternalSelectors() {
7602 // ID 0 (the null selector) is considered an external selector.
7603 return getTotalNumSelectors() + 1;
7604}
7605
7606serialization::SelectorID
7607ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7608 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7609 return LocalID;
7610
7611 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7612 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7613 assert(I != M.SelectorRemap.end()
7614 && "Invalid index into selector index remap");
7615
7616 return LocalID + I->second;
7617}
7618
7619DeclarationName
7620ASTReader::ReadDeclarationName(ModuleFile &F,
7621 const RecordData &Record, unsigned &Idx) {
7622 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7623 switch (Kind) {
7624 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007625 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007626
7627 case DeclarationName::ObjCZeroArgSelector:
7628 case DeclarationName::ObjCOneArgSelector:
7629 case DeclarationName::ObjCMultiArgSelector:
7630 return DeclarationName(ReadSelector(F, Record, Idx));
7631
7632 case DeclarationName::CXXConstructorName:
7633 return Context.DeclarationNames.getCXXConstructorName(
7634 Context.getCanonicalType(readType(F, Record, Idx)));
7635
7636 case DeclarationName::CXXDestructorName:
7637 return Context.DeclarationNames.getCXXDestructorName(
7638 Context.getCanonicalType(readType(F, Record, Idx)));
7639
7640 case DeclarationName::CXXConversionFunctionName:
7641 return Context.DeclarationNames.getCXXConversionFunctionName(
7642 Context.getCanonicalType(readType(F, Record, Idx)));
7643
7644 case DeclarationName::CXXOperatorName:
7645 return Context.DeclarationNames.getCXXOperatorName(
7646 (OverloadedOperatorKind)Record[Idx++]);
7647
7648 case DeclarationName::CXXLiteralOperatorName:
7649 return Context.DeclarationNames.getCXXLiteralOperatorName(
7650 GetIdentifierInfo(F, Record, Idx));
7651
7652 case DeclarationName::CXXUsingDirective:
7653 return DeclarationName::getUsingDirectiveName();
7654 }
7655
7656 llvm_unreachable("Invalid NameKind!");
7657}
7658
7659void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7660 DeclarationNameLoc &DNLoc,
7661 DeclarationName Name,
7662 const RecordData &Record, unsigned &Idx) {
7663 switch (Name.getNameKind()) {
7664 case DeclarationName::CXXConstructorName:
7665 case DeclarationName::CXXDestructorName:
7666 case DeclarationName::CXXConversionFunctionName:
7667 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7668 break;
7669
7670 case DeclarationName::CXXOperatorName:
7671 DNLoc.CXXOperatorName.BeginOpNameLoc
7672 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7673 DNLoc.CXXOperatorName.EndOpNameLoc
7674 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7675 break;
7676
7677 case DeclarationName::CXXLiteralOperatorName:
7678 DNLoc.CXXLiteralOperatorName.OpNameLoc
7679 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7680 break;
7681
7682 case DeclarationName::Identifier:
7683 case DeclarationName::ObjCZeroArgSelector:
7684 case DeclarationName::ObjCOneArgSelector:
7685 case DeclarationName::ObjCMultiArgSelector:
7686 case DeclarationName::CXXUsingDirective:
7687 break;
7688 }
7689}
7690
7691void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7692 DeclarationNameInfo &NameInfo,
7693 const RecordData &Record, unsigned &Idx) {
7694 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7695 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7696 DeclarationNameLoc DNLoc;
7697 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7698 NameInfo.setInfo(DNLoc);
7699}
7700
7701void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7702 const RecordData &Record, unsigned &Idx) {
7703 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7704 unsigned NumTPLists = Record[Idx++];
7705 Info.NumTemplParamLists = NumTPLists;
7706 if (NumTPLists) {
7707 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7708 for (unsigned i=0; i != NumTPLists; ++i)
7709 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7710 }
7711}
7712
7713TemplateName
7714ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7715 unsigned &Idx) {
7716 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7717 switch (Kind) {
7718 case TemplateName::Template:
7719 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7720
7721 case TemplateName::OverloadedTemplate: {
7722 unsigned size = Record[Idx++];
7723 UnresolvedSet<8> Decls;
7724 while (size--)
7725 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7726
7727 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7728 }
7729
7730 case TemplateName::QualifiedTemplate: {
7731 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7732 bool hasTemplKeyword = Record[Idx++];
7733 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7734 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7735 }
7736
7737 case TemplateName::DependentTemplate: {
7738 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7739 if (Record[Idx++]) // isIdentifier
7740 return Context.getDependentTemplateName(NNS,
7741 GetIdentifierInfo(F, Record,
7742 Idx));
7743 return Context.getDependentTemplateName(NNS,
7744 (OverloadedOperatorKind)Record[Idx++]);
7745 }
7746
7747 case TemplateName::SubstTemplateTemplateParm: {
7748 TemplateTemplateParmDecl *param
7749 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7750 if (!param) return TemplateName();
7751 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7752 return Context.getSubstTemplateTemplateParm(param, replacement);
7753 }
7754
7755 case TemplateName::SubstTemplateTemplateParmPack: {
7756 TemplateTemplateParmDecl *Param
7757 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7758 if (!Param)
7759 return TemplateName();
7760
7761 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7762 if (ArgPack.getKind() != TemplateArgument::Pack)
7763 return TemplateName();
7764
7765 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7766 }
7767 }
7768
7769 llvm_unreachable("Unhandled template name kind!");
7770}
7771
7772TemplateArgument
7773ASTReader::ReadTemplateArgument(ModuleFile &F,
7774 const RecordData &Record, unsigned &Idx) {
7775 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7776 switch (Kind) {
7777 case TemplateArgument::Null:
7778 return TemplateArgument();
7779 case TemplateArgument::Type:
7780 return TemplateArgument(readType(F, Record, Idx));
7781 case TemplateArgument::Declaration: {
7782 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007783 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 }
7785 case TemplateArgument::NullPtr:
7786 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7787 case TemplateArgument::Integral: {
7788 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7789 QualType T = readType(F, Record, Idx);
7790 return TemplateArgument(Context, Value, T);
7791 }
7792 case TemplateArgument::Template:
7793 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7794 case TemplateArgument::TemplateExpansion: {
7795 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007796 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 if (unsigned NumExpansions = Record[Idx++])
7798 NumTemplateExpansions = NumExpansions - 1;
7799 return TemplateArgument(Name, NumTemplateExpansions);
7800 }
7801 case TemplateArgument::Expression:
7802 return TemplateArgument(ReadExpr(F));
7803 case TemplateArgument::Pack: {
7804 unsigned NumArgs = Record[Idx++];
7805 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7806 for (unsigned I = 0; I != NumArgs; ++I)
7807 Args[I] = ReadTemplateArgument(F, Record, Idx);
7808 return TemplateArgument(Args, NumArgs);
7809 }
7810 }
7811
7812 llvm_unreachable("Unhandled template argument kind!");
7813}
7814
7815TemplateParameterList *
7816ASTReader::ReadTemplateParameterList(ModuleFile &F,
7817 const RecordData &Record, unsigned &Idx) {
7818 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7819 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7820 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7821
7822 unsigned NumParams = Record[Idx++];
7823 SmallVector<NamedDecl *, 16> Params;
7824 Params.reserve(NumParams);
7825 while (NumParams--)
7826 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7827
7828 TemplateParameterList* TemplateParams =
7829 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7830 Params.data(), Params.size(), RAngleLoc);
7831 return TemplateParams;
7832}
7833
7834void
7835ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007836ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 ModuleFile &F, const RecordData &Record,
7838 unsigned &Idx) {
7839 unsigned NumTemplateArgs = Record[Idx++];
7840 TemplArgs.reserve(NumTemplateArgs);
7841 while (NumTemplateArgs--)
7842 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7843}
7844
7845/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007846void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 const RecordData &Record, unsigned &Idx) {
7848 unsigned NumDecls = Record[Idx++];
7849 Set.reserve(Context, NumDecls);
7850 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007851 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007853 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 }
7855}
7856
7857CXXBaseSpecifier
7858ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7859 const RecordData &Record, unsigned &Idx) {
7860 bool isVirtual = static_cast<bool>(Record[Idx++]);
7861 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7862 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7863 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7864 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7865 SourceRange Range = ReadSourceRange(F, Record, Idx);
7866 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7867 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7868 EllipsisLoc);
7869 Result.setInheritConstructors(inheritConstructors);
7870 return Result;
7871}
7872
7873std::pair<CXXCtorInitializer **, unsigned>
7874ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7875 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007876 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007877 unsigned NumInitializers = Record[Idx++];
7878 if (NumInitializers) {
7879 CtorInitializers
7880 = new (Context) CXXCtorInitializer*[NumInitializers];
7881 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007882 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007884 FieldDecl *Member = nullptr;
7885 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007886
7887 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7888 switch (Type) {
7889 case CTOR_INITIALIZER_BASE:
7890 TInfo = GetTypeSourceInfo(F, Record, Idx);
7891 IsBaseVirtual = Record[Idx++];
7892 break;
7893
7894 case CTOR_INITIALIZER_DELEGATING:
7895 TInfo = GetTypeSourceInfo(F, Record, Idx);
7896 break;
7897
7898 case CTOR_INITIALIZER_MEMBER:
7899 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7900 break;
7901
7902 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7903 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7904 break;
7905 }
7906
7907 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7908 Expr *Init = ReadExpr(F);
7909 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7910 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7911 bool IsWritten = Record[Idx++];
7912 unsigned SourceOrderOrNumArrayIndices;
7913 SmallVector<VarDecl *, 8> Indices;
7914 if (IsWritten) {
7915 SourceOrderOrNumArrayIndices = Record[Idx++];
7916 } else {
7917 SourceOrderOrNumArrayIndices = Record[Idx++];
7918 Indices.reserve(SourceOrderOrNumArrayIndices);
7919 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7920 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7921 }
7922
7923 CXXCtorInitializer *BOMInit;
7924 if (Type == CTOR_INITIALIZER_BASE) {
7925 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7926 LParenLoc, Init, RParenLoc,
7927 MemberOrEllipsisLoc);
7928 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7929 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7930 Init, RParenLoc);
7931 } else if (IsWritten) {
7932 if (Member)
7933 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7934 LParenLoc, Init, RParenLoc);
7935 else
7936 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7937 MemberOrEllipsisLoc, LParenLoc,
7938 Init, RParenLoc);
7939 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007940 if (IndirectMember) {
7941 assert(Indices.empty() && "Indirect field improperly initialized");
7942 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7943 MemberOrEllipsisLoc, LParenLoc,
7944 Init, RParenLoc);
7945 } else {
7946 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7947 LParenLoc, Init, RParenLoc,
7948 Indices.data(), Indices.size());
7949 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007950 }
7951
7952 if (IsWritten)
7953 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7954 CtorInitializers[i] = BOMInit;
7955 }
7956 }
7957
7958 return std::make_pair(CtorInitializers, NumInitializers);
7959}
7960
7961NestedNameSpecifier *
7962ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7963 const RecordData &Record, unsigned &Idx) {
7964 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007965 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 for (unsigned I = 0; I != N; ++I) {
7967 NestedNameSpecifier::SpecifierKind Kind
7968 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7969 switch (Kind) {
7970 case NestedNameSpecifier::Identifier: {
7971 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7972 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7973 break;
7974 }
7975
7976 case NestedNameSpecifier::Namespace: {
7977 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7978 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7979 break;
7980 }
7981
7982 case NestedNameSpecifier::NamespaceAlias: {
7983 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7984 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7985 break;
7986 }
7987
7988 case NestedNameSpecifier::TypeSpec:
7989 case NestedNameSpecifier::TypeSpecWithTemplate: {
7990 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7991 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007992 return nullptr;
7993
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 bool Template = Record[Idx++];
7995 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7996 break;
7997 }
7998
7999 case NestedNameSpecifier::Global: {
8000 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8001 // No associated value, and there can't be a prefix.
8002 break;
8003 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008004
8005 case NestedNameSpecifier::Super: {
8006 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8007 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8008 break;
8009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 }
8011 Prev = NNS;
8012 }
8013 return NNS;
8014}
8015
8016NestedNameSpecifierLoc
8017ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8018 unsigned &Idx) {
8019 unsigned N = Record[Idx++];
8020 NestedNameSpecifierLocBuilder Builder;
8021 for (unsigned I = 0; I != N; ++I) {
8022 NestedNameSpecifier::SpecifierKind Kind
8023 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8024 switch (Kind) {
8025 case NestedNameSpecifier::Identifier: {
8026 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8027 SourceRange Range = ReadSourceRange(F, Record, Idx);
8028 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8029 break;
8030 }
8031
8032 case NestedNameSpecifier::Namespace: {
8033 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8034 SourceRange Range = ReadSourceRange(F, Record, Idx);
8035 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8036 break;
8037 }
8038
8039 case NestedNameSpecifier::NamespaceAlias: {
8040 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8041 SourceRange Range = ReadSourceRange(F, Record, Idx);
8042 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8043 break;
8044 }
8045
8046 case NestedNameSpecifier::TypeSpec:
8047 case NestedNameSpecifier::TypeSpecWithTemplate: {
8048 bool Template = Record[Idx++];
8049 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8050 if (!T)
8051 return NestedNameSpecifierLoc();
8052 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8053
8054 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8055 Builder.Extend(Context,
8056 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8057 T->getTypeLoc(), ColonColonLoc);
8058 break;
8059 }
8060
8061 case NestedNameSpecifier::Global: {
8062 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8063 Builder.MakeGlobal(Context, ColonColonLoc);
8064 break;
8065 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008066
8067 case NestedNameSpecifier::Super: {
8068 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8069 SourceRange Range = ReadSourceRange(F, Record, Idx);
8070 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8071 break;
8072 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 }
8074 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008075
Guy Benyei11169dd2012-12-18 14:30:41 +00008076 return Builder.getWithLocInContext(Context);
8077}
8078
8079SourceRange
8080ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8081 unsigned &Idx) {
8082 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8083 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8084 return SourceRange(beg, end);
8085}
8086
8087/// \brief Read an integral value
8088llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8089 unsigned BitWidth = Record[Idx++];
8090 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8091 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8092 Idx += NumWords;
8093 return Result;
8094}
8095
8096/// \brief Read a signed integral value
8097llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8098 bool isUnsigned = Record[Idx++];
8099 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8100}
8101
8102/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008103llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8104 const llvm::fltSemantics &Sem,
8105 unsigned &Idx) {
8106 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008107}
8108
8109// \brief Read a string
8110std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8111 unsigned Len = Record[Idx++];
8112 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8113 Idx += Len;
8114 return Result;
8115}
8116
Richard Smith7ed1bc92014-12-05 22:42:13 +00008117std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8118 unsigned &Idx) {
8119 std::string Filename = ReadString(Record, Idx);
8120 ResolveImportedPath(F, Filename);
8121 return Filename;
8122}
8123
Guy Benyei11169dd2012-12-18 14:30:41 +00008124VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8125 unsigned &Idx) {
8126 unsigned Major = Record[Idx++];
8127 unsigned Minor = Record[Idx++];
8128 unsigned Subminor = Record[Idx++];
8129 if (Minor == 0)
8130 return VersionTuple(Major);
8131 if (Subminor == 0)
8132 return VersionTuple(Major, Minor - 1);
8133 return VersionTuple(Major, Minor - 1, Subminor - 1);
8134}
8135
8136CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8137 const RecordData &Record,
8138 unsigned &Idx) {
8139 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8140 return CXXTemporary::Create(Context, Decl);
8141}
8142
8143DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008144 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008145}
8146
8147DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8148 return Diags.Report(Loc, DiagID);
8149}
8150
8151/// \brief Retrieve the identifier table associated with the
8152/// preprocessor.
8153IdentifierTable &ASTReader::getIdentifierTable() {
8154 return PP.getIdentifierTable();
8155}
8156
8157/// \brief Record that the given ID maps to the given switch-case
8158/// statement.
8159void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008160 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 "Already have a SwitchCase with this ID");
8162 (*CurrSwitchCaseStmts)[ID] = SC;
8163}
8164
8165/// \brief Retrieve the switch-case statement with the given ID.
8166SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008167 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 return (*CurrSwitchCaseStmts)[ID];
8169}
8170
8171void ASTReader::ClearSwitchCaseIDs() {
8172 CurrSwitchCaseStmts->clear();
8173}
8174
8175void ASTReader::ReadComments() {
8176 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008177 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 serialization::ModuleFile *> >::iterator
8179 I = CommentsCursors.begin(),
8180 E = CommentsCursors.end();
8181 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008182 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008183 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 serialization::ModuleFile &F = *I->second;
8185 SavedStreamPosition SavedPosition(Cursor);
8186
8187 RecordData Record;
8188 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008189 llvm::BitstreamEntry Entry =
8190 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008191
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008192 switch (Entry.Kind) {
8193 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8194 case llvm::BitstreamEntry::Error:
8195 Error("malformed block record in AST file");
8196 return;
8197 case llvm::BitstreamEntry::EndBlock:
8198 goto NextCursor;
8199 case llvm::BitstreamEntry::Record:
8200 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 }
8203
8204 // Read a record.
8205 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008206 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 case COMMENTS_RAW_COMMENT: {
8208 unsigned Idx = 0;
8209 SourceRange SR = ReadSourceRange(F, Record, Idx);
8210 RawComment::CommentKind Kind =
8211 (RawComment::CommentKind) Record[Idx++];
8212 bool IsTrailingComment = Record[Idx++];
8213 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008214 Comments.push_back(new (Context) RawComment(
8215 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8216 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 break;
8218 }
8219 }
8220 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008221 NextCursor:
8222 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008224}
8225
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008226void ASTReader::getInputFiles(ModuleFile &F,
8227 SmallVectorImpl<serialization::InputFile> &Files) {
8228 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8229 unsigned ID = I+1;
8230 Files.push_back(getInputFile(F, ID));
8231 }
8232}
8233
Richard Smithcd45dbc2014-04-19 03:48:30 +00008234std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8235 // If we know the owning module, use it.
8236 if (Module *M = D->getOwningModule())
8237 return M->getFullModuleName();
8238
8239 // Otherwise, use the name of the top-level module the decl is within.
8240 if (ModuleFile *M = getOwningModuleFile(D))
8241 return M->ModuleName;
8242
8243 // Not from a module.
8244 return "";
8245}
8246
Guy Benyei11169dd2012-12-18 14:30:41 +00008247void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008248 while (!PendingIdentifierInfos.empty() ||
8249 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008250 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008251 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 // If any identifiers with corresponding top-level declarations have
8253 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008254 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8255 TopLevelDeclsMap;
8256 TopLevelDeclsMap TopLevelDecls;
8257
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008259 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008260 SmallVector<uint32_t, 4> DeclIDs =
8261 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008262 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008263
8264 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008266
Richard Smith851072e2014-05-19 20:59:20 +00008267 // For each decl chain that we wanted to complete while deserializing, mark
8268 // it as "still needs to be completed".
8269 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8270 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8271 }
8272 PendingIncompleteDeclChains.clear();
8273
Guy Benyei11169dd2012-12-18 14:30:41 +00008274 // Load pending declaration chains.
8275 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8276 loadPendingDeclChain(PendingDeclChains[I]);
8277 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8278 }
8279 PendingDeclChains.clear();
8280
Douglas Gregor6168bd22013-02-18 15:53:43 +00008281 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008282 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8283 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008284 IdentifierInfo *II = TLD->first;
8285 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008286 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008287 }
8288 }
8289
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 // Load any pending macro definitions.
8291 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008292 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8293 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8294 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8295 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008296 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008297 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008298 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008299 if (Info.M->Kind != MK_ImplicitModule &&
8300 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008301 resolvePendingMacro(II, Info);
8302 }
8303 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008304 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008305 ++IDIdx) {
8306 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008307 if (Info.M->Kind == MK_ImplicitModule ||
8308 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008309 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 }
8311 }
8312 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008313
8314 // Wire up the DeclContexts for Decls that we delayed setting until
8315 // recursive loading is completed.
8316 while (!PendingDeclContextInfos.empty()) {
8317 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8318 PendingDeclContextInfos.pop_front();
8319 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8320 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8321 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8322 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008323
Richard Smithd1c46742014-04-30 02:24:17 +00008324 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008325 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008326 auto Update = PendingUpdateRecords.pop_back_val();
8327 ReadingKindTracker ReadingKind(Read_Decl, *this);
8328 loadDeclUpdateRecords(Update.first, Update.second);
8329 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 }
Richard Smith8a639892015-01-24 01:07:20 +00008331
8332 // At this point, all update records for loaded decls are in place, so any
8333 // fake class definitions should have become real.
8334 assert(PendingFakeDefinitionData.empty() &&
8335 "faked up a class definition but never saw the real one");
8336
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 // If we deserialized any C++ or Objective-C class definitions, any
8338 // Objective-C protocol definitions, or any redeclarable templates, make sure
8339 // that all redeclarations point to the definitions. Note that this can only
8340 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008341 for (Decl *D : PendingDefinitions) {
8342 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008343 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008344 // Make sure that the TagType points at the definition.
8345 const_cast<TagType*>(TagT)->decl = TD;
8346 }
8347
Craig Topperc6914d02014-08-25 04:15:02 +00008348 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008349 for (auto R : RD->redecls()) {
8350 assert((R == D) == R->isThisDeclarationADefinition() &&
8351 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008352 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008353 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
8355
8356 continue;
8357 }
8358
Craig Topperc6914d02014-08-25 04:15:02 +00008359 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 // Make sure that the ObjCInterfaceType points at the definition.
8361 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8362 ->Decl = ID;
8363
Aaron Ballman86c93902014-03-06 23:45:36 +00008364 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 R->Data = ID->Data;
8366
8367 continue;
8368 }
8369
Craig Topperc6914d02014-08-25 04:15:02 +00008370 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008371 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 R->Data = PD->Data;
8373
8374 continue;
8375 }
8376
Craig Topperc6914d02014-08-25 04:15:02 +00008377 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008378 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 R->Common = RTD->Common;
8380 }
8381 PendingDefinitions.clear();
8382
8383 // Load the bodies of any functions or methods we've encountered. We do
8384 // this now (delayed) so that we can be sure that the declaration chains
8385 // have been fully wired up.
8386 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8387 PBEnd = PendingBodies.end();
8388 PB != PBEnd; ++PB) {
8389 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8390 // FIXME: Check for =delete/=default?
8391 // FIXME: Complain about ODR violations here?
8392 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8393 FD->setLazyBody(PB->second);
8394 continue;
8395 }
8396
8397 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8398 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8399 MD->setLazyBody(PB->second);
8400 }
8401 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008402}
8403
8404void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008405 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8406 return;
8407
Richard Smitha0ce9c42014-07-29 23:23:27 +00008408 // Trigger the import of the full definition of each class that had any
8409 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008410 // These updates may in turn find and diagnose some ODR failures, so take
8411 // ownership of the set first.
8412 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8413 PendingOdrMergeFailures.clear();
8414 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008415 Merge.first->buildLookup();
8416 Merge.first->decls_begin();
8417 Merge.first->bases_begin();
8418 Merge.first->vbases_begin();
8419 for (auto *RD : Merge.second) {
8420 RD->decls_begin();
8421 RD->bases_begin();
8422 RD->vbases_begin();
8423 }
8424 }
8425
8426 // For each declaration from a merged context, check that the canonical
8427 // definition of that context also contains a declaration of the same
8428 // entity.
8429 //
8430 // Caution: this loop does things that might invalidate iterators into
8431 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8432 while (!PendingOdrMergeChecks.empty()) {
8433 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8434
8435 // FIXME: Skip over implicit declarations for now. This matters for things
8436 // like implicitly-declared special member functions. This isn't entirely
8437 // correct; we can end up with multiple unmerged declarations of the same
8438 // implicit entity.
8439 if (D->isImplicit())
8440 continue;
8441
8442 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008443
8444 bool Found = false;
8445 const Decl *DCanon = D->getCanonicalDecl();
8446
Richard Smith01bdb7a2014-08-28 05:44:07 +00008447 for (auto RI : D->redecls()) {
8448 if (RI->getLexicalDeclContext() == CanonDef) {
8449 Found = true;
8450 break;
8451 }
8452 }
8453 if (Found)
8454 continue;
8455
Richard Smitha0ce9c42014-07-29 23:23:27 +00008456 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008457 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008458 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8459 !Found && I != E; ++I) {
8460 for (auto RI : (*I)->redecls()) {
8461 if (RI->getLexicalDeclContext() == CanonDef) {
8462 // This declaration is present in the canonical definition. If it's
8463 // in the same redecl chain, it's the one we're looking for.
8464 if (RI->getCanonicalDecl() == DCanon)
8465 Found = true;
8466 else
8467 Candidates.push_back(cast<NamedDecl>(RI));
8468 break;
8469 }
8470 }
8471 }
8472
8473 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008474 // The AST doesn't like TagDecls becoming invalid after they've been
8475 // completed. We only really need to mark FieldDecls as invalid here.
8476 if (!isa<TagDecl>(D))
8477 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008478
8479 std::string CanonDefModule =
8480 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8481 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8482 << D << getOwningModuleNameForDiagnostic(D)
8483 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8484
8485 if (Candidates.empty())
8486 Diag(cast<Decl>(CanonDef)->getLocation(),
8487 diag::note_module_odr_violation_no_possible_decls) << D;
8488 else {
8489 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8490 Diag(Candidates[I]->getLocation(),
8491 diag::note_module_odr_violation_possible_decl)
8492 << Candidates[I];
8493 }
8494
8495 DiagnosedOdrMergeFailures.insert(CanonDef);
8496 }
8497 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008498
8499 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008500 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008501 // If we've already pointed out a specific problem with this class, don't
8502 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008503 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008504 continue;
8505
8506 bool Diagnosed = false;
8507 for (auto *RD : Merge.second) {
8508 // Multiple different declarations got merged together; tell the user
8509 // where they came from.
8510 if (Merge.first != RD) {
8511 // FIXME: Walk the definition, figure out what's different,
8512 // and diagnose that.
8513 if (!Diagnosed) {
8514 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8515 Diag(Merge.first->getLocation(),
8516 diag::err_module_odr_violation_different_definitions)
8517 << Merge.first << Module.empty() << Module;
8518 Diagnosed = true;
8519 }
8520
8521 Diag(RD->getLocation(),
8522 diag::note_module_odr_violation_different_definitions)
8523 << getOwningModuleNameForDiagnostic(RD);
8524 }
8525 }
8526
8527 if (!Diagnosed) {
8528 // All definitions are updates to the same declaration. This happens if a
8529 // module instantiates the declaration of a class template specialization
8530 // and two or more other modules instantiate its definition.
8531 //
8532 // FIXME: Indicate which modules had instantiations of this definition.
8533 // FIXME: How can this even happen?
8534 Diag(Merge.first->getLocation(),
8535 diag::err_module_odr_violation_different_instantiations)
8536 << Merge.first;
8537 }
8538 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008539}
8540
8541void ASTReader::FinishedDeserializing() {
8542 assert(NumCurrentElementsDeserializing &&
8543 "FinishedDeserializing not paired with StartedDeserializing");
8544 if (NumCurrentElementsDeserializing == 1) {
8545 // We decrease NumCurrentElementsDeserializing only after pending actions
8546 // are finished, to avoid recursively re-calling finishPendingActions().
8547 finishPendingActions();
8548 }
8549 --NumCurrentElementsDeserializing;
8550
Richard Smitha0ce9c42014-07-29 23:23:27 +00008551 if (NumCurrentElementsDeserializing == 0) {
8552 diagnoseOdrViolations();
8553
Richard Smith04d05b52014-03-23 00:27:18 +00008554 // We are not in recursive loading, so it's safe to pass the "interesting"
8555 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008556 if (Consumer)
8557 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 }
8559}
8560
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008561void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008562 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008563
8564 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8565 SemaObj->TUScope->AddDecl(D);
8566 } else if (SemaObj->TUScope) {
8567 // Adding the decl to IdResolver may have failed because it was already in
8568 // (even though it was not added in scope). If it is already in, make sure
8569 // it gets in the scope as well.
8570 if (std::find(SemaObj->IdResolver.begin(Name),
8571 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8572 SemaObj->TUScope->AddDecl(D);
8573 }
8574}
8575
Nico Weber824285e2014-05-08 04:26:47 +00008576ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8577 bool DisableValidation, bool AllowASTWithCompilerErrors,
8578 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008579 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008580 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008581 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008582 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8583 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8584 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8585 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008586 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8587 AllowConfigurationMismatch(AllowConfigurationMismatch),
8588 ValidateSystemInputs(ValidateSystemInputs),
8589 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008590 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008591 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8592 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8593 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8594 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8595 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8596 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8597 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8598 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8599 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8600 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8601 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008602 SourceMgr.setExternalSLocEntrySource(this);
8603}
8604
8605ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008606 if (OwnsDeserializationListener)
8607 delete DeserializationListener;
8608
Guy Benyei11169dd2012-12-18 14:30:41 +00008609 for (DeclContextVisibleUpdatesPending::iterator
8610 I = PendingVisibleUpdates.begin(),
8611 E = PendingVisibleUpdates.end();
8612 I != E; ++I) {
8613 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8614 F = I->second.end();
8615 J != F; ++J)
8616 delete J->first;
8617 }
8618}