blob: ff0b1dd62949f4ae000457a7a566906793e65c6f [file] [log] [blame]
Nick Lewycky995e26b2013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei7f92f2d2012-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"
25#include "clang/Basic/FileManager.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/SourceManagerInternals.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Basic/TargetOptions.h"
30#include "clang/Basic/Version.h"
31#include "clang/Basic/VersionTuple.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/MacroInfo.h"
35#include "clang/Lex/PreprocessingRecord.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/PreprocessorOptions.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregor1a49d972013-01-25 01:03:03 +000041#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000042#include "clang/Serialization/ModuleManager.h"
43#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Bitcode/BitstreamReader.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Path.h"
51#include "llvm/Support/SaveAndRestore.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070052#include "llvm/Support/raw_ostream.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000053#include "llvm/Support/system_error.h"
54#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000055#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000056#include <iterator>
57
58using namespace clang;
59using namespace clang::serialization;
60using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000061using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000062
Stephen Hines651f13c2014-04-23 16:59:28 -070063
64//===----------------------------------------------------------------------===//
65// ChainedASTReaderListener implementation
66//===----------------------------------------------------------------------===//
67
68bool
69ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
70 return First->ReadFullVersionInformation(FullVersion) ||
71 Second->ReadFullVersionInformation(FullVersion);
72}
73bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
74 bool Complain) {
75 return First->ReadLanguageOptions(LangOpts, Complain) ||
76 Second->ReadLanguageOptions(LangOpts, Complain);
77}
78bool
79ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
80 bool Complain) {
81 return First->ReadTargetOptions(TargetOpts, Complain) ||
82 Second->ReadTargetOptions(TargetOpts, Complain);
83}
84bool ChainedASTReaderListener::ReadDiagnosticOptions(
85 const DiagnosticOptions &DiagOpts, bool Complain) {
86 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
87 Second->ReadDiagnosticOptions(DiagOpts, Complain);
88}
89bool
90ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
91 bool Complain) {
92 return First->ReadFileSystemOptions(FSOpts, Complain) ||
93 Second->ReadFileSystemOptions(FSOpts, Complain);
94}
95
96bool ChainedASTReaderListener::ReadHeaderSearchOptions(
97 const HeaderSearchOptions &HSOpts, bool Complain) {
98 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
99 Second->ReadHeaderSearchOptions(HSOpts, Complain);
100}
101bool ChainedASTReaderListener::ReadPreprocessorOptions(
102 const PreprocessorOptions &PPOpts, bool Complain,
103 std::string &SuggestedPredefines) {
104 return First->ReadPreprocessorOptions(PPOpts, Complain,
105 SuggestedPredefines) ||
106 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
107}
108void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
109 unsigned Value) {
110 First->ReadCounter(M, Value);
111 Second->ReadCounter(M, Value);
112}
113bool ChainedASTReaderListener::needsInputFileVisitation() {
114 return First->needsInputFileVisitation() ||
115 Second->needsInputFileVisitation();
116}
117bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
118 return First->needsSystemInputFileVisitation() ||
119 Second->needsSystemInputFileVisitation();
120}
121void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
122 First->visitModuleFile(Filename);
123 Second->visitModuleFile(Filename);
124}
125bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
126 bool isSystem,
127 bool isOverridden) {
128 return First->visitInputFile(Filename, isSystem, isOverridden) ||
129 Second->visitInputFile(Filename, isSystem, isOverridden);
130}
131
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000132//===----------------------------------------------------------------------===//
133// PCH validator implementation
134//===----------------------------------------------------------------------===//
135
136ASTReaderListener::~ASTReaderListener() {}
137
138/// \brief Compare the given set of language options against an existing set of
139/// language options.
140///
141/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
142///
143/// \returns true if the languagae options mis-match, false otherwise.
144static bool checkLanguageOptions(const LangOptions &LangOpts,
145 const LangOptions &ExistingLangOpts,
146 DiagnosticsEngine *Diags) {
147#define LANGOPT(Name, Bits, Default, Description) \
148 if (ExistingLangOpts.Name != LangOpts.Name) { \
149 if (Diags) \
150 Diags->Report(diag::err_pch_langopt_mismatch) \
151 << Description << LangOpts.Name << ExistingLangOpts.Name; \
152 return true; \
153 }
154
155#define VALUE_LANGOPT(Name, Bits, Default, Description) \
156 if (ExistingLangOpts.Name != LangOpts.Name) { \
157 if (Diags) \
158 Diags->Report(diag::err_pch_langopt_value_mismatch) \
159 << Description; \
160 return true; \
161 }
162
163#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
164 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_value_mismatch) \
167 << Description; \
168 return true; \
169 }
170
171#define BENIGN_LANGOPT(Name, Bits, Default, Description)
172#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
173#include "clang/Basic/LangOptions.def"
174
175 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
176 if (Diags)
177 Diags->Report(diag::err_pch_langopt_value_mismatch)
178 << "target Objective-C runtime";
179 return true;
180 }
181
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000182 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
183 LangOpts.CommentOpts.BlockCommandNames) {
184 if (Diags)
185 Diags->Report(diag::err_pch_langopt_value_mismatch)
186 << "block command names";
187 return true;
188 }
189
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000190 return false;
191}
192
193/// \brief Compare the given set of target options against an existing set of
194/// target options.
195///
196/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
197///
198/// \returns true if the target options mis-match, false otherwise.
199static bool checkTargetOptions(const TargetOptions &TargetOpts,
200 const TargetOptions &ExistingTargetOpts,
201 DiagnosticsEngine *Diags) {
202#define CHECK_TARGET_OPT(Field, Name) \
203 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
204 if (Diags) \
205 Diags->Report(diag::err_pch_targetopt_mismatch) \
206 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
207 return true; \
208 }
209
210 CHECK_TARGET_OPT(Triple, "target");
211 CHECK_TARGET_OPT(CPU, "target CPU");
212 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000213 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
214#undef CHECK_TARGET_OPT
215
216 // Compare feature sets.
217 SmallVector<StringRef, 4> ExistingFeatures(
218 ExistingTargetOpts.FeaturesAsWritten.begin(),
219 ExistingTargetOpts.FeaturesAsWritten.end());
220 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
221 TargetOpts.FeaturesAsWritten.end());
222 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
223 std::sort(ReadFeatures.begin(), ReadFeatures.end());
224
225 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
226 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
227 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
228 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
229 ++ExistingIdx;
230 ++ReadIdx;
231 continue;
232 }
233
234 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
235 if (Diags)
236 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
237 << false << ReadFeatures[ReadIdx];
238 return true;
239 }
240
241 if (Diags)
242 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
243 << true << ExistingFeatures[ExistingIdx];
244 return true;
245 }
246
247 if (ExistingIdx < ExistingN) {
248 if (Diags)
249 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
250 << true << ExistingFeatures[ExistingIdx];
251 return true;
252 }
253
254 if (ReadIdx < ReadN) {
255 if (Diags)
256 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
257 << false << ReadFeatures[ReadIdx];
258 return true;
259 }
260
261 return false;
262}
263
264bool
265PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
266 bool Complain) {
267 const LangOptions &ExistingLangOpts = PP.getLangOpts();
268 return checkLanguageOptions(LangOpts, ExistingLangOpts,
269 Complain? &Reader.Diags : 0);
270}
271
272bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
273 bool Complain) {
274 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
275 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
276 Complain? &Reader.Diags : 0);
277}
278
279namespace {
280 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
281 MacroDefinitionsMap;
Craig Topper8ae63872013-07-05 04:43:31 +0000282 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
283 DeclsMap;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000284}
285
286/// \brief Collect the macro definitions provided by the given preprocessor
287/// options.
288static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
289 MacroDefinitionsMap &Macros,
290 SmallVectorImpl<StringRef> *MacroNames = 0){
291 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
292 StringRef Macro = PPOpts.Macros[I].first;
293 bool IsUndef = PPOpts.Macros[I].second;
294
295 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
296 StringRef MacroName = MacroPair.first;
297 StringRef MacroBody = MacroPair.second;
298
299 // For an #undef'd macro, we only care about the name.
300 if (IsUndef) {
301 if (MacroNames && !Macros.count(MacroName))
302 MacroNames->push_back(MacroName);
303
304 Macros[MacroName] = std::make_pair("", true);
305 continue;
306 }
307
308 // For a #define'd macro, figure out the actual definition.
309 if (MacroName.size() == Macro.size())
310 MacroBody = "1";
311 else {
312 // Note: GCC drops anything following an end-of-line character.
313 StringRef::size_type End = MacroBody.find_first_of("\n\r");
314 MacroBody = MacroBody.substr(0, End);
315 }
316
317 if (MacroNames && !Macros.count(MacroName))
318 MacroNames->push_back(MacroName);
319 Macros[MacroName] = std::make_pair(MacroBody, false);
320 }
321}
322
323/// \brief Check the preprocessor options deserialized from the control block
324/// against the preprocessor options in an existing preprocessor.
325///
326/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
327static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
328 const PreprocessorOptions &ExistingPPOpts,
329 DiagnosticsEngine *Diags,
330 FileManager &FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000331 std::string &SuggestedPredefines,
332 const LangOptions &LangOpts) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000333 // Check macro definitions.
334 MacroDefinitionsMap ASTFileMacros;
335 collectMacroDefinitions(PPOpts, ASTFileMacros);
336 MacroDefinitionsMap ExistingMacros;
337 SmallVector<StringRef, 4> ExistingMacroNames;
338 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
339
340 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
341 // Dig out the macro definition in the existing preprocessor options.
342 StringRef MacroName = ExistingMacroNames[I];
343 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
344
345 // Check whether we know anything about this macro name or not.
346 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
347 = ASTFileMacros.find(MacroName);
348 if (Known == ASTFileMacros.end()) {
349 // FIXME: Check whether this identifier was referenced anywhere in the
350 // AST file. If so, we should reject the AST file. Unfortunately, this
351 // information isn't in the control block. What shall we do about it?
352
353 if (Existing.second) {
354 SuggestedPredefines += "#undef ";
355 SuggestedPredefines += MacroName.str();
356 SuggestedPredefines += '\n';
357 } else {
358 SuggestedPredefines += "#define ";
359 SuggestedPredefines += MacroName.str();
360 SuggestedPredefines += ' ';
361 SuggestedPredefines += Existing.first.str();
362 SuggestedPredefines += '\n';
363 }
364 continue;
365 }
366
367 // If the macro was defined in one but undef'd in the other, we have a
368 // conflict.
369 if (Existing.second != Known->second.second) {
370 if (Diags) {
371 Diags->Report(diag::err_pch_macro_def_undef)
372 << MacroName << Known->second.second;
373 }
374 return true;
375 }
376
377 // If the macro was #undef'd in both, or if the macro bodies are identical,
378 // it's fine.
379 if (Existing.second || Existing.first == Known->second.first)
380 continue;
381
382 // The macro bodies differ; complain.
383 if (Diags) {
384 Diags->Report(diag::err_pch_macro_def_conflict)
385 << MacroName << Known->second.first << Existing.first;
386 }
387 return true;
388 }
389
390 // Check whether we're using predefines.
391 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
392 if (Diags) {
393 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
394 }
395 return true;
396 }
397
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000398 // Detailed record is important since it is used for the module cache hash.
399 if (LangOpts.Modules &&
400 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
401 if (Diags) {
402 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
403 }
404 return true;
405 }
406
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000407 // Compute the #include and #include_macros lines we need.
408 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
409 StringRef File = ExistingPPOpts.Includes[I];
410 if (File == ExistingPPOpts.ImplicitPCHInclude)
411 continue;
412
413 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
414 != PPOpts.Includes.end())
415 continue;
416
417 SuggestedPredefines += "#include \"";
418 SuggestedPredefines +=
419 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
420 SuggestedPredefines += "\"\n";
421 }
422
423 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
424 StringRef File = ExistingPPOpts.MacroIncludes[I];
425 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
426 File)
427 != PPOpts.MacroIncludes.end())
428 continue;
429
430 SuggestedPredefines += "#__include_macros \"";
431 SuggestedPredefines +=
432 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
433 SuggestedPredefines += "\"\n##\n";
434 }
435
436 return false;
437}
438
439bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
440 bool Complain,
441 std::string &SuggestedPredefines) {
442 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
443
444 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
445 Complain? &Reader.Diags : 0,
446 PP.getFileManager(),
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000447 SuggestedPredefines,
448 PP.getLangOpts());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000449}
450
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000451void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
452 PP.setCounterValue(Value);
453}
454
455//===----------------------------------------------------------------------===//
456// AST reader implementation
457//===----------------------------------------------------------------------===//
458
459void
460ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
461 DeserializationListener = Listener;
462}
463
464
465
466unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
467 return serialization::ComputeHash(Sel);
468}
469
470
471std::pair<unsigned, unsigned>
472ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700473 using namespace llvm::support;
474 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
475 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000476 return std::make_pair(KeyLen, DataLen);
477}
478
479ASTSelectorLookupTrait::internal_key_type
480ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700481 using namespace llvm::support;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000482 SelectorTable &SelTable = Reader.getContext().Selectors;
Stephen Hines651f13c2014-04-23 16:59:28 -0700483 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
484 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
485 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000486 if (N == 0)
487 return SelTable.getNullarySelector(FirstII);
488 else if (N == 1)
489 return SelTable.getUnarySelector(FirstII);
490
491 SmallVector<IdentifierInfo *, 16> Args;
492 Args.push_back(FirstII);
493 for (unsigned I = 1; I != N; ++I)
Stephen Hines651f13c2014-04-23 16:59:28 -0700494 Args.push_back(Reader.getLocalIdentifier(
495 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000496
497 return SelTable.getSelector(N, Args.data());
498}
499
500ASTSelectorLookupTrait::data_type
501ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
502 unsigned DataLen) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700503 using namespace llvm::support;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000504
505 data_type Result;
506
Stephen Hines651f13c2014-04-23 16:59:28 -0700507 Result.ID = Reader.getGlobalSelectorID(
508 F, endian::readNext<uint32_t, little, unaligned>(d));
509 unsigned NumInstanceMethodsAndBits =
510 endian::readNext<uint16_t, little, unaligned>(d);
511 unsigned NumFactoryMethodsAndBits =
512 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +0000513 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
514 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
515 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
516 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000517
518 // Load instance methods
519 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700520 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
521 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000522 Result.Instance.push_back(Method);
523 }
524
525 // Load factory methods
526 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700527 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
528 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000529 Result.Factory.push_back(Method);
530 }
531
532 return Result;
533}
534
Douglas Gregor479633c2013-01-23 18:53:14 +0000535unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
536 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000537}
538
539std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000540ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700541 using namespace llvm::support;
542 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
543 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000544 return std::make_pair(KeyLen, DataLen);
545}
546
Douglas Gregor479633c2013-01-23 18:53:14 +0000547ASTIdentifierLookupTraitBase::internal_key_type
548ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000549 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000550 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000551}
552
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000553/// \brief Whether the given identifier is "interesting".
554static bool isInterestingIdentifier(IdentifierInfo &II) {
555 return II.isPoisoned() ||
556 II.isExtensionToken() ||
557 II.getObjCOrBuiltinID() ||
558 II.hasRevertedTokenIDToIdentifier() ||
559 II.hadMacroDefinition() ||
560 II.getFETokenInfo<void>();
561}
562
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000563IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
564 const unsigned char* d,
565 unsigned DataLen) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700566 using namespace llvm::support;
567 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000568 bool IsInteresting = RawID & 0x01;
569
570 // Wipe out the "is interesting" bit.
571 RawID = RawID >> 1;
572
573 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
574 if (!IsInteresting) {
575 // For uninteresting identifiers, just build the IdentifierInfo
576 // and associate it with the persistent ID.
577 IdentifierInfo *II = KnownII;
578 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000579 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000580 KnownII = II;
581 }
582 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000583 if (!II->isFromAST()) {
584 bool WasInteresting = isInterestingIdentifier(*II);
585 II->setIsFromAST();
586 if (WasInteresting)
587 II->setChangedSinceDeserialization();
588 }
589 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000590 return II;
591 }
592
Stephen Hines651f13c2014-04-23 16:59:28 -0700593 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
594 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 bool CPlusPlusOperatorKeyword = Bits & 0x01;
596 Bits >>= 1;
597 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
598 Bits >>= 1;
599 bool Poisoned = Bits & 0x01;
600 Bits >>= 1;
601 bool ExtensionToken = Bits & 0x01;
602 Bits >>= 1;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000603 bool hasSubmoduleMacros = Bits & 0x01;
604 Bits >>= 1;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000605 bool hadMacroDefinition = Bits & 0x01;
606 Bits >>= 1;
607
608 assert(Bits == 0 && "Extra bits in the identifier?");
609 DataLen -= 8;
610
611 // Build the IdentifierInfo itself and link the identifier ID with
612 // the new IdentifierInfo.
613 IdentifierInfo *II = KnownII;
614 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000615 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000616 KnownII = II;
617 }
618 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000619 if (!II->isFromAST()) {
620 bool WasInteresting = isInterestingIdentifier(*II);
621 II->setIsFromAST();
622 if (WasInteresting)
623 II->setChangedSinceDeserialization();
624 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000625
626 // Set or check the various bits in the IdentifierInfo structure.
627 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000628 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000629 II->RevertTokenIDToIdentifier();
630 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
631 assert(II->isExtensionToken() == ExtensionToken &&
632 "Incorrect extension token flag");
633 (void)ExtensionToken;
634 if (Poisoned)
635 II->setIsPoisoned(true);
636 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
637 "Incorrect C++ operator keyword flag");
638 (void)CPlusPlusOperatorKeyword;
639
640 // If this identifier is a macro, deserialize the macro
641 // definition.
642 if (hadMacroDefinition) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700643 uint32_t MacroDirectivesOffset =
644 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000645 DataLen -= 4;
646 SmallVector<uint32_t, 8> LocalMacroIDs;
647 if (hasSubmoduleMacros) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700648 while (uint32_t LocalMacroID =
649 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000650 DataLen -= 4;
651 LocalMacroIDs.push_back(LocalMacroID);
652 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000653 DataLen -= 4;
654 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000655
656 if (F.Kind == MK_Module) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700657 // Macro definitions are stored from newest to oldest, so reverse them
658 // before registering them.
659 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000660 for (SmallVectorImpl<uint32_t>::iterator
Stephen Hines651f13c2014-04-23 16:59:28 -0700661 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
662 unsigned Size = 1;
663
664 static const uint32_t HasOverridesFlag = 0x80000000U;
665 if (I + 1 != E && (I[1] & HasOverridesFlag))
666 Size += 1 + (I[1] & ~HasOverridesFlag);
667
668 MacroSizes.push_back(Size);
669 I += Size;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000670 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700671
672 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
673 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
674 SE = MacroSizes.rend();
675 SI != SE; ++SI) {
676 I -= *SI;
677
678 uint32_t LocalMacroID = *I;
679 llvm::ArrayRef<uint32_t> Overrides;
680 if (*SI != 1)
681 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
682 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
683 }
684 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000685 } else {
686 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
687 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000688 }
689
690 Reader.SetIdentifierInfo(ID, II);
691
692 // Read all of the declarations visible at global scope with this
693 // name.
694 if (DataLen > 0) {
695 SmallVector<uint32_t, 4> DeclIDs;
696 for (; DataLen > 0; DataLen -= 4)
Stephen Hines651f13c2014-04-23 16:59:28 -0700697 DeclIDs.push_back(Reader.getGlobalDeclID(
698 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000699 Reader.SetGloballyVisibleDecls(II, DeclIDs);
700 }
701
702 return II;
703}
704
705unsigned
706ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
707 llvm::FoldingSetNodeID ID;
708 ID.AddInteger(Key.Kind);
709
710 switch (Key.Kind) {
711 case DeclarationName::Identifier:
712 case DeclarationName::CXXLiteralOperatorName:
713 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
714 break;
715 case DeclarationName::ObjCZeroArgSelector:
716 case DeclarationName::ObjCOneArgSelector:
717 case DeclarationName::ObjCMultiArgSelector:
718 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
719 break;
720 case DeclarationName::CXXOperatorName:
721 ID.AddInteger((OverloadedOperatorKind)Key.Data);
722 break;
723 case DeclarationName::CXXConstructorName:
724 case DeclarationName::CXXDestructorName:
725 case DeclarationName::CXXConversionFunctionName:
726 case DeclarationName::CXXUsingDirective:
727 break;
728 }
729
730 return ID.ComputeHash();
731}
732
733ASTDeclContextNameLookupTrait::internal_key_type
734ASTDeclContextNameLookupTrait::GetInternalKey(
735 const external_key_type& Name) const {
736 DeclNameKey Key;
737 Key.Kind = Name.getNameKind();
738 switch (Name.getNameKind()) {
739 case DeclarationName::Identifier:
740 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
741 break;
742 case DeclarationName::ObjCZeroArgSelector:
743 case DeclarationName::ObjCOneArgSelector:
744 case DeclarationName::ObjCMultiArgSelector:
745 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
746 break;
747 case DeclarationName::CXXOperatorName:
748 Key.Data = Name.getCXXOverloadedOperator();
749 break;
750 case DeclarationName::CXXLiteralOperatorName:
751 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
752 break;
753 case DeclarationName::CXXConstructorName:
754 case DeclarationName::CXXDestructorName:
755 case DeclarationName::CXXConversionFunctionName:
756 case DeclarationName::CXXUsingDirective:
757 Key.Data = 0;
758 break;
759 }
760
761 return Key;
762}
763
764std::pair<unsigned, unsigned>
765ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700766 using namespace llvm::support;
767 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
768 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000769 return std::make_pair(KeyLen, DataLen);
770}
771
772ASTDeclContextNameLookupTrait::internal_key_type
773ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700774 using namespace llvm::support;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000775
776 DeclNameKey Key;
777 Key.Kind = (DeclarationName::NameKind)*d++;
778 switch (Key.Kind) {
779 case DeclarationName::Identifier:
Stephen Hines651f13c2014-04-23 16:59:28 -0700780 Key.Data = (uint64_t)Reader.getLocalIdentifier(
781 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000782 break;
783 case DeclarationName::ObjCZeroArgSelector:
784 case DeclarationName::ObjCOneArgSelector:
785 case DeclarationName::ObjCMultiArgSelector:
786 Key.Data =
Stephen Hines651f13c2014-04-23 16:59:28 -0700787 (uint64_t)Reader.getLocalSelector(
788 F, endian::readNext<uint32_t, little, unaligned>(
789 d)).getAsOpaquePtr();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000790 break;
791 case DeclarationName::CXXOperatorName:
792 Key.Data = *d++; // OverloadedOperatorKind
793 break;
794 case DeclarationName::CXXLiteralOperatorName:
Stephen Hines651f13c2014-04-23 16:59:28 -0700795 Key.Data = (uint64_t)Reader.getLocalIdentifier(
796 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000797 break;
798 case DeclarationName::CXXConstructorName:
799 case DeclarationName::CXXDestructorName:
800 case DeclarationName::CXXConversionFunctionName:
801 case DeclarationName::CXXUsingDirective:
802 Key.Data = 0;
803 break;
804 }
805
806 return Key;
807}
808
809ASTDeclContextNameLookupTrait::data_type
810ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
811 const unsigned char* d,
812 unsigned DataLen) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700813 using namespace llvm::support;
814 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000815 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
816 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000817 return std::make_pair(Start, Start + NumDecls);
818}
819
820bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000821 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000822 const std::pair<uint64_t, uint64_t> &Offsets,
823 DeclContextInfo &Info) {
824 SavedStreamPosition SavedPosition(Cursor);
825 // First the lexical decls.
826 if (Offsets.first != 0) {
827 Cursor.JumpToBit(Offsets.first);
828
829 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000830 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000831 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000832 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000833 if (RecCode != DECL_CONTEXT_LEXICAL) {
834 Error("Expected lexical block");
835 return true;
836 }
837
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000838 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
839 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000840 }
841
842 // Now the lookup table.
843 if (Offsets.second != 0) {
844 Cursor.JumpToBit(Offsets.second);
845
846 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000847 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000848 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000849 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000850 if (RecCode != DECL_CONTEXT_VISIBLE) {
851 Error("Expected visible lookup table block");
852 return true;
853 }
854 Info.NameLookupTableData
855 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000856 (const unsigned char *)Blob.data() + Record[0],
857 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000858 ASTDeclContextNameLookupTrait(*this, M));
859 }
860
861 return false;
862}
863
864void ASTReader::Error(StringRef Msg) {
865 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregorc1478612013-05-10 22:15:13 +0000866 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
867 Diag(diag::note_module_cache_path)
868 << PP.getHeaderSearchInfo().getModuleCachePath();
869 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000870}
871
872void ASTReader::Error(unsigned DiagID,
873 StringRef Arg1, StringRef Arg2) {
874 if (Diags.isDiagnosticInFlight())
875 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
876 else
877 Diag(DiagID) << Arg1 << Arg2;
878}
879
880//===----------------------------------------------------------------------===//
881// Source Manager Deserialization
882//===----------------------------------------------------------------------===//
883
884/// \brief Read the line table in the source manager block.
885/// \returns true if there was an error.
886bool ASTReader::ParseLineTable(ModuleFile &F,
887 SmallVectorImpl<uint64_t> &Record) {
888 unsigned Idx = 0;
889 LineTableInfo &LineTable = SourceMgr.getLineTable();
890
891 // Parse the file names
892 std::map<int, int> FileIDs;
893 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
894 // Extract the file name
895 unsigned FilenameLen = Record[Idx++];
896 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
897 Idx += FilenameLen;
898 MaybeAddSystemRootToFilename(F, Filename);
899 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
900 }
901
902 // Parse the line entries
903 std::vector<LineEntry> Entries;
904 while (Idx < Record.size()) {
905 int FID = Record[Idx++];
906 assert(FID >= 0 && "Serialized line entries for non-local file.");
907 // Remap FileID from 1-based old view.
908 FID += F.SLocEntryBaseID - 1;
909
910 // Extract the line entries
911 unsigned NumEntries = Record[Idx++];
912 assert(NumEntries && "Numentries is 00000");
913 Entries.clear();
914 Entries.reserve(NumEntries);
915 for (unsigned I = 0; I != NumEntries; ++I) {
916 unsigned FileOffset = Record[Idx++];
917 unsigned LineNo = Record[Idx++];
918 int FilenameID = FileIDs[Record[Idx++]];
919 SrcMgr::CharacteristicKind FileKind
920 = (SrcMgr::CharacteristicKind)Record[Idx++];
921 unsigned IncludeOffset = Record[Idx++];
922 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
923 FileKind, IncludeOffset));
924 }
925 LineTable.AddEntry(FileID::get(FID), Entries);
926 }
927
928 return false;
929}
930
931/// \brief Read a source manager block
932bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
933 using namespace SrcMgr;
934
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000935 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000936
937 // Set the source-location entry cursor to the current position in
938 // the stream. This cursor will be used to read the contents of the
939 // source manager block initially, and then lazily read
940 // source-location entries as needed.
941 SLocEntryCursor = F.Stream;
942
943 // The stream itself is going to skip over the source manager block.
944 if (F.Stream.SkipBlock()) {
945 Error("malformed block record in AST file");
946 return true;
947 }
948
949 // Enter the source manager block.
950 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
951 Error("malformed source manager block record in AST file");
952 return true;
953 }
954
955 RecordData Record;
956 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000957 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
958
959 switch (E.Kind) {
960 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
961 case llvm::BitstreamEntry::Error:
962 Error("malformed block record in AST file");
963 return true;
964 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000965 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000966 case llvm::BitstreamEntry::Record:
967 // The interesting case.
968 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000969 }
Chris Lattner88bde502013-01-19 21:39:22 +0000970
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000971 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000972 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000973 StringRef Blob;
974 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000975 default: // Default behavior: ignore.
976 break;
977
978 case SM_SLOC_FILE_ENTRY:
979 case SM_SLOC_BUFFER_ENTRY:
980 case SM_SLOC_EXPANSION_ENTRY:
981 // Once we hit one of the source location entries, we're done.
982 return false;
983 }
984 }
985}
986
987/// \brief If a header file is not found at the path that we expect it to be
988/// and the PCH file was moved from its original location, try to resolve the
989/// file by assuming that header+PCH were moved together and the header is in
990/// the same place relative to the PCH.
991static std::string
992resolveFileRelativeToOriginalDir(const std::string &Filename,
993 const std::string &OriginalDir,
994 const std::string &CurrDir) {
995 assert(OriginalDir != CurrDir &&
996 "No point trying to resolve the file if the PCH dir didn't change");
997 using namespace llvm::sys;
998 SmallString<128> filePath(Filename);
999 fs::make_absolute(filePath);
1000 assert(path::is_absolute(OriginalDir));
1001 SmallString<128> currPCHPath(CurrDir);
1002
1003 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1004 fileDirE = path::end(path::parent_path(filePath));
1005 path::const_iterator origDirI = path::begin(OriginalDir),
1006 origDirE = path::end(OriginalDir);
1007 // Skip the common path components from filePath and OriginalDir.
1008 while (fileDirI != fileDirE && origDirI != origDirE &&
1009 *fileDirI == *origDirI) {
1010 ++fileDirI;
1011 ++origDirI;
1012 }
1013 for (; origDirI != origDirE; ++origDirI)
1014 path::append(currPCHPath, "..");
1015 path::append(currPCHPath, fileDirI, fileDirE);
1016 path::append(currPCHPath, path::filename(Filename));
1017 return currPCHPath.str();
1018}
1019
1020bool ASTReader::ReadSLocEntry(int ID) {
1021 if (ID == 0)
1022 return false;
1023
1024 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1025 Error("source location entry ID out-of-range for AST file");
1026 return true;
1027 }
1028
1029 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1030 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001031 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001032 unsigned BaseOffset = F->SLocEntryBaseOffset;
1033
1034 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +00001035 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1036 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001037 Error("incorrectly-formatted source location entry in AST file");
1038 return true;
1039 }
Chris Lattner88bde502013-01-19 21:39:22 +00001040
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001041 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001042 StringRef Blob;
1043 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001044 default:
1045 Error("incorrectly-formatted source location entry in AST file");
1046 return true;
1047
1048 case SM_SLOC_FILE_ENTRY: {
1049 // We will detect whether a file changed and return 'Failure' for it, but
1050 // we will also try to fail gracefully by setting up the SLocEntry.
1051 unsigned InputID = Record[4];
1052 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001053 const FileEntry *File = IF.getFile();
1054 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001055
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001056 // Note that we only check if a File was returned. If it was out-of-date
1057 // we have complained but we will continue creating a FileID to recover
1058 // gracefully.
1059 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001060 return true;
1061
1062 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1063 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1064 // This is the module's main file.
1065 IncludeLoc = getImportLocation(F);
1066 }
1067 SrcMgr::CharacteristicKind
1068 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1069 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1070 ID, BaseOffset + Record[0]);
1071 SrcMgr::FileInfo &FileInfo =
1072 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1073 FileInfo.NumCreatedFIDs = Record[5];
1074 if (Record[3])
1075 FileInfo.setHasLineDirectives();
1076
1077 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1078 unsigned NumFileDecls = Record[7];
1079 if (NumFileDecls) {
1080 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1081 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1082 NumFileDecls));
1083 }
1084
1085 const SrcMgr::ContentCache *ContentCache
1086 = SourceMgr.getOrCreateContentCache(File,
1087 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1088 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1089 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1090 unsigned Code = SLocEntryCursor.ReadCode();
1091 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001092 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001093
1094 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1095 Error("AST record has invalid code");
1096 return true;
1097 }
1098
1099 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001100 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001101 SourceMgr.overrideFileContents(File, Buffer);
1102 }
1103
1104 break;
1105 }
1106
1107 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001108 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001109 unsigned Offset = Record[0];
1110 SrcMgr::CharacteristicKind
1111 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1112 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1113 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1114 IncludeLoc = getImportLocation(F);
1115 }
1116 unsigned Code = SLocEntryCursor.ReadCode();
1117 Record.clear();
1118 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001119 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001120
1121 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1122 Error("AST record has invalid code");
1123 return true;
1124 }
1125
1126 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001127 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001128 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1129 BaseOffset + Offset, IncludeLoc);
1130 break;
1131 }
1132
1133 case SM_SLOC_EXPANSION_ENTRY: {
1134 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1135 SourceMgr.createExpansionLoc(SpellingLoc,
1136 ReadSourceLocation(*F, Record[2]),
1137 ReadSourceLocation(*F, Record[3]),
1138 Record[4],
1139 ID,
1140 BaseOffset + Record[0]);
1141 break;
1142 }
1143 }
1144
1145 return false;
1146}
1147
1148std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1149 if (ID == 0)
1150 return std::make_pair(SourceLocation(), "");
1151
1152 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1153 Error("source location entry ID out-of-range for AST file");
1154 return std::make_pair(SourceLocation(), "");
1155 }
1156
1157 // Find which module file this entry lands in.
1158 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1159 if (M->Kind != MK_Module)
1160 return std::make_pair(SourceLocation(), "");
1161
1162 // FIXME: Can we map this down to a particular submodule? That would be
1163 // ideal.
1164 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1165}
1166
1167/// \brief Find the location where the module F is imported.
1168SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1169 if (F->ImportLoc.isValid())
1170 return F->ImportLoc;
1171
1172 // Otherwise we have a PCH. It's considered to be "imported" at the first
1173 // location of its includer.
1174 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1175 // Main file is the importer. We assume that it is the first entry in the
1176 // entry table. We can't ask the manager, because at the time of PCH loading
1177 // the main file entry doesn't exist yet.
1178 // The very first entry is the invalid instantiation loc, which takes up
1179 // offsets 0 and 1.
1180 return SourceLocation::getFromRawEncoding(2U);
1181 }
1182 //return F->Loaders[0]->FirstLoc;
1183 return F->ImportedBy[0]->FirstLoc;
1184}
1185
1186/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1187/// specified cursor. Read the abbreviations that are at the top of the block
1188/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001189bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001190 if (Cursor.EnterSubBlock(BlockID)) {
1191 Error("malformed block record in AST file");
1192 return Failure;
1193 }
1194
1195 while (true) {
1196 uint64_t Offset = Cursor.GetCurrentBitNo();
1197 unsigned Code = Cursor.ReadCode();
1198
1199 // We expect all abbrevs to be at the start of the block.
1200 if (Code != llvm::bitc::DEFINE_ABBREV) {
1201 Cursor.JumpToBit(Offset);
1202 return false;
1203 }
1204 Cursor.ReadAbbrevRecord();
1205 }
1206}
1207
Richard Smithac32d902013-08-07 21:41:30 +00001208Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallaeeacf72013-05-03 00:10:13 +00001209 unsigned &Idx) {
1210 Token Tok;
1211 Tok.startToken();
1212 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1213 Tok.setLength(Record[Idx++]);
1214 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1215 Tok.setIdentifierInfo(II);
1216 Tok.setKind((tok::TokenKind)Record[Idx++]);
1217 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1218 return Tok;
1219}
1220
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001221MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001222 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001223
1224 // Keep track of where we are in the stream, then jump back there
1225 // after reading this macro.
1226 SavedStreamPosition SavedPosition(Stream);
1227
1228 Stream.JumpToBit(Offset);
1229 RecordData Record;
1230 SmallVector<IdentifierInfo*, 16> MacroArgs;
1231 MacroInfo *Macro = 0;
1232
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001233 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001234 // Advance to the next record, but if we get to the end of the block, don't
1235 // pop it (removing all the abbreviations from the cursor) since we want to
1236 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001237 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001238 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1239
1240 switch (Entry.Kind) {
1241 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1242 case llvm::BitstreamEntry::Error:
1243 Error("malformed block record in AST file");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001244 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001245 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001246 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001247 case llvm::BitstreamEntry::Record:
1248 // The interesting case.
1249 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001250 }
1251
1252 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001253 Record.clear();
1254 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001255 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001256 switch (RecType) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001257 case PP_MACRO_DIRECTIVE_HISTORY:
1258 return Macro;
1259
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001260 case PP_MACRO_OBJECT_LIKE:
1261 case PP_MACRO_FUNCTION_LIKE: {
1262 // If we already have a macro, that means that we've hit the end
1263 // of the definition of the macro we were looking for. We're
1264 // done.
1265 if (Macro)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001266 return Macro;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001267
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001268 unsigned NextIndex = 1; // Skip identifier ID.
1269 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001270 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001271 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001272 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001273 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001274
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001275 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1276 // Decode function-like macro info.
1277 bool isC99VarArgs = Record[NextIndex++];
1278 bool isGNUVarArgs = Record[NextIndex++];
1279 bool hasCommaPasting = Record[NextIndex++];
1280 MacroArgs.clear();
1281 unsigned NumArgs = Record[NextIndex++];
1282 for (unsigned i = 0; i != NumArgs; ++i)
1283 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1284
1285 // Install function-like macro info.
1286 MI->setIsFunctionLike();
1287 if (isC99VarArgs) MI->setIsC99Varargs();
1288 if (isGNUVarArgs) MI->setIsGNUVarargs();
1289 if (hasCommaPasting) MI->setHasCommaPasting();
1290 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1291 PP.getPreprocessorAllocator());
1292 }
1293
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001294 // Remember that we saw this macro last so that we add the tokens that
1295 // form its body to it.
1296 Macro = MI;
1297
1298 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1299 Record[NextIndex]) {
1300 // We have a macro definition. Register the association
1301 PreprocessedEntityID
1302 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1303 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001304 PreprocessingRecord::PPEntityID
1305 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1306 MacroDefinition *PPDef =
1307 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1308 if (PPDef)
1309 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001310 }
1311
1312 ++NumMacrosRead;
1313 break;
1314 }
1315
1316 case PP_TOKEN: {
1317 // If we see a TOKEN before a PP_MACRO_*, then the file is
1318 // erroneous, just pretend we didn't see this.
1319 if (Macro == 0) break;
1320
John McCallaeeacf72013-05-03 00:10:13 +00001321 unsigned Idx = 0;
1322 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001323 Macro->AddTokenToBody(Tok);
1324 break;
1325 }
1326 }
1327 }
1328}
1329
1330PreprocessedEntityID
1331ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1332 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1333 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1334 assert(I != M.PreprocessedEntityRemap.end()
1335 && "Invalid index into preprocessed entity index remap");
1336
1337 return LocalID + I->second;
1338}
1339
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001340unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1341 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001342}
1343
1344HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001345HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1346 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1347 FE->getName() };
1348 return ikey;
1349}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001350
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001351bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1352 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001353 return false;
1354
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001355 if (strcmp(a.Filename, b.Filename) == 0)
1356 return true;
1357
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001358 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001359 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001360 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1361 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001362 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001363}
1364
1365std::pair<unsigned, unsigned>
1366HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001367 using namespace llvm::support;
1368 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001369 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001370 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001371}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001372
1373HeaderFileInfoTrait::internal_key_type
1374HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001375 using namespace llvm::support;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001376 internal_key_type ikey;
Stephen Hines651f13c2014-04-23 16:59:28 -07001377 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1378 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001379 ikey.Filename = (const char *)d;
1380 return ikey;
1381}
1382
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001383HeaderFileInfoTrait::data_type
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001384HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001385 unsigned DataLen) {
1386 const unsigned char *End = d + DataLen;
Stephen Hines651f13c2014-04-23 16:59:28 -07001387 using namespace llvm::support;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001388 HeaderFileInfo HFI;
1389 unsigned Flags = *d++;
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001390 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1391 ((Flags >> 6) & 0x03);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001392 HFI.isImport = (Flags >> 5) & 0x01;
1393 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1394 HFI.DirInfo = (Flags >> 2) & 0x03;
1395 HFI.Resolved = (Flags >> 1) & 0x01;
1396 HFI.IndexHeaderMapHeader = Flags & 0x01;
Stephen Hines651f13c2014-04-23 16:59:28 -07001397 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1398 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1399 M, endian::readNext<uint32_t, little, unaligned>(d));
1400 if (unsigned FrameworkOffset =
1401 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001402 // The framework offset is 1 greater than the actual offset,
1403 // since 0 is used as an indicator for "no framework name".
1404 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1405 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1406 }
1407
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001408 if (d != End) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001409 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001410 if (LocalSMID) {
1411 // This header is part of a module. Associate it with the module to enable
1412 // implicit module import.
1413 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1414 Module *Mod = Reader.getSubmodule(GlobalSMID);
1415 HFI.isModuleHeader = true;
1416 FileManager &FileMgr = Reader.getFileManager();
1417 ModuleMap &ModMap =
1418 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00001419 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001420 }
1421 }
1422
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001423 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1424 (void)End;
1425
1426 // This HeaderFileInfo was externally loaded.
1427 HFI.External = true;
1428 return HFI;
1429}
1430
Stephen Hines651f13c2014-04-23 16:59:28 -07001431void
1432ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1433 GlobalMacroID GMacID,
1434 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001435 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Stephen Hines651f13c2014-04-23 16:59:28 -07001436 SubmoduleID *OverrideData = 0;
1437 if (!Overrides.empty()) {
1438 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1439 OverrideData[0] = Overrides.size();
1440 for (unsigned I = 0; I != Overrides.size(); ++I)
1441 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1442 }
1443 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001444}
1445
1446void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1447 ModuleFile *M,
1448 uint64_t MacroDirectivesOffset) {
1449 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1450 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001451}
1452
1453void ASTReader::ReadDefinedMacros() {
1454 // Note that we are loading defined macros.
1455 Deserializing Macros(this);
1456
1457 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1458 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001459 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001460
1461 // If there was no preprocessor block, skip this file.
1462 if (!MacroCursor.getBitStreamReader())
1463 continue;
1464
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001465 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001466 Cursor.JumpToBit((*I)->MacroStartOffset);
1467
1468 RecordData Record;
1469 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001470 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1471
1472 switch (E.Kind) {
1473 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1474 case llvm::BitstreamEntry::Error:
1475 Error("malformed block record in AST file");
1476 return;
1477 case llvm::BitstreamEntry::EndBlock:
1478 goto NextCursor;
1479
1480 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001481 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001482 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001483 default: // Default behavior: ignore.
1484 break;
1485
1486 case PP_MACRO_OBJECT_LIKE:
1487 case PP_MACRO_FUNCTION_LIKE:
1488 getLocalIdentifier(**I, Record[0]);
1489 break;
1490
1491 case PP_TOKEN:
1492 // Ignore tokens.
1493 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001494 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001495 break;
1496 }
1497 }
Chris Lattner88bde502013-01-19 21:39:22 +00001498 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001499 }
1500}
1501
1502namespace {
1503 /// \brief Visitor class used to look up identifirs in an AST file.
1504 class IdentifierLookupVisitor {
1505 StringRef Name;
1506 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001507 unsigned &NumIdentifierLookups;
1508 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001509 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001510
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001511 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001512 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1513 unsigned &NumIdentifierLookups,
1514 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001515 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001516 NumIdentifierLookups(NumIdentifierLookups),
1517 NumIdentifierLookupHits(NumIdentifierLookupHits),
1518 Found()
1519 {
1520 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521
1522 static bool visit(ModuleFile &M, void *UserData) {
1523 IdentifierLookupVisitor *This
1524 = static_cast<IdentifierLookupVisitor *>(UserData);
1525
1526 // If we've already searched this module file, skip it now.
1527 if (M.Generation <= This->PriorGeneration)
1528 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001529
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530 ASTIdentifierLookupTable *IdTable
1531 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1532 if (!IdTable)
1533 return false;
1534
1535 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1536 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001537 ++This->NumIdentifierLookups;
1538 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001539 if (Pos == IdTable->end())
1540 return false;
1541
1542 // Dereferencing the iterator has the effect of building the
1543 // IdentifierInfo node and populating it with the various
1544 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001545 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001546 This->Found = *Pos;
1547 return true;
1548 }
1549
1550 // \brief Retrieve the identifier info found within the module
1551 // files.
1552 IdentifierInfo *getIdentifierInfo() const { return Found; }
1553 };
1554}
1555
1556void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1557 // Note that we are loading an identifier.
1558 Deserializing AnIdentifier(this);
1559
1560 unsigned PriorGeneration = 0;
1561 if (getContext().getLangOpts().Modules)
1562 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001563
1564 // If there is a global index, look there first to determine which modules
1565 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001566 GlobalModuleIndex::HitSet Hits;
1567 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001568 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001569 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1570 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001571 }
1572 }
1573
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001574 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001575 NumIdentifierLookups,
1576 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001577 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001578 markIdentifierUpToDate(&II);
1579}
1580
1581void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1582 if (!II)
1583 return;
1584
1585 II->setOutOfDate(false);
1586
1587 // Update the generation for this identifier.
1588 if (getContext().getLangOpts().Modules)
1589 IdentifierGeneration[II] = CurrentGeneration;
1590}
1591
Stephen Hines651f13c2014-04-23 16:59:28 -07001592struct ASTReader::ModuleMacroInfo {
1593 SubmoduleID SubModID;
1594 MacroInfo *MI;
1595 SubmoduleID *Overrides;
1596 // FIXME: Remove this.
1597 ModuleFile *F;
1598
1599 bool isDefine() const { return MI; }
1600
1601 SubmoduleID getSubmoduleID() const { return SubModID; }
1602
1603 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1604 if (!Overrides)
1605 return llvm::ArrayRef<SubmoduleID>();
1606 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1607 }
1608
1609 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1610 if (!MI)
1611 return 0;
1612 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1613 }
1614};
1615
1616ASTReader::ModuleMacroInfo *
1617ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1618 ModuleMacroInfo Info;
1619
1620 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1621 if (ID & 1) {
1622 // Macro undefinition.
1623 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1624 Info.MI = 0;
1625 } else {
1626 // Macro definition.
1627 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1628 assert(GMacID);
1629
1630 // If this macro has already been loaded, don't do so again.
1631 // FIXME: This is highly dubious. Multiple macro definitions can have the
1632 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1633 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1634 return 0;
1635
1636 Info.MI = getMacro(GMacID);
1637 Info.SubModID = Info.MI->getOwningModuleID();
1638 }
1639 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1640 Info.F = PMInfo.M;
1641
1642 return new (Context) ModuleMacroInfo(Info);
1643}
1644
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001645void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1646 const PendingMacroInfo &PMInfo) {
1647 assert(II);
1648
1649 if (PMInfo.M->Kind != MK_Module) {
1650 installPCHMacroDirectives(II, *PMInfo.M,
1651 PMInfo.PCHMacroData.MacroDirectivesOffset);
1652 return;
1653 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001654
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001655 // Module Macro.
1656
Stephen Hines651f13c2014-04-23 16:59:28 -07001657 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1658 if (!MMI)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001659 return;
1660
Stephen Hines651f13c2014-04-23 16:59:28 -07001661 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1662 if (Owner && Owner->NameVisibility == Module::Hidden) {
1663 // Macros in the owning module are hidden. Just remember this macro to
1664 // install if we make this module visible.
1665 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1666 } else {
1667 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001668 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001669}
1670
1671void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1672 ModuleFile &M, uint64_t Offset) {
1673 assert(M.Kind != MK_Module);
1674
1675 BitstreamCursor &Cursor = M.MacroCursor;
1676 SavedStreamPosition SavedPosition(Cursor);
1677 Cursor.JumpToBit(Offset);
1678
1679 llvm::BitstreamEntry Entry =
1680 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1681 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1682 Error("malformed block record in AST file");
1683 return;
1684 }
1685
1686 RecordData Record;
1687 PreprocessorRecordTypes RecType =
1688 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1689 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1690 Error("malformed block record in AST file");
1691 return;
1692 }
1693
1694 // Deserialize the macro directives history in reverse source-order.
1695 MacroDirective *Latest = 0, *Earliest = 0;
1696 unsigned Idx = 0, N = Record.size();
1697 while (Idx < N) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001698 MacroDirective *MD = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001699 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001700 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1701 switch (K) {
1702 case MacroDirective::MD_Define: {
1703 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1704 MacroInfo *MI = getMacro(GMacID);
1705 bool isImported = Record[Idx++];
1706 bool isAmbiguous = Record[Idx++];
1707 DefMacroDirective *DefMD =
1708 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1709 DefMD->setAmbiguous(isAmbiguous);
1710 MD = DefMD;
1711 break;
1712 }
1713 case MacroDirective::MD_Undefine:
1714 MD = PP.AllocateUndefMacroDirective(Loc);
1715 break;
1716 case MacroDirective::MD_Visibility: {
1717 bool isPublic = Record[Idx++];
1718 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1719 break;
1720 }
1721 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001722
1723 if (!Latest)
1724 Latest = MD;
1725 if (Earliest)
1726 Earliest->setPrevious(MD);
1727 Earliest = MD;
1728 }
1729
1730 PP.setLoadedMacroDirective(II, Latest);
1731}
1732
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001733/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor7332ae42013-04-12 21:00:54 +00001734/// modules.
1735static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001736 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001737 assert(PrevMI && NewMI);
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001738 Module *PrevOwner = 0;
1739 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1740 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001741 SourceManager &SrcMgr = Reader.getSourceManager();
1742 bool PrevInSystem
1743 = PrevOwner? PrevOwner->IsSystem
1744 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1745 bool NewInSystem
1746 = NewOwner? NewOwner->IsSystem
1747 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1748 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001749 return false;
Douglas Gregorf9dbae72013-06-07 22:56:11 +00001750 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001751}
1752
Stephen Hines651f13c2014-04-23 16:59:28 -07001753void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1754 AmbiguousMacros &Ambig,
1755 llvm::ArrayRef<SubmoduleID> Overrides) {
1756 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1757 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001758
Stephen Hines651f13c2014-04-23 16:59:28 -07001759 // If this macro is not yet visible, remove it from the hidden names list.
1760 Module *Owner = getSubmodule(OwnerID);
1761 HiddenNames &Hidden = HiddenNamesMap[Owner];
1762 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1763 if (HI != Hidden.HiddenMacros.end()) {
1764 auto SubOverrides = HI->second->getOverriddenSubmodules();
1765 Hidden.HiddenMacros.erase(HI);
1766 removeOverriddenMacros(II, Ambig, SubOverrides);
1767 }
1768
1769 // If this macro is already in our list of conflicts, remove it from there.
1770 Ambig.erase(
1771 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1772 return MD->getInfo()->getOwningModuleID() == OwnerID;
1773 }),
1774 Ambig.end());
1775 }
1776}
1777
1778ASTReader::AmbiguousMacros *
1779ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1780 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001781 MacroDirective *Prev = PP.getMacroDirective(II);
Stephen Hines651f13c2014-04-23 16:59:28 -07001782 if (!Prev && Overrides.empty())
1783 return 0;
1784
1785 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1786 if (PrevDef && PrevDef->isAmbiguous()) {
1787 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1788 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1789 Ambig.push_back(PrevDef);
1790
1791 removeOverriddenMacros(II, Ambig, Overrides);
1792
1793 if (!Ambig.empty())
1794 return &Ambig;
1795
1796 AmbiguousMacroDefs.erase(II);
1797 } else {
1798 // There's no ambiguity yet. Maybe we're introducing one.
1799 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1800 if (PrevDef)
1801 Ambig.push_back(PrevDef);
1802
1803 removeOverriddenMacros(II, Ambig, Overrides);
1804
1805 if (!Ambig.empty()) {
1806 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1807 Result.swap(Ambig);
1808 return &Result;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001809 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001810 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001811
1812 // We ended up with no ambiguity.
1813 return 0;
1814}
1815
1816void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1817 Module *Owner) {
1818 assert(II && Owner);
1819
1820 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1821 if (ImportLoc.isInvalid()) {
1822 // FIXME: If we made macros from this module visible but didn't provide a
1823 // source location for the import, we don't have a location for the macro.
1824 // Use the location at which the containing module file was first imported
1825 // for now.
1826 ImportLoc = MMI->F->DirectImportLoc;
1827 assert(ImportLoc.isValid() && "no import location for a visible macro?");
1828 }
1829
1830 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1831 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1832
1833
1834 // Create a synthetic macro definition corresponding to the import (or null
1835 // if this was an undefinition of the macro).
1836 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1837
1838 // If there's no ambiguity, just install the macro.
1839 if (!Prev) {
1840 if (MD)
1841 PP.appendMacroDirective(II, MD);
1842 else
1843 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1844 return;
1845 }
1846 assert(!Prev->empty());
1847
1848 if (!MD) {
1849 // We imported a #undef that didn't remove all prior definitions. The most
1850 // recent prior definition remains, and we install it in the place of the
1851 // imported directive.
1852 MacroInfo *NewMI = Prev->back()->getInfo();
1853 Prev->pop_back();
1854 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1855 }
1856
1857 // We're introducing a macro definition that creates or adds to an ambiguity.
1858 // We can resolve that ambiguity if this macro is token-for-token identical to
1859 // all of the existing definitions.
1860 MacroInfo *NewMI = MD->getInfo();
1861 assert(NewMI && "macro definition with no MacroInfo?");
1862 while (!Prev->empty()) {
1863 MacroInfo *PrevMI = Prev->back()->getInfo();
1864 assert(PrevMI && "macro definition with no MacroInfo?");
1865
1866 // Before marking the macros as ambiguous, check if this is a case where
1867 // both macros are in system headers. If so, we trust that the system
1868 // did not get it wrong. This also handles cases where Clang's own
1869 // headers have a different spelling of certain system macros:
1870 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1871 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1872 //
1873 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1874 // overrides the system limits.h's macros, so there's no conflict here.
1875 if (NewMI != PrevMI &&
1876 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1877 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1878 break;
1879
1880 // The previous definition is the same as this one (or both are defined in
1881 // system modules so we can assume they're equivalent); we don't need to
1882 // track it any more.
1883 Prev->pop_back();
1884 }
1885
1886 if (!Prev->empty())
1887 MD->setAmbiguous(true);
1888
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001889 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001890}
1891
Stephen Hines651f13c2014-04-23 16:59:28 -07001892ASTReader::InputFileInfo
1893ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1894 // Go find this input file.
1895 BitstreamCursor &Cursor = F.InputFilesCursor;
1896 SavedStreamPosition SavedPosition(Cursor);
1897 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1898
1899 unsigned Code = Cursor.ReadCode();
1900 RecordData Record;
1901 StringRef Blob;
1902
1903 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1904 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1905 "invalid record type for input file");
1906 (void)Result;
1907
1908 std::string Filename;
1909 off_t StoredSize;
1910 time_t StoredTime;
1911 bool Overridden;
1912
1913 assert(Record[0] == ID && "Bogus stored ID or offset");
1914 StoredSize = static_cast<off_t>(Record[1]);
1915 StoredTime = static_cast<time_t>(Record[2]);
1916 Overridden = static_cast<bool>(Record[3]);
1917 Filename = Blob;
1918 MaybeAddSystemRootToFilename(F, Filename);
1919
1920 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1921 return R;
1922}
1923
1924std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
1925 return readInputFileInfo(F, ID).Filename;
1926}
1927
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001928InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001929 // If this ID is bogus, just return an empty input file.
1930 if (ID == 0 || ID > F.InputFilesLoaded.size())
1931 return InputFile();
1932
1933 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001934 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001935 return F.InputFilesLoaded[ID-1];
1936
Stephen Hines651f13c2014-04-23 16:59:28 -07001937 if (F.InputFilesLoaded[ID-1].isNotFound())
1938 return InputFile();
1939
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001940 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001941 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001942 SavedStreamPosition SavedPosition(Cursor);
1943 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1944
Stephen Hines651f13c2014-04-23 16:59:28 -07001945 InputFileInfo FI = readInputFileInfo(F, ID);
1946 off_t StoredSize = FI.StoredSize;
1947 time_t StoredTime = FI.StoredTime;
1948 bool Overridden = FI.Overridden;
1949 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001950
Stephen Hines651f13c2014-04-23 16:59:28 -07001951 const FileEntry *File
1952 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1953 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1954
1955 // If we didn't find the file, resolve it relative to the
1956 // original directory from which this AST file was created.
1957 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1958 F.OriginalDir != CurrentDir) {
1959 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1960 F.OriginalDir,
1961 CurrentDir);
1962 if (!Resolved.empty())
1963 File = FileMgr.getFile(Resolved);
1964 }
1965
1966 // For an overridden file, create a virtual file with the stored
1967 // size/timestamp.
1968 if (Overridden && File == 0) {
1969 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1970 }
1971
1972 if (File == 0) {
1973 if (Complain) {
1974 std::string ErrorStr = "could not find file '";
1975 ErrorStr += Filename;
1976 ErrorStr += "' referenced by AST file";
1977 Error(ErrorStr.c_str());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001978 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001979 // Record that we didn't find the file.
1980 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1981 return InputFile();
1982 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001983
Stephen Hines651f13c2014-04-23 16:59:28 -07001984 // Check if there was a request to override the contents of the file
1985 // that was part of the precompiled header. Overridding such a file
1986 // can lead to problems when lexing using the source locations from the
1987 // PCH.
1988 SourceManager &SM = getSourceManager();
1989 if (!Overridden && SM.isFileOverridden(File)) {
1990 if (Complain)
1991 Error(diag::err_fe_pch_file_overridden, Filename);
1992 // After emitting the diagnostic, recover by disabling the override so
1993 // that the original file will be used.
1994 SM.disableFileContentsOverride(File);
1995 // The FileEntry is a virtual file entry with the size of the contents
1996 // that would override the original contents. Set it to the original's
1997 // size/time.
1998 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1999 StoredSize, StoredTime);
2000 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002001
Stephen Hines651f13c2014-04-23 16:59:28 -07002002 bool IsOutOfDate = false;
2003
2004 // For an overridden file, there is nothing to validate.
2005 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002006#if !defined(LLVM_ON_WIN32)
Stephen Hines651f13c2014-04-23 16:59:28 -07002007 // In our regression testing, the Windows file system seems to
2008 // have inconsistent modification times that sometimes
2009 // erroneously trigger this error-handling path.
2010 || StoredTime != File->getModificationTime()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002011#endif
Stephen Hines651f13c2014-04-23 16:59:28 -07002012 )) {
2013 if (Complain) {
2014 // Build a list of the PCH imports that got us here (in reverse).
2015 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2016 while (ImportStack.back()->ImportedBy.size() > 0)
2017 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2018
2019 // The top-level PCH is stale.
2020 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2021 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2022
2023 // Print the import stack.
2024 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2025 Diag(diag::note_pch_required_by)
2026 << Filename << ImportStack[0]->FileName;
2027 for (unsigned I = 1; I < ImportStack.size(); ++I)
2028 Diag(diag::note_pch_required_by)
2029 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor677e15f2013-03-19 00:28:20 +00002030 }
2031
Stephen Hines651f13c2014-04-23 16:59:28 -07002032 if (!Diags.isDiagnosticInFlight())
2033 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002034 }
2035
Stephen Hines651f13c2014-04-23 16:59:28 -07002036 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002037 }
2038
Stephen Hines651f13c2014-04-23 16:59:28 -07002039 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2040
2041 // Note that we've loaded this input file.
2042 F.InputFilesLoaded[ID-1] = IF;
2043 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002044}
2045
2046const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2047 ModuleFile &M = ModuleMgr.getPrimaryModule();
2048 std::string Filename = filenameStrRef;
2049 MaybeAddSystemRootToFilename(M, Filename);
2050 const FileEntry *File = FileMgr.getFile(Filename);
2051 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2052 M.OriginalDir != CurrentDir) {
2053 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2054 M.OriginalDir,
2055 CurrentDir);
2056 if (!resolved.empty())
2057 File = FileMgr.getFile(resolved);
2058 }
2059
2060 return File;
2061}
2062
2063/// \brief If we are loading a relocatable PCH file, and the filename is
2064/// not an absolute path, add the system root to the beginning of the file
2065/// name.
2066void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2067 std::string &Filename) {
2068 // If this is not a relocatable PCH file, there's nothing to do.
2069 if (!M.RelocatablePCH)
2070 return;
2071
2072 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2073 return;
2074
2075 if (isysroot.empty()) {
2076 // If no system root was given, default to '/'
2077 Filename.insert(Filename.begin(), '/');
2078 return;
2079 }
2080
2081 unsigned Length = isysroot.size();
2082 if (isysroot[Length - 1] != '/')
2083 Filename.insert(Filename.begin(), '/');
2084
2085 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2086}
2087
2088ASTReader::ASTReadResult
2089ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002090 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002091 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002092 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002093
2094 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2095 Error("malformed block record in AST file");
2096 return Failure;
2097 }
2098
2099 // Read all of the records and blocks in the control block.
2100 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00002101 while (1) {
2102 llvm::BitstreamEntry Entry = Stream.advance();
2103
2104 switch (Entry.Kind) {
2105 case llvm::BitstreamEntry::Error:
2106 Error("malformed block record in AST file");
2107 return Failure;
Stephen Hines651f13c2014-04-23 16:59:28 -07002108 case llvm::BitstreamEntry::EndBlock: {
2109 // Validate input files.
2110 const HeaderSearchOptions &HSOpts =
2111 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2112
2113 // All user input files reside at the index range [0, Record[1]), and
2114 // system input files reside at [Record[1], Record[0]).
2115 // Record is the one from INPUT_FILE_OFFSETS.
2116 unsigned NumInputs = Record[0];
2117 unsigned NumUserInputs = Record[1];
2118
2119 if (!DisableValidation &&
2120 (!HSOpts.ModulesValidateOncePerBuildSession ||
2121 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002122 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07002123
2124 // If we are reading a module, we will create a verification timestamp,
2125 // so we verify all input files. Otherwise, verify only user input
2126 // files.
2127
2128 unsigned N = NumUserInputs;
2129 if (ValidateSystemInputs ||
2130 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2131 N = NumInputs;
2132
2133 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00002134 InputFile IF = getInputFile(F, I+1, Complain);
2135 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00002137 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002138 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002139
2140 if (Listener)
2141 Listener->visitModuleFile(F.FileName);
2142
2143 if (Listener && Listener->needsInputFileVisitation()) {
2144 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2145 : NumUserInputs;
2146 for (unsigned I = 0; I < N; ++I) {
2147 bool IsSystem = I >= NumUserInputs;
2148 InputFileInfo FI = readInputFileInfo(F, I+1);
2149 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2150 }
2151 }
2152
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002153 return Success;
Stephen Hines651f13c2014-04-23 16:59:28 -07002154 }
2155
Chris Lattner88bde502013-01-19 21:39:22 +00002156 case llvm::BitstreamEntry::SubBlock:
2157 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002158 case INPUT_FILES_BLOCK_ID:
2159 F.InputFilesCursor = Stream;
2160 if (Stream.SkipBlock() || // Skip with the main cursor
2161 // Read the abbreviations
2162 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2163 Error("malformed block record in AST file");
2164 return Failure;
2165 }
2166 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002167
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002168 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002169 if (Stream.SkipBlock()) {
2170 Error("malformed block record in AST file");
2171 return Failure;
2172 }
2173 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002174 }
Chris Lattner88bde502013-01-19 21:39:22 +00002175
2176 case llvm::BitstreamEntry::Record:
2177 // The interesting case.
2178 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002179 }
2180
2181 // Read and process a record.
2182 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002183 StringRef Blob;
2184 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002185 case METADATA: {
2186 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2187 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -07002188 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2189 : diag::err_pch_version_too_new);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002190 return VersionMismatch;
2191 }
2192
2193 bool hasErrors = Record[5];
2194 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2195 Diag(diag::err_pch_with_compiler_errors);
2196 return HadErrors;
2197 }
2198
2199 F.RelocatablePCH = Record[4];
2200
2201 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002202 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002203 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2204 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -07002205 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002206 return VersionMismatch;
2207 }
2208 break;
2209 }
2210
2211 case IMPORTS: {
2212 // Load each of the imported PCH files.
2213 unsigned Idx = 0, N = Record.size();
2214 while (Idx < N) {
2215 // Read information about the AST file.
2216 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2217 // The import location will be the local one for now; we will adjust
2218 // all import locations of module imports after the global source
2219 // location info are setup.
2220 SourceLocation ImportLoc =
2221 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00002222 off_t StoredSize = (off_t)Record[Idx++];
2223 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002224 unsigned Length = Record[Idx++];
2225 SmallString<128> ImportedFile(Record.begin() + Idx,
2226 Record.begin() + Idx + Length);
2227 Idx += Length;
2228
2229 // Load the AST file.
2230 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002231 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002232 ClientLoadCapabilities)) {
2233 case Failure: return Failure;
2234 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00002235 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002236 case OutOfDate: return OutOfDate;
2237 case VersionMismatch: return VersionMismatch;
2238 case ConfigurationMismatch: return ConfigurationMismatch;
2239 case HadErrors: return HadErrors;
2240 case Success: break;
2241 }
2242 }
2243 break;
2244 }
2245
2246 case LANGUAGE_OPTIONS: {
2247 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2248 if (Listener && &F == *ModuleMgr.begin() &&
2249 ParseLanguageOptions(Record, Complain, *Listener) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002250 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002251 return ConfigurationMismatch;
2252 break;
2253 }
2254
2255 case TARGET_OPTIONS: {
2256 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2257 if (Listener && &F == *ModuleMgr.begin() &&
2258 ParseTargetOptions(Record, Complain, *Listener) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002259 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002260 return ConfigurationMismatch;
2261 break;
2262 }
2263
2264 case DIAGNOSTIC_OPTIONS: {
2265 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2266 if (Listener && &F == *ModuleMgr.begin() &&
2267 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002268 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002269 return ConfigurationMismatch;
2270 break;
2271 }
2272
2273 case FILE_SYSTEM_OPTIONS: {
2274 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2275 if (Listener && &F == *ModuleMgr.begin() &&
2276 ParseFileSystemOptions(Record, Complain, *Listener) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002277 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002278 return ConfigurationMismatch;
2279 break;
2280 }
2281
2282 case HEADER_SEARCH_OPTIONS: {
2283 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2284 if (Listener && &F == *ModuleMgr.begin() &&
2285 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002286 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002287 return ConfigurationMismatch;
2288 break;
2289 }
2290
2291 case PREPROCESSOR_OPTIONS: {
2292 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2293 if (Listener && &F == *ModuleMgr.begin() &&
2294 ParsePreprocessorOptions(Record, Complain, *Listener,
2295 SuggestedPredefines) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07002296 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002297 return ConfigurationMismatch;
2298 break;
2299 }
2300
2301 case ORIGINAL_FILE:
2302 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002303 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002304 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2305 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2306 break;
2307
2308 case ORIGINAL_FILE_ID:
2309 F.OriginalSourceFileID = FileID::get(Record[0]);
2310 break;
2311
2312 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002313 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002314 break;
2315
2316 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002317 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002318 F.InputFilesLoaded.resize(Record[0]);
2319 break;
2320 }
2321 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002322}
2323
2324bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002325 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002326
2327 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2328 Error("malformed block record in AST file");
2329 return true;
2330 }
2331
2332 // Read all of the records and blocks for the AST file.
2333 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00002334 while (1) {
2335 llvm::BitstreamEntry Entry = Stream.advance();
2336
2337 switch (Entry.Kind) {
2338 case llvm::BitstreamEntry::Error:
2339 Error("error at end of module block in AST file");
2340 return true;
2341 case llvm::BitstreamEntry::EndBlock: {
Richard Smith43828672013-04-03 22:49:41 +00002342 // Outside of C++, we do not store a lookup map for the translation unit.
2343 // Instead, mark it as needing a lookup map to be built if this module
2344 // contains any declarations lexically within it (which it always does!).
2345 // This usually has no cost, since we very rarely need the lookup map for
2346 // the translation unit outside C++.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002347 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smith43828672013-04-03 22:49:41 +00002348 if (DC->hasExternalLexicalStorage() &&
2349 !getContext().getLangOpts().CPlusPlus)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002350 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002351
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002352 return false;
2353 }
Chris Lattner88bde502013-01-19 21:39:22 +00002354 case llvm::BitstreamEntry::SubBlock:
2355 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002356 case DECLTYPES_BLOCK_ID:
2357 // We lazily load the decls block, but we want to set up the
2358 // DeclsCursor cursor to point into it. Clone our current bitcode
2359 // cursor to it, enter the block and read the abbrevs in that block.
2360 // With the main cursor, we just skip over it.
2361 F.DeclsCursor = Stream;
2362 if (Stream.SkipBlock() || // Skip with the main cursor.
2363 // Read the abbrevs.
2364 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2365 Error("malformed block record in AST file");
2366 return true;
2367 }
2368 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07002369
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002370 case PREPROCESSOR_BLOCK_ID:
2371 F.MacroCursor = Stream;
2372 if (!PP.getExternalSource())
2373 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002374
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002375 if (Stream.SkipBlock() ||
2376 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2377 Error("malformed block record in AST file");
2378 return true;
2379 }
2380 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2381 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002382
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002383 case PREPROCESSOR_DETAIL_BLOCK_ID:
2384 F.PreprocessorDetailCursor = Stream;
2385 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002386 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002387 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002388 Error("malformed preprocessor detail record in AST file");
2389 return true;
2390 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002391 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002392 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2393
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002394 if (!PP.getPreprocessingRecord())
2395 PP.createPreprocessingRecord();
2396 if (!PP.getPreprocessingRecord()->getExternalSource())
2397 PP.getPreprocessingRecord()->SetExternalSource(*this);
2398 break;
2399
2400 case SOURCE_MANAGER_BLOCK_ID:
2401 if (ReadSourceManagerBlock(F))
2402 return true;
2403 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002404
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002405 case SUBMODULE_BLOCK_ID:
2406 if (ReadSubmoduleBlock(F))
2407 return true;
2408 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002410 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002411 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002412 if (Stream.SkipBlock() ||
2413 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2414 Error("malformed comments block in AST file");
2415 return true;
2416 }
2417 CommentsCursors.push_back(std::make_pair(C, &F));
2418 break;
2419 }
Chris Lattner88bde502013-01-19 21:39:22 +00002420
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002421 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002422 if (Stream.SkipBlock()) {
2423 Error("malformed block record in AST file");
2424 return true;
2425 }
2426 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002427 }
2428 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002429
2430 case llvm::BitstreamEntry::Record:
2431 // The interesting case.
2432 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002433 }
2434
2435 // Read and process a record.
2436 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002437 StringRef Blob;
2438 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002439 default: // Default behavior: ignore.
2440 break;
2441
2442 case TYPE_OFFSET: {
2443 if (F.LocalNumTypes != 0) {
2444 Error("duplicate TYPE_OFFSET record in AST file");
2445 return true;
2446 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002447 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002448 F.LocalNumTypes = Record[0];
2449 unsigned LocalBaseTypeIndex = Record[1];
2450 F.BaseTypeIndex = getTotalNumTypes();
2451
2452 if (F.LocalNumTypes > 0) {
2453 // Introduce the global -> local mapping for types within this module.
2454 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2455
2456 // Introduce the local -> global mapping for types within this module.
2457 F.TypeRemap.insertOrReplace(
2458 std::make_pair(LocalBaseTypeIndex,
2459 F.BaseTypeIndex - LocalBaseTypeIndex));
2460
2461 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2462 }
2463 break;
2464 }
2465
2466 case DECL_OFFSET: {
2467 if (F.LocalNumDecls != 0) {
2468 Error("duplicate DECL_OFFSET record in AST file");
2469 return true;
2470 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002471 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002472 F.LocalNumDecls = Record[0];
2473 unsigned LocalBaseDeclID = Record[1];
2474 F.BaseDeclID = getTotalNumDecls();
2475
2476 if (F.LocalNumDecls > 0) {
2477 // Introduce the global -> local mapping for declarations within this
2478 // module.
2479 GlobalDeclMap.insert(
2480 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2481
2482 // Introduce the local -> global mapping for declarations within this
2483 // module.
2484 F.DeclRemap.insertOrReplace(
2485 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2486
2487 // Introduce the global -> local mapping for declarations within this
2488 // module.
2489 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2490
2491 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2492 }
2493 break;
2494 }
2495
2496 case TU_UPDATE_LEXICAL: {
2497 DeclContext *TU = Context.getTranslationUnitDecl();
2498 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002499 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002500 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002501 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002502 TU->setHasExternalLexicalStorage(true);
2503 break;
2504 }
2505
2506 case UPDATE_VISIBLE: {
2507 unsigned Idx = 0;
2508 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2509 ASTDeclContextNameLookupTable *Table =
2510 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002511 (const unsigned char *)Blob.data() + Record[Idx++],
2512 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002513 ASTDeclContextNameLookupTrait(*this, F));
2514 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2515 DeclContext *TU = Context.getTranslationUnitDecl();
2516 F.DeclContextInfos[TU].NameLookupTableData = Table;
2517 TU->setHasExternalVisibleStorage(true);
Stephen Hines651f13c2014-04-23 16:59:28 -07002518 } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2519 auto *DC = cast<DeclContext>(D);
2520 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
2521 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2522 delete LookupTable;
2523 LookupTable = Table;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002524 } else
2525 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2526 break;
2527 }
2528
2529 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002530 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002531 if (Record[0]) {
2532 F.IdentifierLookupTable
2533 = ASTIdentifierLookupTable::Create(
2534 (const unsigned char *)F.IdentifierTableData + Record[0],
2535 (const unsigned char *)F.IdentifierTableData,
2536 ASTIdentifierLookupTrait(*this, F));
2537
2538 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2539 }
2540 break;
2541
2542 case IDENTIFIER_OFFSET: {
2543 if (F.LocalNumIdentifiers != 0) {
2544 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2545 return true;
2546 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002547 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002548 F.LocalNumIdentifiers = Record[0];
2549 unsigned LocalBaseIdentifierID = Record[1];
2550 F.BaseIdentifierID = getTotalNumIdentifiers();
2551
2552 if (F.LocalNumIdentifiers > 0) {
2553 // Introduce the global -> local mapping for identifiers within this
2554 // module.
2555 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2556 &F));
2557
2558 // Introduce the local -> global mapping for identifiers within this
2559 // module.
2560 F.IdentifierRemap.insertOrReplace(
2561 std::make_pair(LocalBaseIdentifierID,
2562 F.BaseIdentifierID - LocalBaseIdentifierID));
2563
2564 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2565 + F.LocalNumIdentifiers);
2566 }
2567 break;
2568 }
2569
Stephen Hines651f13c2014-04-23 16:59:28 -07002570 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Stephen Hines651f13c2014-04-23 16:59:28 -07002572 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002573 break;
2574
2575 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002576 if (SpecialTypes.empty()) {
2577 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2578 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2579 break;
2580 }
2581
2582 if (SpecialTypes.size() != Record.size()) {
2583 Error("invalid special-types record");
2584 return true;
2585 }
2586
2587 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2588 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2589 if (!SpecialTypes[I])
2590 SpecialTypes[I] = ID;
2591 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2592 // merge step?
2593 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002594 break;
2595
2596 case STATISTICS:
2597 TotalNumStatements += Record[0];
2598 TotalNumMacros += Record[1];
2599 TotalLexicalDeclContexts += Record[2];
2600 TotalVisibleDeclContexts += Record[3];
2601 break;
2602
2603 case UNUSED_FILESCOPED_DECLS:
2604 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2605 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2606 break;
2607
2608 case DELEGATING_CTORS:
2609 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2611 break;
2612
2613 case WEAK_UNDECLARED_IDENTIFIERS:
2614 if (Record.size() % 4 != 0) {
2615 Error("invalid weak identifiers record");
2616 return true;
2617 }
2618
2619 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2620 // files. This isn't the way to do it :)
2621 WeakUndeclaredIdentifiers.clear();
2622
2623 // Translate the weak, undeclared identifiers into global IDs.
2624 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2625 WeakUndeclaredIdentifiers.push_back(
2626 getGlobalIdentifierID(F, Record[I++]));
2627 WeakUndeclaredIdentifiers.push_back(
2628 getGlobalIdentifierID(F, Record[I++]));
2629 WeakUndeclaredIdentifiers.push_back(
2630 ReadSourceLocation(F, Record, I).getRawEncoding());
2631 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2632 }
2633 break;
2634
Richard Smith5ea6ef42013-01-10 23:43:47 +00002635 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002636 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002637 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002638 break;
2639
2640 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002641 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002642 F.LocalNumSelectors = Record[0];
2643 unsigned LocalBaseSelectorID = Record[1];
2644 F.BaseSelectorID = getTotalNumSelectors();
2645
2646 if (F.LocalNumSelectors > 0) {
2647 // Introduce the global -> local mapping for selectors within this
2648 // module.
2649 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2650
2651 // Introduce the local -> global mapping for selectors within this
2652 // module.
2653 F.SelectorRemap.insertOrReplace(
2654 std::make_pair(LocalBaseSelectorID,
2655 F.BaseSelectorID - LocalBaseSelectorID));
2656
2657 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2658 }
2659 break;
2660 }
2661
2662 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002663 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002664 if (Record[0])
2665 F.SelectorLookupTable
2666 = ASTSelectorLookupTable::Create(
2667 F.SelectorLookupTableData + Record[0],
2668 F.SelectorLookupTableData,
2669 ASTSelectorLookupTrait(*this, F));
2670 TotalNumMethodPoolEntries += Record[1];
2671 break;
2672
2673 case REFERENCED_SELECTOR_POOL:
2674 if (!Record.empty()) {
2675 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2676 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2677 Record[Idx++]));
2678 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2679 getRawEncoding());
2680 }
2681 }
2682 break;
2683
2684 case PP_COUNTER_VALUE:
2685 if (!Record.empty() && Listener)
2686 Listener->ReadCounter(F, Record[0]);
2687 break;
2688
2689 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002690 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002691 F.NumFileSortedDecls = Record[0];
2692 break;
2693
2694 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002695 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696 F.LocalNumSLocEntries = Record[0];
2697 unsigned SLocSpaceSize = Record[1];
Stephen Hines651f13c2014-04-23 16:59:28 -07002698 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002699 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2700 SLocSpaceSize);
2701 // Make our entry in the range map. BaseID is negative and growing, so
2702 // we invert it. Because we invert it, though, we need the other end of
2703 // the range.
2704 unsigned RangeStart =
2705 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2706 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2707 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2708
2709 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2710 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2711 GlobalSLocOffsetMap.insert(
2712 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2713 - SLocSpaceSize,&F));
2714
2715 // Initialize the remapping table.
2716 // Invalid stays invalid.
Stephen Hines651f13c2014-04-23 16:59:28 -07002717 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002718 // This module. Base was 2 when being compiled.
Stephen Hines651f13c2014-04-23 16:59:28 -07002719 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002720 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2721
2722 TotalNumSLocEntries += F.LocalNumSLocEntries;
2723 break;
2724 }
2725
2726 case MODULE_OFFSET_MAP: {
2727 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002728 const unsigned char *Data = (const unsigned char*)Blob.data();
2729 const unsigned char *DataEnd = Data + Blob.size();
Stephen Hines651f13c2014-04-23 16:59:28 -07002730
2731 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2732 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2733 F.SLocRemap.insert(std::make_pair(0U, 0));
2734 F.SLocRemap.insert(std::make_pair(2U, 1));
2735 }
2736
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002737 // Continuous range maps we may be updating in our module.
2738 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2739 ContinuousRangeMap<uint32_t, int, 2>::Builder
2740 IdentifierRemap(F.IdentifierRemap);
2741 ContinuousRangeMap<uint32_t, int, 2>::Builder
2742 MacroRemap(F.MacroRemap);
2743 ContinuousRangeMap<uint32_t, int, 2>::Builder
2744 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2745 ContinuousRangeMap<uint32_t, int, 2>::Builder
2746 SubmoduleRemap(F.SubmoduleRemap);
2747 ContinuousRangeMap<uint32_t, int, 2>::Builder
2748 SelectorRemap(F.SelectorRemap);
2749 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2750 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2751
2752 while(Data < DataEnd) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002753 using namespace llvm::support;
2754 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002755 StringRef Name = StringRef((const char*)Data, Len);
2756 Data += Len;
2757 ModuleFile *OM = ModuleMgr.lookup(Name);
2758 if (!OM) {
2759 Error("SourceLocation remap refers to unknown module");
2760 return true;
2761 }
2762
Stephen Hines651f13c2014-04-23 16:59:28 -07002763 uint32_t SLocOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765 uint32_t IdentifierIDOffset =
2766 endian::readNext<uint32_t, little, unaligned>(Data);
2767 uint32_t MacroIDOffset =
2768 endian::readNext<uint32_t, little, unaligned>(Data);
2769 uint32_t PreprocessedEntityIDOffset =
2770 endian::readNext<uint32_t, little, unaligned>(Data);
2771 uint32_t SubmoduleIDOffset =
2772 endian::readNext<uint32_t, little, unaligned>(Data);
2773 uint32_t SelectorIDOffset =
2774 endian::readNext<uint32_t, little, unaligned>(Data);
2775 uint32_t DeclIDOffset =
2776 endian::readNext<uint32_t, little, unaligned>(Data);
2777 uint32_t TypeIndexOffset =
2778 endian::readNext<uint32_t, little, unaligned>(Data);
2779
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002780 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2781 SLocRemap.insert(std::make_pair(SLocOffset,
2782 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2783 IdentifierRemap.insert(
2784 std::make_pair(IdentifierIDOffset,
2785 OM->BaseIdentifierID - IdentifierIDOffset));
2786 MacroRemap.insert(std::make_pair(MacroIDOffset,
2787 OM->BaseMacroID - MacroIDOffset));
2788 PreprocessedEntityRemap.insert(
2789 std::make_pair(PreprocessedEntityIDOffset,
2790 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2791 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2792 OM->BaseSubmoduleID - SubmoduleIDOffset));
2793 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2794 OM->BaseSelectorID - SelectorIDOffset));
2795 DeclRemap.insert(std::make_pair(DeclIDOffset,
2796 OM->BaseDeclID - DeclIDOffset));
2797
2798 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2799 OM->BaseTypeIndex - TypeIndexOffset));
2800
2801 // Global -> local mappings.
2802 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2803 }
2804 break;
2805 }
2806
2807 case SOURCE_MANAGER_LINE_TABLE:
2808 if (ParseLineTable(F, Record))
2809 return true;
2810 break;
2811
2812 case SOURCE_LOCATION_PRELOADS: {
2813 // Need to transform from the local view (1-based IDs) to the global view,
2814 // which is based off F.SLocEntryBaseID.
2815 if (!F.PreloadSLocEntries.empty()) {
2816 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2817 return true;
2818 }
2819
2820 F.PreloadSLocEntries.swap(Record);
2821 break;
2822 }
2823
2824 case EXT_VECTOR_DECLS:
2825 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2826 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2827 break;
2828
2829 case VTABLE_USES:
2830 if (Record.size() % 3 != 0) {
2831 Error("Invalid VTABLE_USES record");
2832 return true;
2833 }
2834
2835 // Later tables overwrite earlier ones.
2836 // FIXME: Modules will have some trouble with this. This is clearly not
2837 // the right way to do this.
2838 VTableUses.clear();
2839
2840 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2841 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2842 VTableUses.push_back(
2843 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2844 VTableUses.push_back(Record[Idx++]);
2845 }
2846 break;
2847
2848 case DYNAMIC_CLASSES:
2849 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2850 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2851 break;
2852
2853 case PENDING_IMPLICIT_INSTANTIATIONS:
2854 if (PendingInstantiations.size() % 2 != 0) {
2855 Error("Invalid existing PendingInstantiations");
2856 return true;
2857 }
2858
2859 if (Record.size() % 2 != 0) {
2860 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2861 return true;
2862 }
2863
2864 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2865 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2866 PendingInstantiations.push_back(
2867 ReadSourceLocation(F, Record, I).getRawEncoding());
2868 }
2869 break;
2870
2871 case SEMA_DECL_REFS:
Richard Smith9b671182013-10-18 06:54:39 +00002872 if (Record.size() != 2) {
2873 Error("Invalid SEMA_DECL_REFS block");
2874 return true;
2875 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002876 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2877 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2878 break;
2879
2880 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002881 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2882 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2883 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002884
2885 unsigned LocalBasePreprocessedEntityID = Record[0];
2886
2887 unsigned StartingID;
2888 if (!PP.getPreprocessingRecord())
2889 PP.createPreprocessingRecord();
2890 if (!PP.getPreprocessingRecord()->getExternalSource())
2891 PP.getPreprocessingRecord()->SetExternalSource(*this);
2892 StartingID
2893 = PP.getPreprocessingRecord()
2894 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2895 F.BasePreprocessedEntityID = StartingID;
2896
2897 if (F.NumPreprocessedEntities > 0) {
2898 // Introduce the global -> local mapping for preprocessed entities in
2899 // this module.
2900 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2901
2902 // Introduce the local -> global mapping for preprocessed entities in
2903 // this module.
2904 F.PreprocessedEntityRemap.insertOrReplace(
2905 std::make_pair(LocalBasePreprocessedEntityID,
2906 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2907 }
2908
2909 break;
2910 }
2911
2912 case DECL_UPDATE_OFFSETS: {
2913 if (Record.size() % 2 != 0) {
2914 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2915 return true;
2916 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002917 // FIXME: If we've already loaded the decl, perform the updates now.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002918 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2919 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2920 .push_back(std::make_pair(&F, Record[I+1]));
2921 break;
2922 }
2923
2924 case DECL_REPLACEMENTS: {
2925 if (Record.size() % 3 != 0) {
2926 Error("invalid DECL_REPLACEMENTS block in AST file");
2927 return true;
2928 }
2929 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2930 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2931 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2932 break;
2933 }
2934
2935 case OBJC_CATEGORIES_MAP: {
2936 if (F.LocalNumObjCCategoriesInMap != 0) {
2937 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2938 return true;
2939 }
2940
2941 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002942 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002943 break;
2944 }
2945
2946 case OBJC_CATEGORIES:
2947 F.ObjCCategories.swap(Record);
2948 break;
2949
2950 case CXX_BASE_SPECIFIER_OFFSETS: {
2951 if (F.LocalNumCXXBaseSpecifiers != 0) {
2952 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2953 return true;
2954 }
2955
2956 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002957 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002958 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2959 break;
2960 }
2961
2962 case DIAG_PRAGMA_MAPPINGS:
2963 if (F.PragmaDiagMappings.empty())
2964 F.PragmaDiagMappings.swap(Record);
2965 else
2966 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2967 Record.begin(), Record.end());
2968 break;
2969
2970 case CUDA_SPECIAL_DECL_REFS:
2971 // Later tables overwrite earlier ones.
2972 // FIXME: Modules will have trouble with this.
2973 CUDASpecialDeclRefs.clear();
2974 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2975 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2976 break;
2977
2978 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002979 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002980 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002981 if (Record[0]) {
2982 F.HeaderFileInfoTable
2983 = HeaderFileInfoLookupTable::Create(
2984 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2985 (const unsigned char *)F.HeaderFileInfoTableData,
2986 HeaderFileInfoTrait(*this, F,
2987 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002988 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002989
2990 PP.getHeaderSearchInfo().SetExternalSource(this);
2991 if (!PP.getHeaderSearchInfo().getExternalLookup())
2992 PP.getHeaderSearchInfo().SetExternalLookup(this);
2993 }
2994 break;
2995 }
2996
2997 case FP_PRAGMA_OPTIONS:
2998 // Later tables overwrite earlier ones.
2999 FPPragmaOptions.swap(Record);
3000 break;
3001
3002 case OPENCL_EXTENSIONS:
3003 // Later tables overwrite earlier ones.
3004 OpenCLExtensions.swap(Record);
3005 break;
3006
3007 case TENTATIVE_DEFINITIONS:
3008 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3009 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3010 break;
3011
3012 case KNOWN_NAMESPACES:
3013 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3014 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3015 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00003016
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003017 case UNDEFINED_BUT_USED:
3018 if (UndefinedButUsed.size() % 2 != 0) {
3019 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00003020 return true;
3021 }
3022
3023 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003024 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00003025 return true;
3026 }
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00003028 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3029 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00003030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
3033
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003034 case IMPORTED_MODULES: {
3035 if (F.Kind != MK_Module) {
3036 // If we aren't loading a module (which has its own exports), make
3037 // all of the imported modules visible.
3038 // FIXME: Deal with macros-only imports.
Stephen Hines651f13c2014-04-23 16:59:28 -07003039 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3040 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3041 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3042 if (GlobalID)
3043 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003044 }
3045 }
3046 break;
3047 }
3048
3049 case LOCAL_REDECLARATIONS: {
3050 F.RedeclarationChains.swap(Record);
3051 break;
3052 }
3053
3054 case LOCAL_REDECLARATIONS_MAP: {
3055 if (F.LocalNumRedeclarationsInMap != 0) {
3056 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3057 return true;
3058 }
3059
3060 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003061 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003062 break;
3063 }
3064
3065 case MERGED_DECLARATIONS: {
3066 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3067 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3068 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3069 for (unsigned N = Record[Idx++]; N > 0; --N)
3070 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3071 }
3072 break;
3073 }
3074
3075 case MACRO_OFFSET: {
3076 if (F.LocalNumMacros != 0) {
3077 Error("duplicate MACRO_OFFSET record in AST file");
3078 return true;
3079 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003080 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003081 F.LocalNumMacros = Record[0];
3082 unsigned LocalBaseMacroID = Record[1];
3083 F.BaseMacroID = getTotalNumMacros();
3084
3085 if (F.LocalNumMacros > 0) {
3086 // Introduce the global -> local mapping for macros within this module.
3087 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3088
3089 // Introduce the local -> global mapping for macros within this module.
3090 F.MacroRemap.insertOrReplace(
3091 std::make_pair(LocalBaseMacroID,
3092 F.BaseMacroID - LocalBaseMacroID));
3093
3094 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3095 }
3096 break;
3097 }
3098
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00003099 case MACRO_TABLE: {
3100 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003101 break;
3102 }
Richard Smithac32d902013-08-07 21:41:30 +00003103
3104 case LATE_PARSED_TEMPLATE: {
3105 LateParsedTemplates.append(Record.begin(), Record.end());
3106 break;
3107 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003108 }
3109 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003110}
3111
Douglas Gregor2cbd4272013-02-12 23:36:21 +00003112/// \brief Move the given method to the back of the global list of methods.
3113static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3114 // Find the entry for this selector in the method pool.
3115 Sema::GlobalMethodPool::iterator Known
3116 = S.MethodPool.find(Method->getSelector());
3117 if (Known == S.MethodPool.end())
3118 return;
3119
3120 // Retrieve the appropriate method list.
3121 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3122 : Known->second.second;
3123 bool Found = false;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00003124 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00003125 if (!Found) {
3126 if (List->Method == Method) {
3127 Found = true;
3128 } else {
3129 // Keep searching.
3130 continue;
3131 }
3132 }
3133
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00003134 if (List->getNext())
3135 List->Method = List->getNext()->Method;
Douglas Gregor2cbd4272013-02-12 23:36:21 +00003136 else
3137 List->Method = Method;
3138 }
3139}
3140
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003141void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003142 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3143 Decl *D = Names.HiddenDecls[I];
3144 bool wasHidden = D->Hidden;
3145 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003146
Stephen Hines651f13c2014-04-23 16:59:28 -07003147 if (wasHidden && SemaObj) {
3148 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3149 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregor2cbd4272013-02-12 23:36:21 +00003150 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003151 }
3152 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003153
3154 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3155 E = Names.HiddenMacros.end();
3156 I != E; ++I)
3157 installImportedMacro(I->first, I->second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003158}
3159
Stephen Hines651f13c2014-04-23 16:59:28 -07003160void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003161 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003162 SourceLocation ImportLoc,
3163 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003164 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003165 SmallVector<Module *, 4> Stack;
Robert Wilhelm344472e2013-08-23 16:11:15 +00003166 Stack.push_back(Mod);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003167 while (!Stack.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00003168 Mod = Stack.pop_back_val();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003169
3170 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00003171 // This module already has this level of visibility (or greater), so
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003172 // there is nothing more to do.
3173 continue;
3174 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003175
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003176 if (!Mod->isAvailable()) {
3177 // Modules that aren't available cannot be made visible.
3178 continue;
3179 }
3180
3181 // Update the module's name visibility.
Stephen Hines651f13c2014-04-23 16:59:28 -07003182 if (NameVisibility >= Module::MacrosVisible &&
3183 Mod->NameVisibility < Module::MacrosVisible)
3184 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003185 Mod->NameVisibility = NameVisibility;
Stephen Hines651f13c2014-04-23 16:59:28 -07003186
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003187 // If we've already deserialized any names from this module,
3188 // mark them as visible.
3189 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3190 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003191 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003192 HiddenNamesMap.erase(Hidden);
3193 }
Dmitri Gribenko86250892013-11-04 21:51:33 +00003194
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003195 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00003196 SmallVector<Module *, 16> Exports;
3197 Mod->getExportedModules(Exports);
3198 for (SmallVectorImpl<Module *>::iterator
3199 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3200 Module *Exported = *I;
3201 if (Visited.insert(Exported))
3202 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003203 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003204
3205 // Detect any conflicts.
3206 if (Complain) {
3207 assert(ImportLoc.isValid() && "Missing import location");
3208 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3209 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3210 Diag(ImportLoc, diag::warn_module_conflict)
3211 << Mod->getFullModuleName()
3212 << Mod->Conflicts[I].Other->getFullModuleName()
3213 << Mod->Conflicts[I].Message;
3214 // FIXME: Need note where the other module was imported.
3215 }
3216 }
3217 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003218 }
3219}
3220
Douglas Gregor1a49d972013-01-25 01:03:03 +00003221bool ASTReader::loadGlobalIndex() {
3222 if (GlobalIndex)
3223 return false;
3224
3225 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3226 !Context.getLangOpts().Modules)
3227 return true;
3228
3229 // Try to load the global index.
3230 TriedLoadingGlobalIndex = true;
3231 StringRef ModuleCachePath
3232 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3233 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00003234 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00003235 if (!Result.first)
3236 return true;
3237
3238 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00003239 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00003240 return false;
3241}
3242
3243bool ASTReader::isGlobalIndexUnavailable() const {
3244 return Context.getLangOpts().Modules && UseGlobalIndex &&
3245 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3246}
3247
Stephen Hines651f13c2014-04-23 16:59:28 -07003248static void updateModuleTimestamp(ModuleFile &MF) {
3249 // Overwrite the timestamp file contents so that file's mtime changes.
3250 std::string TimestampFilename = MF.getTimestampFilename();
3251 std::string ErrorInfo;
3252 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
3253 llvm::sys::fs::F_Text);
3254 if (!ErrorInfo.empty())
3255 return;
3256 OS << "Timestamp file\n";
3257}
3258
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003259ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3260 ModuleKind Type,
3261 SourceLocation ImportLoc,
3262 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00003263 llvm::SaveAndRestore<SourceLocation>
3264 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3265
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003266 // Bump the generation number.
3267 unsigned PreviousGeneration = CurrentGeneration++;
3268
3269 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003270 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003271 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3272 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003273 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003274 ClientLoadCapabilities)) {
3275 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00003276 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003277 case OutOfDate:
3278 case VersionMismatch:
3279 case ConfigurationMismatch:
3280 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00003281 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3282 Context.getLangOpts().Modules
3283 ? &PP.getHeaderSearchInfo().getModuleMap()
3284 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00003285
3286 // If we find that any modules are unusable, the global index is going
3287 // to be out-of-date. Just remove it.
3288 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00003289 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003290 return ReadResult;
3291
3292 case Success:
3293 break;
3294 }
3295
3296 // Here comes stuff that we only do once the entire chain is loaded.
3297
3298 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003299 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3300 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003301 M != MEnd; ++M) {
3302 ModuleFile &F = *M->Mod;
3303
3304 // Read the AST block.
3305 if (ReadASTBlock(F))
3306 return Failure;
3307
3308 // Once read, set the ModuleFile bit base offset and update the size in
3309 // bits of all files we've seen.
3310 F.GlobalBitOffset = TotalModulesSizeInBits;
3311 TotalModulesSizeInBits += F.SizeInBits;
3312 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3313
3314 // Preload SLocEntries.
3315 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3316 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3317 // Load it through the SourceManager and don't call ReadSLocEntry()
3318 // directly because the entry may have already been loaded in which case
3319 // calling ReadSLocEntry() directly would trigger an assertion in
3320 // SourceManager.
3321 SourceMgr.getLoadedSLocEntryByID(Index);
3322 }
3323 }
3324
Douglas Gregorfa69fc12013-03-22 18:50:14 +00003325 // Setup the import locations and notify the module manager that we've
3326 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003327 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3328 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003329 M != MEnd; ++M) {
3330 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00003331
3332 ModuleMgr.moduleFileAccepted(&F);
3333
3334 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00003335 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003336 if (!M->ImportedBy)
3337 F.ImportLoc = M->ImportLoc;
3338 else
3339 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3340 M->ImportLoc.getRawEncoding());
3341 }
3342
3343 // Mark all of the identifiers in the identifier table as being out of date,
3344 // so that various accessors know to check the loaded modules when the
3345 // identifier is used.
3346 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3347 IdEnd = PP.getIdentifierTable().end();
3348 Id != IdEnd; ++Id)
3349 Id->second->setOutOfDate(true);
3350
3351 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00003352 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3353 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003354 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3355 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00003356
3357 switch (Unresolved.Kind) {
3358 case UnresolvedModuleRef::Conflict:
3359 if (ResolvedMod) {
3360 Module::Conflict Conflict;
3361 Conflict.Other = ResolvedMod;
3362 Conflict.Message = Unresolved.String.str();
3363 Unresolved.Mod->Conflicts.push_back(Conflict);
3364 }
3365 continue;
3366
3367 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003368 if (ResolvedMod)
3369 Unresolved.Mod->Imports.push_back(ResolvedMod);
3370 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003371
Douglas Gregor906d66a2013-03-20 21:10:35 +00003372 case UnresolvedModuleRef::Export:
3373 if (ResolvedMod || Unresolved.IsWildcard)
3374 Unresolved.Mod->Exports.push_back(
3375 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3376 continue;
3377 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003378 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003379 UnresolvedModuleRefs.clear();
Daniel Jasperddd2dfc2013-09-24 09:14:14 +00003380
3381 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3382 // Might be unnecessary as use declarations are only used to build the
3383 // module itself.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003384
3385 InitializeContext();
3386
Richard Smith9b671182013-10-18 06:54:39 +00003387 if (SemaObj)
3388 UpdateSema();
3389
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003390 if (DeserializationListener)
3391 DeserializationListener->ReaderInitialized(this);
3392
3393 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3394 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3395 PrimaryModule.OriginalSourceFileID
3396 = FileID::get(PrimaryModule.SLocEntryBaseID
3397 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3398
3399 // If this AST file is a precompiled preamble, then set the
3400 // preamble file ID of the source manager to the file source file
3401 // from which the preamble was built.
3402 if (Type == MK_Preamble) {
3403 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3404 } else if (Type == MK_MainFile) {
3405 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3406 }
3407 }
3408
3409 // For any Objective-C class definitions we have already loaded, make sure
3410 // that we load any additional categories.
3411 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3412 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3413 ObjCClassesLoaded[I],
3414 PreviousGeneration);
3415 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003416
Stephen Hines651f13c2014-04-23 16:59:28 -07003417 if (PP.getHeaderSearchInfo()
3418 .getHeaderSearchOpts()
3419 .ModulesValidateOncePerBuildSession) {
3420 // Now we are certain that the module and all modules it depends on are
3421 // up to date. Create or update timestamp files for modules that are
3422 // located in the module cache (not for PCH files that could be anywhere
3423 // in the filesystem).
3424 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3425 ImportedModule &M = Loaded[I];
3426 if (M.Mod->Kind == MK_Module) {
3427 updateModuleTimestamp(*M.Mod);
3428 }
3429 }
3430 }
3431
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003432 return Success;
3433}
3434
3435ASTReader::ASTReadResult
3436ASTReader::ReadASTCore(StringRef FileName,
3437 ModuleKind Type,
3438 SourceLocation ImportLoc,
3439 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003440 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003441 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003442 unsigned ClientLoadCapabilities) {
3443 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003444 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003445 ModuleManager::AddModuleResult AddResult
3446 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3447 CurrentGeneration, ExpectedSize, ExpectedModTime,
3448 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003449
Douglas Gregor677e15f2013-03-19 00:28:20 +00003450 switch (AddResult) {
3451 case ModuleManager::AlreadyLoaded:
3452 return Success;
3453
3454 case ModuleManager::NewlyLoaded:
3455 // Load module file below.
3456 break;
3457
3458 case ModuleManager::Missing:
3459 // The module file was missing; if the client handle handle, that, return
3460 // it.
3461 if (ClientLoadCapabilities & ARR_Missing)
3462 return Missing;
3463
3464 // Otherwise, return an error.
3465 {
3466 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3467 + ErrorStr;
3468 Error(Msg);
3469 }
3470 return Failure;
3471
3472 case ModuleManager::OutOfDate:
3473 // We couldn't load the module file because it is out-of-date. If the
3474 // client can handle out-of-date, return it.
3475 if (ClientLoadCapabilities & ARR_OutOfDate)
3476 return OutOfDate;
3477
3478 // Otherwise, return an error.
3479 {
3480 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3481 + ErrorStr;
3482 Error(Msg);
3483 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003484 return Failure;
3485 }
3486
Douglas Gregor677e15f2013-03-19 00:28:20 +00003487 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003488
3489 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3490 // module?
3491 if (FileName != "-") {
3492 CurrentDir = llvm::sys::path::parent_path(FileName);
3493 if (CurrentDir.empty()) CurrentDir = ".";
3494 }
3495
3496 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003497 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003498 Stream.init(F.StreamFile);
3499 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3500
3501 // Sniff for the signature.
3502 if (Stream.Read(8) != 'C' ||
3503 Stream.Read(8) != 'P' ||
3504 Stream.Read(8) != 'C' ||
3505 Stream.Read(8) != 'H') {
3506 Diag(diag::err_not_a_pch_file) << FileName;
3507 return Failure;
3508 }
3509
3510 // This is used for compatibility with older PCH formats.
3511 bool HaveReadControlBlock = false;
3512
Chris Lattner99a5af02013-01-20 00:00:22 +00003513 while (1) {
3514 llvm::BitstreamEntry Entry = Stream.advance();
3515
3516 switch (Entry.Kind) {
3517 case llvm::BitstreamEntry::Error:
3518 case llvm::BitstreamEntry::EndBlock:
3519 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003520 Error("invalid record at top-level of AST file");
3521 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003522
3523 case llvm::BitstreamEntry::SubBlock:
3524 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003525 }
3526
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003527 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003528 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003529 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3530 if (Stream.ReadBlockInfoBlock()) {
3531 Error("malformed BlockInfoBlock in AST file");
3532 return Failure;
3533 }
3534 break;
3535 case CONTROL_BLOCK_ID:
3536 HaveReadControlBlock = true;
3537 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3538 case Success:
3539 break;
3540
3541 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003542 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003543 case OutOfDate: return OutOfDate;
3544 case VersionMismatch: return VersionMismatch;
3545 case ConfigurationMismatch: return ConfigurationMismatch;
3546 case HadErrors: return HadErrors;
3547 }
3548 break;
3549 case AST_BLOCK_ID:
3550 if (!HaveReadControlBlock) {
3551 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -07003552 Diag(diag::err_pch_version_too_old);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003553 return VersionMismatch;
3554 }
3555
3556 // Record that we've loaded this module.
3557 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3558 return Success;
3559
3560 default:
3561 if (Stream.SkipBlock()) {
3562 Error("malformed block record in AST file");
3563 return Failure;
3564 }
3565 break;
3566 }
3567 }
3568
3569 return Success;
3570}
3571
3572void ASTReader::InitializeContext() {
3573 // If there's a listener, notify them that we "read" the translation unit.
3574 if (DeserializationListener)
3575 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3576 Context.getTranslationUnitDecl());
3577
3578 // Make sure we load the declaration update records for the translation unit,
3579 // if there are any.
3580 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3581 Context.getTranslationUnitDecl());
3582
3583 // FIXME: Find a better way to deal with collisions between these
3584 // built-in types. Right now, we just ignore the problem.
3585
3586 // Load the special types.
3587 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3588 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3589 if (!Context.CFConstantStringTypeDecl)
3590 Context.setCFConstantStringType(GetType(String));
3591 }
3592
3593 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3594 QualType FileType = GetType(File);
3595 if (FileType.isNull()) {
3596 Error("FILE type is NULL");
3597 return;
3598 }
3599
3600 if (!Context.FILEDecl) {
3601 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3602 Context.setFILEDecl(Typedef->getDecl());
3603 else {
3604 const TagType *Tag = FileType->getAs<TagType>();
3605 if (!Tag) {
3606 Error("Invalid FILE type in AST file");
3607 return;
3608 }
3609 Context.setFILEDecl(Tag->getDecl());
3610 }
3611 }
3612 }
3613
3614 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3615 QualType Jmp_bufType = GetType(Jmp_buf);
3616 if (Jmp_bufType.isNull()) {
3617 Error("jmp_buf type is NULL");
3618 return;
3619 }
3620
3621 if (!Context.jmp_bufDecl) {
3622 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3623 Context.setjmp_bufDecl(Typedef->getDecl());
3624 else {
3625 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3626 if (!Tag) {
3627 Error("Invalid jmp_buf type in AST file");
3628 return;
3629 }
3630 Context.setjmp_bufDecl(Tag->getDecl());
3631 }
3632 }
3633 }
3634
3635 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3636 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3637 if (Sigjmp_bufType.isNull()) {
3638 Error("sigjmp_buf type is NULL");
3639 return;
3640 }
3641
3642 if (!Context.sigjmp_bufDecl) {
3643 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3644 Context.setsigjmp_bufDecl(Typedef->getDecl());
3645 else {
3646 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3647 assert(Tag && "Invalid sigjmp_buf type in AST file");
3648 Context.setsigjmp_bufDecl(Tag->getDecl());
3649 }
3650 }
3651 }
3652
3653 if (unsigned ObjCIdRedef
3654 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3655 if (Context.ObjCIdRedefinitionType.isNull())
3656 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3657 }
3658
3659 if (unsigned ObjCClassRedef
3660 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3661 if (Context.ObjCClassRedefinitionType.isNull())
3662 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3663 }
3664
3665 if (unsigned ObjCSelRedef
3666 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3667 if (Context.ObjCSelRedefinitionType.isNull())
3668 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3669 }
3670
3671 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3672 QualType Ucontext_tType = GetType(Ucontext_t);
3673 if (Ucontext_tType.isNull()) {
3674 Error("ucontext_t type is NULL");
3675 return;
3676 }
3677
3678 if (!Context.ucontext_tDecl) {
3679 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3680 Context.setucontext_tDecl(Typedef->getDecl());
3681 else {
3682 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3683 assert(Tag && "Invalid ucontext_t type in AST file");
3684 Context.setucontext_tDecl(Tag->getDecl());
3685 }
3686 }
3687 }
3688 }
3689
3690 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3691
3692 // If there were any CUDA special declarations, deserialize them.
3693 if (!CUDASpecialDeclRefs.empty()) {
3694 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3695 Context.setcudaConfigureCallDecl(
3696 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3697 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003698
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003699 // Re-export any modules that were imported by a non-module AST file.
Stephen Hines651f13c2014-04-23 16:59:28 -07003700 // FIXME: This does not make macro-only imports visible again. It also doesn't
3701 // make #includes mapped to module imports visible.
3702 for (auto &Import : ImportedModules) {
3703 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003704 makeModuleVisible(Imported, Module::AllVisible,
Stephen Hines651f13c2014-04-23 16:59:28 -07003705 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003706 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003707 }
3708 ImportedModules.clear();
3709}
3710
3711void ASTReader::finalizeForWriting() {
3712 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3713 HiddenEnd = HiddenNamesMap.end();
3714 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003715 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003716 }
3717 HiddenNamesMap.clear();
3718}
3719
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003720/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3721/// cursor into the start of the given block ID, returning false on success and
3722/// true on failure.
3723static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003724 while (1) {
3725 llvm::BitstreamEntry Entry = Cursor.advance();
3726 switch (Entry.Kind) {
3727 case llvm::BitstreamEntry::Error:
3728 case llvm::BitstreamEntry::EndBlock:
3729 return true;
3730
3731 case llvm::BitstreamEntry::Record:
3732 // Ignore top-level records.
3733 Cursor.skipRecord(Entry.ID);
3734 break;
3735
3736 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003737 if (Entry.ID == BlockID) {
3738 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003739 return true;
3740 // Found it!
3741 return false;
3742 }
3743
3744 if (Cursor.SkipBlock())
3745 return true;
3746 }
3747 }
3748}
3749
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003750/// \brief Retrieve the name of the original source file name
3751/// directly from the AST file, without actually loading the AST
3752/// file.
3753std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3754 FileManager &FileMgr,
3755 DiagnosticsEngine &Diags) {
3756 // Open the AST file.
3757 std::string ErrStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003758 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003759 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3760 if (!Buffer) {
3761 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3762 return std::string();
3763 }
3764
3765 // Initialize the stream
3766 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003767 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003768 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3769 (const unsigned char *)Buffer->getBufferEnd());
3770 Stream.init(StreamFile);
3771
3772 // Sniff for the signature.
3773 if (Stream.Read(8) != 'C' ||
3774 Stream.Read(8) != 'P' ||
3775 Stream.Read(8) != 'C' ||
3776 Stream.Read(8) != 'H') {
3777 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3778 return std::string();
3779 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003780
Chris Lattner88bde502013-01-19 21:39:22 +00003781 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003782 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003783 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3784 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003785 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003786
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003787 // Scan for ORIGINAL_FILE inside the control block.
3788 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003789 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003790 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003791 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3792 return std::string();
3793
3794 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3795 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3796 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003797 }
Chris Lattner88bde502013-01-19 21:39:22 +00003798
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003799 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003800 StringRef Blob;
3801 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3802 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003803 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003804}
3805
3806namespace {
3807 class SimplePCHValidator : public ASTReaderListener {
3808 const LangOptions &ExistingLangOpts;
3809 const TargetOptions &ExistingTargetOpts;
3810 const PreprocessorOptions &ExistingPPOpts;
3811 FileManager &FileMgr;
3812
3813 public:
3814 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3815 const TargetOptions &ExistingTargetOpts,
3816 const PreprocessorOptions &ExistingPPOpts,
3817 FileManager &FileMgr)
3818 : ExistingLangOpts(ExistingLangOpts),
3819 ExistingTargetOpts(ExistingTargetOpts),
3820 ExistingPPOpts(ExistingPPOpts),
3821 FileMgr(FileMgr)
3822 {
3823 }
3824
Stephen Hines651f13c2014-04-23 16:59:28 -07003825 bool ReadLanguageOptions(const LangOptions &LangOpts,
3826 bool Complain) override {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003827 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3828 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003829 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3830 bool Complain) override {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003831 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3832 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003833 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3834 bool Complain,
3835 std::string &SuggestedPredefines) override {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003836 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00003837 SuggestedPredefines, ExistingLangOpts);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003838 }
3839 };
3840}
3841
3842bool ASTReader::readASTFileControlBlock(StringRef Filename,
3843 FileManager &FileMgr,
3844 ASTReaderListener &Listener) {
3845 // Open the AST file.
3846 std::string ErrStr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003847 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003848 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3849 if (!Buffer) {
3850 return true;
3851 }
3852
3853 // Initialize the stream
3854 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003855 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003856 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3857 (const unsigned char *)Buffer->getBufferEnd());
3858 Stream.init(StreamFile);
3859
3860 // Sniff for the signature.
3861 if (Stream.Read(8) != 'C' ||
3862 Stream.Read(8) != 'P' ||
3863 Stream.Read(8) != 'C' ||
3864 Stream.Read(8) != 'H') {
3865 return true;
3866 }
3867
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003868 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003869 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003870 return true;
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003871
3872 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Stephen Hines651f13c2014-04-23 16:59:28 -07003873 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003874 BitstreamCursor InputFilesCursor;
3875 if (NeedsInputFiles) {
3876 InputFilesCursor = Stream;
3877 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3878 return true;
3879
3880 // Read the abbreviations
3881 while (true) {
3882 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3883 unsigned Code = InputFilesCursor.ReadCode();
3884
3885 // We expect all abbrevs to be at the start of the block.
3886 if (Code != llvm::bitc::DEFINE_ABBREV) {
3887 InputFilesCursor.JumpToBit(Offset);
3888 break;
3889 }
3890 InputFilesCursor.ReadAbbrevRecord();
3891 }
3892 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003893
3894 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003895 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003896 while (1) {
3897 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3898 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3899 return false;
3900
3901 if (Entry.Kind != llvm::BitstreamEntry::Record)
3902 return true;
3903
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003904 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003905 StringRef Blob;
3906 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003907 switch ((ControlRecordTypes)RecCode) {
3908 case METADATA: {
3909 if (Record[0] != VERSION_MAJOR)
3910 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003911
Douglas Gregorc544ba02013-03-27 16:47:18 +00003912 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003913 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003914
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003915 break;
3916 }
3917 case LANGUAGE_OPTIONS:
3918 if (ParseLanguageOptions(Record, false, Listener))
3919 return true;
3920 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003921
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003922 case TARGET_OPTIONS:
3923 if (ParseTargetOptions(Record, false, Listener))
3924 return true;
3925 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003926
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003927 case DIAGNOSTIC_OPTIONS:
3928 if (ParseDiagnosticOptions(Record, false, Listener))
3929 return true;
3930 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003931
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003932 case FILE_SYSTEM_OPTIONS:
3933 if (ParseFileSystemOptions(Record, false, Listener))
3934 return true;
3935 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003936
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003937 case HEADER_SEARCH_OPTIONS:
3938 if (ParseHeaderSearchOptions(Record, false, Listener))
3939 return true;
3940 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003941
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003942 case PREPROCESSOR_OPTIONS: {
3943 std::string IgnoredSuggestedPredefines;
3944 if (ParsePreprocessorOptions(Record, false, Listener,
3945 IgnoredSuggestedPredefines))
3946 return true;
3947 break;
3948 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003949
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003950 case INPUT_FILE_OFFSETS: {
3951 if (!NeedsInputFiles)
3952 break;
3953
3954 unsigned NumInputFiles = Record[0];
3955 unsigned NumUserFiles = Record[1];
3956 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3957 for (unsigned I = 0; I != NumInputFiles; ++I) {
3958 // Go find this input file.
3959 bool isSystemFile = I >= NumUserFiles;
Stephen Hines651f13c2014-04-23 16:59:28 -07003960
3961 if (isSystemFile && !NeedsSystemInputFiles)
3962 break; // the rest are system input files
3963
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003964 BitstreamCursor &Cursor = InputFilesCursor;
3965 SavedStreamPosition SavedPosition(Cursor);
3966 Cursor.JumpToBit(InputFileOffs[I]);
3967
3968 unsigned Code = Cursor.ReadCode();
3969 RecordData Record;
3970 StringRef Blob;
3971 bool shouldContinue = false;
3972 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3973 case INPUT_FILE:
Stephen Hines651f13c2014-04-23 16:59:28 -07003974 bool Overridden = static_cast<bool>(Record[3]);
3975 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisbdfdb1d2013-05-06 19:23:40 +00003976 break;
3977 }
3978 if (!shouldContinue)
3979 break;
3980 }
3981 break;
3982 }
3983
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003984 default:
3985 // No other validation to perform.
3986 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003987 }
3988 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003989}
3990
3991
3992bool ASTReader::isAcceptableASTFile(StringRef Filename,
3993 FileManager &FileMgr,
3994 const LangOptions &LangOpts,
3995 const TargetOptions &TargetOpts,
3996 const PreprocessorOptions &PPOpts) {
3997 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3998 return !readASTFileControlBlock(Filename, FileMgr, validator);
3999}
4000
4001bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
4002 // Enter the submodule block.
4003 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4004 Error("malformed submodule block record in AST file");
4005 return true;
4006 }
4007
4008 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4009 bool First = true;
4010 Module *CurrentModule = 0;
4011 RecordData Record;
4012 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004013 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4014
4015 switch (Entry.Kind) {
4016 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4017 case llvm::BitstreamEntry::Error:
4018 Error("malformed block record in AST file");
4019 return true;
4020 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004021 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004022 case llvm::BitstreamEntry::Record:
4023 // The interesting case.
4024 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004025 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004026
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004027 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004028 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004029 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004030 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004031 default: // Default behavior: ignore.
4032 break;
4033
4034 case SUBMODULE_DEFINITION: {
4035 if (First) {
4036 Error("missing submodule metadata record at beginning of block");
4037 return true;
4038 }
4039
Douglas Gregor970e4412013-03-20 03:59:18 +00004040 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004041 Error("malformed module definition");
4042 return true;
4043 }
4044
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004045 StringRef Name = Blob;
Stephen Hines651f13c2014-04-23 16:59:28 -07004046 unsigned Idx = 0;
4047 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4048 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4049 bool IsFramework = Record[Idx++];
4050 bool IsExplicit = Record[Idx++];
4051 bool IsSystem = Record[Idx++];
4052 bool IsExternC = Record[Idx++];
4053 bool InferSubmodules = Record[Idx++];
4054 bool InferExplicitSubmodules = Record[Idx++];
4055 bool InferExportWildcard = Record[Idx++];
4056 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor970e4412013-03-20 03:59:18 +00004057
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004058 Module *ParentModule = 0;
4059 if (Parent)
4060 ParentModule = getSubmodule(Parent);
4061
4062 // Retrieve this (sub)module from the module map, creating it if
4063 // necessary.
4064 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4065 IsFramework,
4066 IsExplicit).first;
4067 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4068 if (GlobalIndex >= SubmodulesLoaded.size() ||
4069 SubmodulesLoaded[GlobalIndex]) {
4070 Error("too many submodules");
4071 return true;
4072 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00004073
Douglas Gregor677e15f2013-03-19 00:28:20 +00004074 if (!ParentModule) {
4075 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4076 if (CurFile != F.File) {
4077 if (!Diags.isDiagnosticInFlight()) {
4078 Diag(diag::err_module_file_conflict)
4079 << CurrentModule->getTopLevelModuleName()
4080 << CurFile->getName()
4081 << F.File->getName();
4082 }
4083 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00004084 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00004085 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00004086
4087 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00004088 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00004089
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004090 CurrentModule->IsFromModuleFile = true;
4091 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Stephen Hines651f13c2014-04-23 16:59:28 -07004092 CurrentModule->IsExternC = IsExternC;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004093 CurrentModule->InferSubmodules = InferSubmodules;
4094 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4095 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00004096 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004097 if (DeserializationListener)
4098 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4099
4100 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00004101
Douglas Gregor906d66a2013-03-20 21:10:35 +00004102 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00004103 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00004104 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00004105 CurrentModule->UnresolvedConflicts.clear();
4106 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004107 break;
4108 }
4109
4110 case SUBMODULE_UMBRELLA_HEADER: {
4111 if (First) {
4112 Error("missing submodule metadata record at beginning of block");
4113 return true;
4114 }
4115
4116 if (!CurrentModule)
4117 break;
4118
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004119 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004120 if (!CurrentModule->getUmbrellaHeader())
4121 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4122 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4123 Error("mismatched umbrella headers in submodule");
4124 return true;
4125 }
4126 }
4127 break;
4128 }
4129
4130 case SUBMODULE_HEADER: {
4131 if (First) {
4132 Error("missing submodule metadata record at beginning of block");
4133 return true;
4134 }
4135
4136 if (!CurrentModule)
4137 break;
4138
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00004139 // We lazily associate headers with their modules via the HeaderInfoTable.
4140 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4141 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004142 break;
4143 }
4144
4145 case SUBMODULE_EXCLUDED_HEADER: {
4146 if (First) {
4147 Error("missing submodule metadata record at beginning of block");
4148 return true;
4149 }
4150
4151 if (!CurrentModule)
4152 break;
4153
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00004154 // We lazily associate headers with their modules via the HeaderInfoTable.
4155 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4156 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004157 break;
4158 }
4159
Lawrence Crowlbc3f6282013-06-20 21:14:14 +00004160 case SUBMODULE_PRIVATE_HEADER: {
4161 if (First) {
4162 Error("missing submodule metadata record at beginning of block");
4163 return true;
4164 }
4165
4166 if (!CurrentModule)
4167 break;
4168
4169 // We lazily associate headers with their modules via the HeaderInfoTable.
4170 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4171 // of complete filenames or remove it entirely.
4172 break;
4173 }
4174
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004175 case SUBMODULE_TOPHEADER: {
4176 if (First) {
4177 Error("missing submodule metadata record at beginning of block");
4178 return true;
4179 }
4180
4181 if (!CurrentModule)
4182 break;
4183
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00004184 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004185 break;
4186 }
4187
4188 case SUBMODULE_UMBRELLA_DIR: {
4189 if (First) {
4190 Error("missing submodule metadata record at beginning of block");
4191 return true;
4192 }
4193
4194 if (!CurrentModule)
4195 break;
4196
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004197 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004198 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004199 if (!CurrentModule->getUmbrellaDir())
4200 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4201 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4202 Error("mismatched umbrella directories in submodule");
4203 return true;
4204 }
4205 }
4206 break;
4207 }
4208
4209 case SUBMODULE_METADATA: {
4210 if (!First) {
4211 Error("submodule metadata record not at beginning of block");
4212 return true;
4213 }
4214 First = false;
4215
4216 F.BaseSubmoduleID = getTotalNumSubmodules();
4217 F.LocalNumSubmodules = Record[0];
4218 unsigned LocalBaseSubmoduleID = Record[1];
4219 if (F.LocalNumSubmodules > 0) {
4220 // Introduce the global -> local mapping for submodules within this
4221 // module.
4222 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4223
4224 // Introduce the local -> global mapping for submodules within this
4225 // module.
4226 F.SubmoduleRemap.insertOrReplace(
4227 std::make_pair(LocalBaseSubmoduleID,
4228 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4229
4230 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4231 }
4232 break;
4233 }
4234
4235 case SUBMODULE_IMPORTS: {
4236 if (First) {
4237 Error("missing submodule metadata record at beginning of block");
4238 return true;
4239 }
4240
4241 if (!CurrentModule)
4242 break;
4243
4244 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00004245 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004246 Unresolved.File = &F;
4247 Unresolved.Mod = CurrentModule;
4248 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00004249 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004250 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00004251 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004252 }
4253 break;
4254 }
4255
4256 case SUBMODULE_EXPORTS: {
4257 if (First) {
4258 Error("missing submodule metadata record at beginning of block");
4259 return true;
4260 }
4261
4262 if (!CurrentModule)
4263 break;
4264
4265 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00004266 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004267 Unresolved.File = &F;
4268 Unresolved.Mod = CurrentModule;
4269 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00004270 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004271 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00004272 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004273 }
4274
4275 // Once we've loaded the set of exports, there's no reason to keep
4276 // the parsed, unresolved exports around.
4277 CurrentModule->UnresolvedExports.clear();
4278 break;
4279 }
4280 case SUBMODULE_REQUIRES: {
4281 if (First) {
4282 Error("missing submodule metadata record at beginning of block");
4283 return true;
4284 }
4285
4286 if (!CurrentModule)
4287 break;
4288
Richard Smith5794b532013-10-28 22:18:19 +00004289 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004290 Context.getTargetInfo());
4291 break;
4292 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00004293
4294 case SUBMODULE_LINK_LIBRARY:
4295 if (First) {
4296 Error("missing submodule metadata record at beginning of block");
4297 return true;
4298 }
4299
4300 if (!CurrentModule)
4301 break;
4302
4303 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004304 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00004305 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00004306
4307 case SUBMODULE_CONFIG_MACRO:
4308 if (First) {
4309 Error("missing submodule metadata record at beginning of block");
4310 return true;
4311 }
4312
4313 if (!CurrentModule)
4314 break;
4315
4316 CurrentModule->ConfigMacros.push_back(Blob.str());
4317 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00004318
4319 case SUBMODULE_CONFLICT: {
4320 if (First) {
4321 Error("missing submodule metadata record at beginning of block");
4322 return true;
4323 }
4324
4325 if (!CurrentModule)
4326 break;
4327
4328 UnresolvedModuleRef Unresolved;
4329 Unresolved.File = &F;
4330 Unresolved.Mod = CurrentModule;
4331 Unresolved.ID = Record[0];
4332 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4333 Unresolved.IsWildcard = false;
4334 Unresolved.String = Blob;
4335 UnresolvedModuleRefs.push_back(Unresolved);
4336 break;
4337 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004338 }
4339 }
4340}
4341
4342/// \brief Parse the record that corresponds to a LangOptions data
4343/// structure.
4344///
4345/// This routine parses the language options from the AST file and then gives
4346/// them to the AST listener if one is set.
4347///
4348/// \returns true if the listener deems the file unacceptable, false otherwise.
4349bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4350 bool Complain,
4351 ASTReaderListener &Listener) {
4352 LangOptions LangOpts;
4353 unsigned Idx = 0;
4354#define LANGOPT(Name, Bits, Default, Description) \
4355 LangOpts.Name = Record[Idx++];
4356#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4357 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4358#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00004359#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4360#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004361
4362 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4363 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4364 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4365
4366 unsigned Length = Record[Idx++];
4367 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4368 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00004369
4370 Idx += Length;
4371
4372 // Comment options.
4373 for (unsigned N = Record[Idx++]; N; --N) {
4374 LangOpts.CommentOpts.BlockCommandNames.push_back(
4375 ReadString(Record, Idx));
4376 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00004377 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00004378
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004379 return Listener.ReadLanguageOptions(LangOpts, Complain);
4380}
4381
4382bool ASTReader::ParseTargetOptions(const RecordData &Record,
4383 bool Complain,
4384 ASTReaderListener &Listener) {
4385 unsigned Idx = 0;
4386 TargetOptions TargetOpts;
4387 TargetOpts.Triple = ReadString(Record, Idx);
4388 TargetOpts.CPU = ReadString(Record, Idx);
4389 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004390 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4391 for (unsigned N = Record[Idx++]; N; --N) {
4392 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4393 }
4394 for (unsigned N = Record[Idx++]; N; --N) {
4395 TargetOpts.Features.push_back(ReadString(Record, Idx));
4396 }
4397
4398 return Listener.ReadTargetOptions(TargetOpts, Complain);
4399}
4400
4401bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4402 ASTReaderListener &Listener) {
4403 DiagnosticOptions DiagOpts;
4404 unsigned Idx = 0;
4405#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4406#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4407 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4408#include "clang/Basic/DiagnosticOptions.def"
4409
4410 for (unsigned N = Record[Idx++]; N; --N) {
4411 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4412 }
4413
4414 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4415}
4416
4417bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4418 ASTReaderListener &Listener) {
4419 FileSystemOptions FSOpts;
4420 unsigned Idx = 0;
4421 FSOpts.WorkingDir = ReadString(Record, Idx);
4422 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4423}
4424
4425bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4426 bool Complain,
4427 ASTReaderListener &Listener) {
4428 HeaderSearchOptions HSOpts;
4429 unsigned Idx = 0;
4430 HSOpts.Sysroot = ReadString(Record, Idx);
4431
4432 // Include entries.
4433 for (unsigned N = Record[Idx++]; N; --N) {
4434 std::string Path = ReadString(Record, Idx);
4435 frontend::IncludeDirGroup Group
4436 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004437 bool IsFramework = Record[Idx++];
4438 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004439 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00004440 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004441 }
4442
4443 // System header prefixes.
4444 for (unsigned N = Record[Idx++]; N; --N) {
4445 std::string Prefix = ReadString(Record, Idx);
4446 bool IsSystemHeader = Record[Idx++];
4447 HSOpts.SystemHeaderPrefixes.push_back(
4448 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4449 }
4450
4451 HSOpts.ResourceDir = ReadString(Record, Idx);
4452 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Stephen Hines651f13c2014-04-23 16:59:28 -07004453 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004454 HSOpts.DisableModuleHash = Record[Idx++];
4455 HSOpts.UseBuiltinIncludes = Record[Idx++];
4456 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4457 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4458 HSOpts.UseLibcxx = Record[Idx++];
4459
4460 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4461}
4462
4463bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4464 bool Complain,
4465 ASTReaderListener &Listener,
4466 std::string &SuggestedPredefines) {
4467 PreprocessorOptions PPOpts;
4468 unsigned Idx = 0;
4469
4470 // Macro definitions/undefs
4471 for (unsigned N = Record[Idx++]; N; --N) {
4472 std::string Macro = ReadString(Record, Idx);
4473 bool IsUndef = Record[Idx++];
4474 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4475 }
4476
4477 // Includes
4478 for (unsigned N = Record[Idx++]; N; --N) {
4479 PPOpts.Includes.push_back(ReadString(Record, Idx));
4480 }
4481
4482 // Macro Includes
4483 for (unsigned N = Record[Idx++]; N; --N) {
4484 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4485 }
4486
4487 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00004488 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004489 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4490 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4491 PPOpts.ObjCXXARCStandardLibrary =
4492 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4493 SuggestedPredefines.clear();
4494 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4495 SuggestedPredefines);
4496}
4497
4498std::pair<ModuleFile *, unsigned>
4499ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4500 GlobalPreprocessedEntityMapType::iterator
4501 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4502 assert(I != GlobalPreprocessedEntityMap.end() &&
4503 "Corrupted global preprocessed entity map");
4504 ModuleFile *M = I->second;
4505 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4506 return std::make_pair(M, LocalIndex);
4507}
4508
4509std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4510ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4511 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4512 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4513 Mod.NumPreprocessedEntities);
4514
4515 return std::make_pair(PreprocessingRecord::iterator(),
4516 PreprocessingRecord::iterator());
4517}
4518
4519std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4520ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4521 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4522 ModuleDeclIterator(this, &Mod,
4523 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4524}
4525
4526PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4527 PreprocessedEntityID PPID = Index+1;
4528 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4529 ModuleFile &M = *PPInfo.first;
4530 unsigned LocalIndex = PPInfo.second;
4531 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4532
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004533 if (!PP.getPreprocessingRecord()) {
4534 Error("no preprocessing record");
4535 return 0;
4536 }
4537
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004538 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4539 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4540
4541 llvm::BitstreamEntry Entry =
4542 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4543 if (Entry.Kind != llvm::BitstreamEntry::Record)
4544 return 0;
4545
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004546 // Read the record.
4547 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4548 ReadSourceLocation(M, PPOffs.End));
4549 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004550 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004551 RecordData Record;
4552 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004553 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4554 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004555 switch (RecType) {
4556 case PPD_MACRO_EXPANSION: {
4557 bool isBuiltin = Record[0];
4558 IdentifierInfo *Name = 0;
4559 MacroDefinition *Def = 0;
4560 if (isBuiltin)
4561 Name = getLocalIdentifier(M, Record[1]);
4562 else {
4563 PreprocessedEntityID
4564 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4565 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4566 }
4567
4568 MacroExpansion *ME;
4569 if (isBuiltin)
4570 ME = new (PPRec) MacroExpansion(Name, Range);
4571 else
4572 ME = new (PPRec) MacroExpansion(Def, Range);
4573
4574 return ME;
4575 }
4576
4577 case PPD_MACRO_DEFINITION: {
4578 // Decode the identifier info and then check again; if the macro is
4579 // still defined and associated with the identifier,
4580 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4581 MacroDefinition *MD
4582 = new (PPRec) MacroDefinition(II, Range);
4583
4584 if (DeserializationListener)
4585 DeserializationListener->MacroDefinitionRead(PPID, MD);
4586
4587 return MD;
4588 }
4589
4590 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004591 const char *FullFileNameStart = Blob.data() + Record[0];
4592 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004593 const FileEntry *File = 0;
4594 if (!FullFileName.empty())
4595 File = PP.getFileManager().getFile(FullFileName);
4596
4597 // FIXME: Stable encoding
4598 InclusionDirective::InclusionKind Kind
4599 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4600 InclusionDirective *ID
4601 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004602 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004603 Record[1], Record[3],
4604 File,
4605 Range);
4606 return ID;
4607 }
4608 }
4609
4610 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4611}
4612
4613/// \brief \arg SLocMapI points at a chunk of a module that contains no
4614/// preprocessed entities or the entities it contains are not the ones we are
4615/// looking for. Find the next module that contains entities and return the ID
4616/// of the first entry.
4617PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4618 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4619 ++SLocMapI;
4620 for (GlobalSLocOffsetMapType::const_iterator
4621 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4622 ModuleFile &M = *SLocMapI->second;
4623 if (M.NumPreprocessedEntities)
4624 return M.BasePreprocessedEntityID;
4625 }
4626
4627 return getTotalNumPreprocessedEntities();
4628}
4629
4630namespace {
4631
4632template <unsigned PPEntityOffset::*PPLoc>
4633struct PPEntityComp {
4634 const ASTReader &Reader;
4635 ModuleFile &M;
4636
4637 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4638
4639 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4640 SourceLocation LHS = getLoc(L);
4641 SourceLocation RHS = getLoc(R);
4642 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4643 }
4644
4645 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4646 SourceLocation LHS = getLoc(L);
4647 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4648 }
4649
4650 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4651 SourceLocation RHS = getLoc(R);
4652 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4653 }
4654
4655 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4656 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4657 }
4658};
4659
4660}
4661
4662/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4663PreprocessedEntityID
4664ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4665 if (SourceMgr.isLocalSourceLocation(BLoc))
4666 return getTotalNumPreprocessedEntities();
4667
4668 GlobalSLocOffsetMapType::const_iterator
4669 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004670 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004671 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4672 "Corrupted global sloc offset map");
4673
4674 if (SLocMapI->second->NumPreprocessedEntities == 0)
4675 return findNextPreprocessedEntity(SLocMapI);
4676
4677 ModuleFile &M = *SLocMapI->second;
4678 typedef const PPEntityOffset *pp_iterator;
4679 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4680 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4681
4682 size_t Count = M.NumPreprocessedEntities;
4683 size_t Half;
4684 pp_iterator First = pp_begin;
4685 pp_iterator PPI;
4686
4687 // Do a binary search manually instead of using std::lower_bound because
4688 // The end locations of entities may be unordered (when a macro expansion
4689 // is inside another macro argument), but for this case it is not important
4690 // whether we get the first macro expansion or its containing macro.
4691 while (Count > 0) {
4692 Half = Count/2;
4693 PPI = First;
4694 std::advance(PPI, Half);
4695 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4696 BLoc)){
4697 First = PPI;
4698 ++First;
4699 Count = Count - Half - 1;
4700 } else
4701 Count = Half;
4702 }
4703
4704 if (PPI == pp_end)
4705 return findNextPreprocessedEntity(SLocMapI);
4706
4707 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4708}
4709
4710/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4711PreprocessedEntityID
4712ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4713 if (SourceMgr.isLocalSourceLocation(ELoc))
4714 return getTotalNumPreprocessedEntities();
4715
4716 GlobalSLocOffsetMapType::const_iterator
4717 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004718 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004719 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4720 "Corrupted global sloc offset map");
4721
4722 if (SLocMapI->second->NumPreprocessedEntities == 0)
4723 return findNextPreprocessedEntity(SLocMapI);
4724
4725 ModuleFile &M = *SLocMapI->second;
4726 typedef const PPEntityOffset *pp_iterator;
4727 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4728 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4729 pp_iterator PPI =
4730 std::upper_bound(pp_begin, pp_end, ELoc,
4731 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4732
4733 if (PPI == pp_end)
4734 return findNextPreprocessedEntity(SLocMapI);
4735
4736 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4737}
4738
4739/// \brief Returns a pair of [Begin, End) indices of preallocated
4740/// preprocessed entities that \arg Range encompasses.
4741std::pair<unsigned, unsigned>
4742 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4743 if (Range.isInvalid())
4744 return std::make_pair(0,0);
4745 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4746
4747 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4748 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4749 return std::make_pair(BeginID, EndID);
4750}
4751
4752/// \brief Optionally returns true or false if the preallocated preprocessed
4753/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004754Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004755 FileID FID) {
4756 if (FID.isInvalid())
4757 return false;
4758
4759 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4760 ModuleFile &M = *PPInfo.first;
4761 unsigned LocalIndex = PPInfo.second;
4762 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4763
4764 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4765 if (Loc.isInvalid())
4766 return false;
4767
4768 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4769 return true;
4770 else
4771 return false;
4772}
4773
4774namespace {
4775 /// \brief Visitor used to search for information about a header file.
4776 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004777 const FileEntry *FE;
4778
David Blaikiedc84cd52013-02-20 22:23:23 +00004779 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004780
4781 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004782 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4783 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004784
4785 static bool visit(ModuleFile &M, void *UserData) {
4786 HeaderFileInfoVisitor *This
4787 = static_cast<HeaderFileInfoVisitor *>(UserData);
4788
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004789 HeaderFileInfoLookupTable *Table
4790 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4791 if (!Table)
4792 return false;
4793
4794 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004795 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004796 if (Pos == Table->end())
4797 return false;
4798
4799 This->HFI = *Pos;
4800 return true;
4801 }
4802
David Blaikiedc84cd52013-02-20 22:23:23 +00004803 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004804 };
4805}
4806
4807HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004808 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004809 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +00004810 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004811 return *HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004812
4813 return HeaderFileInfo();
4814}
4815
4816void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4817 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004818 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004819 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4820 ModuleFile &F = *(*I);
4821 unsigned Idx = 0;
4822 DiagStates.clear();
4823 assert(!Diag.DiagStates.empty());
4824 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4825 while (Idx < F.PragmaDiagMappings.size()) {
4826 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4827 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4828 if (DiagStateID != 0) {
4829 Diag.DiagStatePoints.push_back(
4830 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4831 FullSourceLoc(Loc, SourceMgr)));
4832 continue;
4833 }
4834
4835 assert(DiagStateID == 0);
4836 // A new DiagState was created here.
4837 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4838 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4839 DiagStates.push_back(NewState);
4840 Diag.DiagStatePoints.push_back(
4841 DiagnosticsEngine::DiagStatePoint(NewState,
4842 FullSourceLoc(Loc, SourceMgr)));
4843 while (1) {
4844 assert(Idx < F.PragmaDiagMappings.size() &&
4845 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4846 if (Idx >= F.PragmaDiagMappings.size()) {
4847 break; // Something is messed up but at least avoid infinite loop in
4848 // release build.
4849 }
4850 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4851 if (DiagID == (unsigned)-1) {
4852 break; // no more diag/map pairs for this location.
4853 }
4854 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4855 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4856 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4857 }
4858 }
4859 }
4860}
4861
4862/// \brief Get the correct cursor and offset for loading a type.
4863ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4864 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4865 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4866 ModuleFile *M = I->second;
4867 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4868}
4869
4870/// \brief Read and return the type with the given index..
4871///
4872/// The index is the type ID, shifted and minus the number of predefs. This
4873/// routine actually reads the record corresponding to the type at the given
4874/// location. It is a helper routine for GetType, which deals with reading type
4875/// IDs.
4876QualType ASTReader::readTypeRecord(unsigned Index) {
4877 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004878 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004879
4880 // Keep track of where we are in the stream, then jump back there
4881 // after reading this type.
4882 SavedStreamPosition SavedPosition(DeclsCursor);
4883
4884 ReadingKindTracker ReadingKind(Read_Type, *this);
4885
4886 // Note that we are loading a type record.
4887 Deserializing AType(this);
4888
4889 unsigned Idx = 0;
4890 DeclsCursor.JumpToBit(Loc.Offset);
4891 RecordData Record;
4892 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004893 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004894 case TYPE_EXT_QUAL: {
4895 if (Record.size() != 2) {
4896 Error("Incorrect encoding of extended qualifier type");
4897 return QualType();
4898 }
4899 QualType Base = readType(*Loc.F, Record, Idx);
4900 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4901 return Context.getQualifiedType(Base, Quals);
4902 }
4903
4904 case TYPE_COMPLEX: {
4905 if (Record.size() != 1) {
4906 Error("Incorrect encoding of complex type");
4907 return QualType();
4908 }
4909 QualType ElemType = readType(*Loc.F, Record, Idx);
4910 return Context.getComplexType(ElemType);
4911 }
4912
4913 case TYPE_POINTER: {
4914 if (Record.size() != 1) {
4915 Error("Incorrect encoding of pointer type");
4916 return QualType();
4917 }
4918 QualType PointeeType = readType(*Loc.F, Record, Idx);
4919 return Context.getPointerType(PointeeType);
4920 }
4921
Reid Kleckner12df2462013-06-24 17:51:48 +00004922 case TYPE_DECAYED: {
4923 if (Record.size() != 1) {
4924 Error("Incorrect encoding of decayed type");
4925 return QualType();
4926 }
4927 QualType OriginalType = readType(*Loc.F, Record, Idx);
4928 QualType DT = Context.getAdjustedParameterType(OriginalType);
4929 if (!isa<DecayedType>(DT))
4930 Error("Decayed type does not decay");
4931 return DT;
4932 }
4933
Stephen Hines651f13c2014-04-23 16:59:28 -07004934 case TYPE_ADJUSTED: {
4935 if (Record.size() != 2) {
4936 Error("Incorrect encoding of adjusted type");
4937 return QualType();
4938 }
4939 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4940 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4941 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4942 }
4943
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004944 case TYPE_BLOCK_POINTER: {
4945 if (Record.size() != 1) {
4946 Error("Incorrect encoding of block pointer type");
4947 return QualType();
4948 }
4949 QualType PointeeType = readType(*Loc.F, Record, Idx);
4950 return Context.getBlockPointerType(PointeeType);
4951 }
4952
4953 case TYPE_LVALUE_REFERENCE: {
4954 if (Record.size() != 2) {
4955 Error("Incorrect encoding of lvalue reference type");
4956 return QualType();
4957 }
4958 QualType PointeeType = readType(*Loc.F, Record, Idx);
4959 return Context.getLValueReferenceType(PointeeType, Record[1]);
4960 }
4961
4962 case TYPE_RVALUE_REFERENCE: {
4963 if (Record.size() != 1) {
4964 Error("Incorrect encoding of rvalue reference type");
4965 return QualType();
4966 }
4967 QualType PointeeType = readType(*Loc.F, Record, Idx);
4968 return Context.getRValueReferenceType(PointeeType);
4969 }
4970
4971 case TYPE_MEMBER_POINTER: {
4972 if (Record.size() != 2) {
4973 Error("Incorrect encoding of member pointer type");
4974 return QualType();
4975 }
4976 QualType PointeeType = readType(*Loc.F, Record, Idx);
4977 QualType ClassType = readType(*Loc.F, Record, Idx);
4978 if (PointeeType.isNull() || ClassType.isNull())
4979 return QualType();
4980
4981 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4982 }
4983
4984 case TYPE_CONSTANT_ARRAY: {
4985 QualType ElementType = readType(*Loc.F, Record, Idx);
4986 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4987 unsigned IndexTypeQuals = Record[2];
4988 unsigned Idx = 3;
4989 llvm::APInt Size = ReadAPInt(Record, Idx);
4990 return Context.getConstantArrayType(ElementType, Size,
4991 ASM, IndexTypeQuals);
4992 }
4993
4994 case TYPE_INCOMPLETE_ARRAY: {
4995 QualType ElementType = readType(*Loc.F, Record, Idx);
4996 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4997 unsigned IndexTypeQuals = Record[2];
4998 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4999 }
5000
5001 case TYPE_VARIABLE_ARRAY: {
5002 QualType ElementType = readType(*Loc.F, Record, Idx);
5003 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5004 unsigned IndexTypeQuals = Record[2];
5005 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5006 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5007 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5008 ASM, IndexTypeQuals,
5009 SourceRange(LBLoc, RBLoc));
5010 }
5011
5012 case TYPE_VECTOR: {
5013 if (Record.size() != 3) {
5014 Error("incorrect encoding of vector type in AST file");
5015 return QualType();
5016 }
5017
5018 QualType ElementType = readType(*Loc.F, Record, Idx);
5019 unsigned NumElements = Record[1];
5020 unsigned VecKind = Record[2];
5021 return Context.getVectorType(ElementType, NumElements,
5022 (VectorType::VectorKind)VecKind);
5023 }
5024
5025 case TYPE_EXT_VECTOR: {
5026 if (Record.size() != 3) {
5027 Error("incorrect encoding of extended vector type in AST file");
5028 return QualType();
5029 }
5030
5031 QualType ElementType = readType(*Loc.F, Record, Idx);
5032 unsigned NumElements = Record[1];
5033 return Context.getExtVectorType(ElementType, NumElements);
5034 }
5035
5036 case TYPE_FUNCTION_NO_PROTO: {
5037 if (Record.size() != 6) {
5038 Error("incorrect encoding of no-proto function type");
5039 return QualType();
5040 }
5041 QualType ResultType = readType(*Loc.F, Record, Idx);
5042 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5043 (CallingConv)Record[4], Record[5]);
5044 return Context.getFunctionNoProtoType(ResultType, Info);
5045 }
5046
5047 case TYPE_FUNCTION_PROTO: {
5048 QualType ResultType = readType(*Loc.F, Record, Idx);
5049
5050 FunctionProtoType::ExtProtoInfo EPI;
5051 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5052 /*hasregparm*/ Record[2],
5053 /*regparm*/ Record[3],
5054 static_cast<CallingConv>(Record[4]),
5055 /*produces*/ Record[5]);
5056
5057 unsigned Idx = 6;
5058 unsigned NumParams = Record[Idx++];
5059 SmallVector<QualType, 16> ParamTypes;
5060 for (unsigned I = 0; I != NumParams; ++I)
5061 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5062
5063 EPI.Variadic = Record[Idx++];
5064 EPI.HasTrailingReturn = Record[Idx++];
5065 EPI.TypeQuals = Record[Idx++];
5066 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Stephen Hines651f13c2014-04-23 16:59:28 -07005067 SmallVector<QualType, 8> ExceptionStorage;
5068 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rosebea522f2013-03-08 21:51:21 +00005069 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005070 }
5071
5072 case TYPE_UNRESOLVED_USING: {
5073 unsigned Idx = 0;
5074 return Context.getTypeDeclType(
5075 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5076 }
5077
5078 case TYPE_TYPEDEF: {
5079 if (Record.size() != 2) {
5080 Error("incorrect encoding of typedef type");
5081 return QualType();
5082 }
5083 unsigned Idx = 0;
5084 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5085 QualType Canonical = readType(*Loc.F, Record, Idx);
5086 if (!Canonical.isNull())
5087 Canonical = Context.getCanonicalType(Canonical);
5088 return Context.getTypedefType(Decl, Canonical);
5089 }
5090
5091 case TYPE_TYPEOF_EXPR:
5092 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5093
5094 case TYPE_TYPEOF: {
5095 if (Record.size() != 1) {
5096 Error("incorrect encoding of typeof(type) in AST file");
5097 return QualType();
5098 }
5099 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5100 return Context.getTypeOfType(UnderlyingType);
5101 }
5102
5103 case TYPE_DECLTYPE: {
5104 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5105 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5106 }
5107
5108 case TYPE_UNARY_TRANSFORM: {
5109 QualType BaseType = readType(*Loc.F, Record, Idx);
5110 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5111 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5112 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5113 }
5114
Richard Smitha2c36462013-04-26 16:15:35 +00005115 case TYPE_AUTO: {
5116 QualType Deduced = readType(*Loc.F, Record, Idx);
5117 bool IsDecltypeAuto = Record[Idx++];
Richard Smithdc7a4f52013-04-30 13:56:41 +00005118 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek152b4e42013-08-22 12:12:24 +00005119 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smitha2c36462013-04-26 16:15:35 +00005120 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005121
5122 case TYPE_RECORD: {
5123 if (Record.size() != 2) {
5124 Error("incorrect encoding of record type");
5125 return QualType();
5126 }
5127 unsigned Idx = 0;
5128 bool IsDependent = Record[Idx++];
5129 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5130 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5131 QualType T = Context.getRecordType(RD);
5132 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5133 return T;
5134 }
5135
5136 case TYPE_ENUM: {
5137 if (Record.size() != 2) {
5138 Error("incorrect encoding of enum type");
5139 return QualType();
5140 }
5141 unsigned Idx = 0;
5142 bool IsDependent = Record[Idx++];
5143 QualType T
5144 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5145 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5146 return T;
5147 }
5148
5149 case TYPE_ATTRIBUTED: {
5150 if (Record.size() != 3) {
5151 Error("incorrect encoding of attributed type");
5152 return QualType();
5153 }
5154 QualType modifiedType = readType(*Loc.F, Record, Idx);
5155 QualType equivalentType = readType(*Loc.F, Record, Idx);
5156 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5157 return Context.getAttributedType(kind, modifiedType, equivalentType);
5158 }
5159
5160 case TYPE_PAREN: {
5161 if (Record.size() != 1) {
5162 Error("incorrect encoding of paren type");
5163 return QualType();
5164 }
5165 QualType InnerType = readType(*Loc.F, Record, Idx);
5166 return Context.getParenType(InnerType);
5167 }
5168
5169 case TYPE_PACK_EXPANSION: {
5170 if (Record.size() != 2) {
5171 Error("incorrect encoding of pack expansion type");
5172 return QualType();
5173 }
5174 QualType Pattern = readType(*Loc.F, Record, Idx);
5175 if (Pattern.isNull())
5176 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00005177 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005178 if (Record[1])
5179 NumExpansions = Record[1] - 1;
5180 return Context.getPackExpansionType(Pattern, NumExpansions);
5181 }
5182
5183 case TYPE_ELABORATED: {
5184 unsigned Idx = 0;
5185 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5186 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5187 QualType NamedType = readType(*Loc.F, Record, Idx);
5188 return Context.getElaboratedType(Keyword, NNS, NamedType);
5189 }
5190
5191 case TYPE_OBJC_INTERFACE: {
5192 unsigned Idx = 0;
5193 ObjCInterfaceDecl *ItfD
5194 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5195 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5196 }
5197
5198 case TYPE_OBJC_OBJECT: {
5199 unsigned Idx = 0;
5200 QualType Base = readType(*Loc.F, Record, Idx);
5201 unsigned NumProtos = Record[Idx++];
5202 SmallVector<ObjCProtocolDecl*, 4> Protos;
5203 for (unsigned I = 0; I != NumProtos; ++I)
5204 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5205 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5206 }
5207
5208 case TYPE_OBJC_OBJECT_POINTER: {
5209 unsigned Idx = 0;
5210 QualType Pointee = readType(*Loc.F, Record, Idx);
5211 return Context.getObjCObjectPointerType(Pointee);
5212 }
5213
5214 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5215 unsigned Idx = 0;
5216 QualType Parm = readType(*Loc.F, Record, Idx);
5217 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephen Hines651f13c2014-04-23 16:59:28 -07005218 return Context.getSubstTemplateTypeParmType(
5219 cast<TemplateTypeParmType>(Parm),
5220 Context.getCanonicalType(Replacement));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005221 }
5222
5223 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5224 unsigned Idx = 0;
5225 QualType Parm = readType(*Loc.F, Record, Idx);
5226 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5227 return Context.getSubstTemplateTypeParmPackType(
5228 cast<TemplateTypeParmType>(Parm),
5229 ArgPack);
5230 }
5231
5232 case TYPE_INJECTED_CLASS_NAME: {
5233 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5234 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5235 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5236 // for AST reading, too much interdependencies.
5237 return
5238 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5239 }
5240
5241 case TYPE_TEMPLATE_TYPE_PARM: {
5242 unsigned Idx = 0;
5243 unsigned Depth = Record[Idx++];
5244 unsigned Index = Record[Idx++];
5245 bool Pack = Record[Idx++];
5246 TemplateTypeParmDecl *D
5247 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5248 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5249 }
5250
5251 case TYPE_DEPENDENT_NAME: {
5252 unsigned Idx = 0;
5253 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5254 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5255 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5256 QualType Canon = readType(*Loc.F, Record, Idx);
5257 if (!Canon.isNull())
5258 Canon = Context.getCanonicalType(Canon);
5259 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5260 }
5261
5262 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5263 unsigned Idx = 0;
5264 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5265 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5266 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5267 unsigned NumArgs = Record[Idx++];
5268 SmallVector<TemplateArgument, 8> Args;
5269 Args.reserve(NumArgs);
5270 while (NumArgs--)
5271 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5272 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5273 Args.size(), Args.data());
5274 }
5275
5276 case TYPE_DEPENDENT_SIZED_ARRAY: {
5277 unsigned Idx = 0;
5278
5279 // ArrayType
5280 QualType ElementType = readType(*Loc.F, Record, Idx);
5281 ArrayType::ArraySizeModifier ASM
5282 = (ArrayType::ArraySizeModifier)Record[Idx++];
5283 unsigned IndexTypeQuals = Record[Idx++];
5284
5285 // DependentSizedArrayType
5286 Expr *NumElts = ReadExpr(*Loc.F);
5287 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5288
5289 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5290 IndexTypeQuals, Brackets);
5291 }
5292
5293 case TYPE_TEMPLATE_SPECIALIZATION: {
5294 unsigned Idx = 0;
5295 bool IsDependent = Record[Idx++];
5296 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5297 SmallVector<TemplateArgument, 8> Args;
5298 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5299 QualType Underlying = readType(*Loc.F, Record, Idx);
5300 QualType T;
5301 if (Underlying.isNull())
5302 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5303 Args.size());
5304 else
5305 T = Context.getTemplateSpecializationType(Name, Args.data(),
5306 Args.size(), Underlying);
5307 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5308 return T;
5309 }
5310
5311 case TYPE_ATOMIC: {
5312 if (Record.size() != 1) {
5313 Error("Incorrect encoding of atomic type");
5314 return QualType();
5315 }
5316 QualType ValueType = readType(*Loc.F, Record, Idx);
5317 return Context.getAtomicType(ValueType);
5318 }
5319 }
5320 llvm_unreachable("Invalid TypeCode!");
5321}
5322
Stephen Hines651f13c2014-04-23 16:59:28 -07005323void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5324 SmallVectorImpl<QualType> &Exceptions,
5325 FunctionProtoType::ExtProtoInfo &EPI,
5326 const RecordData &Record, unsigned &Idx) {
5327 ExceptionSpecificationType EST =
5328 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5329 EPI.ExceptionSpecType = EST;
5330 if (EST == EST_Dynamic) {
5331 EPI.NumExceptions = Record[Idx++];
5332 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5333 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5334 EPI.Exceptions = Exceptions.data();
5335 } else if (EST == EST_ComputedNoexcept) {
5336 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5337 } else if (EST == EST_Uninstantiated) {
5338 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5339 EPI.ExceptionSpecTemplate =
5340 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5341 } else if (EST == EST_Unevaluated) {
5342 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5343 }
5344}
5345
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005346class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5347 ASTReader &Reader;
5348 ModuleFile &F;
5349 const ASTReader::RecordData &Record;
5350 unsigned &Idx;
5351
5352 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5353 unsigned &I) {
5354 return Reader.ReadSourceLocation(F, R, I);
5355 }
5356
5357 template<typename T>
5358 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5359 return Reader.ReadDeclAs<T>(F, Record, Idx);
5360 }
5361
5362public:
5363 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5364 const ASTReader::RecordData &Record, unsigned &Idx)
5365 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5366 { }
5367
5368 // We want compile-time assurance that we've enumerated all of
5369 // these, so unfortunately we have to declare them first, then
5370 // define them out-of-line.
5371#define ABSTRACT_TYPELOC(CLASS, PARENT)
5372#define TYPELOC(CLASS, PARENT) \
5373 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5374#include "clang/AST/TypeLocNodes.def"
5375
5376 void VisitFunctionTypeLoc(FunctionTypeLoc);
5377 void VisitArrayTypeLoc(ArrayTypeLoc);
5378};
5379
5380void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5381 // nothing to do
5382}
5383void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5384 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5385 if (TL.needsExtraLocalData()) {
5386 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5387 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5388 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5389 TL.setModeAttr(Record[Idx++]);
5390 }
5391}
5392void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5393 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5394}
5395void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5396 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5397}
Reid Kleckner12df2462013-06-24 17:51:48 +00005398void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5399 // nothing to do
5400}
Stephen Hines651f13c2014-04-23 16:59:28 -07005401void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5402 // nothing to do
5403}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005404void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5405 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5406}
5407void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5408 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5409}
5410void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5411 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5412}
5413void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5414 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5415 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5416}
5417void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5418 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5419 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5420 if (Record[Idx++])
5421 TL.setSizeExpr(Reader.ReadExpr(F));
5422 else
5423 TL.setSizeExpr(0);
5424}
5425void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5426 VisitArrayTypeLoc(TL);
5427}
5428void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5429 VisitArrayTypeLoc(TL);
5430}
5431void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5432 VisitArrayTypeLoc(TL);
5433}
5434void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5435 DependentSizedArrayTypeLoc TL) {
5436 VisitArrayTypeLoc(TL);
5437}
5438void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5439 DependentSizedExtVectorTypeLoc TL) {
5440 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5441}
5442void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5443 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5444}
5445void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5446 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5447}
5448void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5449 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5450 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5451 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5452 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Stephen Hines651f13c2014-04-23 16:59:28 -07005453 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5454 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005455 }
5456}
5457void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5458 VisitFunctionTypeLoc(TL);
5459}
5460void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5461 VisitFunctionTypeLoc(TL);
5462}
5463void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5464 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5465}
5466void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5467 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5468}
5469void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5470 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5471 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5472 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5473}
5474void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5475 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5476 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5477 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5478 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5479}
5480void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5481 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5482}
5483void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5484 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5485 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5486 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5487 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5488}
5489void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5490 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5491}
5492void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5493 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5494}
5495void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5496 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5497}
5498void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5499 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5500 if (TL.hasAttrOperand()) {
5501 SourceRange range;
5502 range.setBegin(ReadSourceLocation(Record, Idx));
5503 range.setEnd(ReadSourceLocation(Record, Idx));
5504 TL.setAttrOperandParensRange(range);
5505 }
5506 if (TL.hasAttrExprOperand()) {
5507 if (Record[Idx++])
5508 TL.setAttrExprOperand(Reader.ReadExpr(F));
5509 else
5510 TL.setAttrExprOperand(0);
5511 } else if (TL.hasAttrEnumOperand())
5512 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5513}
5514void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5515 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5516}
5517void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5518 SubstTemplateTypeParmTypeLoc TL) {
5519 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5520}
5521void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5522 SubstTemplateTypeParmPackTypeLoc TL) {
5523 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5524}
5525void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5526 TemplateSpecializationTypeLoc TL) {
5527 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5528 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5529 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5530 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5531 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5532 TL.setArgLocInfo(i,
5533 Reader.GetTemplateArgumentLocInfo(F,
5534 TL.getTypePtr()->getArg(i).getKind(),
5535 Record, Idx));
5536}
5537void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5538 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5539 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5540}
5541void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5542 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5543 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5544}
5545void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5546 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5549 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5550 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5551 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5552}
5553void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5554 DependentTemplateSpecializationTypeLoc TL) {
5555 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5556 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5557 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5558 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5559 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5560 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5561 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5562 TL.setArgLocInfo(I,
5563 Reader.GetTemplateArgumentLocInfo(F,
5564 TL.getTypePtr()->getArg(I).getKind(),
5565 Record, Idx));
5566}
5567void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5568 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5569}
5570void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5571 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5574 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5575 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5576 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5577 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5578 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5581 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5582}
5583void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5584 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5585 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5586 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5587}
5588
5589TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5590 const RecordData &Record,
5591 unsigned &Idx) {
5592 QualType InfoTy = readType(F, Record, Idx);
5593 if (InfoTy.isNull())
5594 return 0;
5595
5596 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5597 TypeLocReader TLR(*this, F, Record, Idx);
5598 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5599 TLR.Visit(TL);
5600 return TInfo;
5601}
5602
5603QualType ASTReader::GetType(TypeID ID) {
5604 unsigned FastQuals = ID & Qualifiers::FastMask;
5605 unsigned Index = ID >> Qualifiers::FastWidth;
5606
5607 if (Index < NUM_PREDEF_TYPE_IDS) {
5608 QualType T;
5609 switch ((PredefinedTypeIDs)Index) {
5610 case PREDEF_TYPE_NULL_ID: return QualType();
5611 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5612 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5613
5614 case PREDEF_TYPE_CHAR_U_ID:
5615 case PREDEF_TYPE_CHAR_S_ID:
5616 // FIXME: Check that the signedness of CharTy is correct!
5617 T = Context.CharTy;
5618 break;
5619
5620 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5621 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5622 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5623 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5624 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5625 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5626 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5627 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5628 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5629 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5630 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5631 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5632 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5633 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5634 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5635 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5636 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5637 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5638 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5639 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5640 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5641 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5642 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5643 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5644 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5645 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5646 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5647 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005648 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5649 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5650 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5651 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5652 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5653 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005654 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005655 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005656 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5657
5658 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5659 T = Context.getAutoRRefDeductType();
5660 break;
5661
5662 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5663 T = Context.ARCUnbridgedCastTy;
5664 break;
5665
5666 case PREDEF_TYPE_VA_LIST_TAG:
5667 T = Context.getVaListTagType();
5668 break;
5669
5670 case PREDEF_TYPE_BUILTIN_FN:
5671 T = Context.BuiltinFnTy;
5672 break;
5673 }
5674
5675 assert(!T.isNull() && "Unknown predefined type");
5676 return T.withFastQualifiers(FastQuals);
5677 }
5678
5679 Index -= NUM_PREDEF_TYPE_IDS;
5680 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5681 if (TypesLoaded[Index].isNull()) {
5682 TypesLoaded[Index] = readTypeRecord(Index);
5683 if (TypesLoaded[Index].isNull())
5684 return QualType();
5685
5686 TypesLoaded[Index]->setFromAST();
5687 if (DeserializationListener)
5688 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5689 TypesLoaded[Index]);
5690 }
5691
5692 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5693}
5694
5695QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5696 return GetType(getGlobalTypeID(F, LocalID));
5697}
5698
5699serialization::TypeID
5700ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5701 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5702 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5703
5704 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5705 return LocalID;
5706
5707 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5708 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5709 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5710
5711 unsigned GlobalIndex = LocalIndex + I->second;
5712 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5713}
5714
5715TemplateArgumentLocInfo
5716ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5717 TemplateArgument::ArgKind Kind,
5718 const RecordData &Record,
5719 unsigned &Index) {
5720 switch (Kind) {
5721 case TemplateArgument::Expression:
5722 return ReadExpr(F);
5723 case TemplateArgument::Type:
5724 return GetTypeSourceInfo(F, Record, Index);
5725 case TemplateArgument::Template: {
5726 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5727 Index);
5728 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5729 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5730 SourceLocation());
5731 }
5732 case TemplateArgument::TemplateExpansion: {
5733 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5734 Index);
5735 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5736 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5737 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5738 EllipsisLoc);
5739 }
5740 case TemplateArgument::Null:
5741 case TemplateArgument::Integral:
5742 case TemplateArgument::Declaration:
5743 case TemplateArgument::NullPtr:
5744 case TemplateArgument::Pack:
5745 // FIXME: Is this right?
5746 return TemplateArgumentLocInfo();
5747 }
5748 llvm_unreachable("unexpected template argument loc");
5749}
5750
5751TemplateArgumentLoc
5752ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5753 const RecordData &Record, unsigned &Index) {
5754 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5755
5756 if (Arg.getKind() == TemplateArgument::Expression) {
5757 if (Record[Index++]) // bool InfoHasSameExpr.
5758 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5759 }
5760 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5761 Record, Index));
5762}
5763
Enea Zaffanellac1cef082013-08-10 07:24:53 +00005764const ASTTemplateArgumentListInfo*
5765ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5766 const RecordData &Record,
5767 unsigned &Index) {
5768 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5769 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5770 unsigned NumArgsAsWritten = Record[Index++];
5771 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5772 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5773 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5774 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5775}
5776
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005777Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5778 return GetDecl(ID);
5779}
5780
5781uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5782 unsigned &Idx){
5783 if (Idx >= Record.size())
5784 return 0;
5785
5786 unsigned LocalID = Record[Idx++];
5787 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5788}
5789
5790CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5791 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005792 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005793 SavedStreamPosition SavedPosition(Cursor);
5794 Cursor.JumpToBit(Loc.Offset);
5795 ReadingKindTracker ReadingKind(Read_Decl, *this);
5796 RecordData Record;
5797 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005798 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005799 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5800 Error("Malformed AST file: missing C++ base specifiers");
5801 return 0;
5802 }
5803
5804 unsigned Idx = 0;
5805 unsigned NumBases = Record[Idx++];
5806 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5807 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5808 for (unsigned I = 0; I != NumBases; ++I)
5809 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5810 return Bases;
5811}
5812
5813serialization::DeclID
5814ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5815 if (LocalID < NUM_PREDEF_DECL_IDS)
5816 return LocalID;
5817
5818 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5819 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5820 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5821
5822 return LocalID + I->second;
5823}
5824
5825bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5826 ModuleFile &M) const {
5827 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5828 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5829 return &M == I->second;
5830}
5831
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005832ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005833 if (!D->isFromASTFile())
5834 return 0;
5835 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5836 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5837 return I->second;
5838}
5839
5840SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5841 if (ID < NUM_PREDEF_DECL_IDS)
5842 return SourceLocation();
5843
5844 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5845
5846 if (Index > DeclsLoaded.size()) {
5847 Error("declaration ID out-of-range for AST file");
5848 return SourceLocation();
5849 }
5850
5851 if (Decl *D = DeclsLoaded[Index])
5852 return D->getLocation();
5853
5854 unsigned RawLocation = 0;
5855 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5856 return ReadSourceLocation(*Rec.F, RawLocation);
5857}
5858
5859Decl *ASTReader::GetDecl(DeclID ID) {
5860 if (ID < NUM_PREDEF_DECL_IDS) {
5861 switch ((PredefinedDeclIDs)ID) {
5862 case PREDEF_DECL_NULL_ID:
5863 return 0;
5864
5865 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5866 return Context.getTranslationUnitDecl();
5867
5868 case PREDEF_DECL_OBJC_ID_ID:
5869 return Context.getObjCIdDecl();
5870
5871 case PREDEF_DECL_OBJC_SEL_ID:
5872 return Context.getObjCSelDecl();
5873
5874 case PREDEF_DECL_OBJC_CLASS_ID:
5875 return Context.getObjCClassDecl();
5876
5877 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5878 return Context.getObjCProtocolDecl();
5879
5880 case PREDEF_DECL_INT_128_ID:
5881 return Context.getInt128Decl();
5882
5883 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5884 return Context.getUInt128Decl();
5885
5886 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5887 return Context.getObjCInstanceTypeDecl();
5888
5889 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5890 return Context.getBuiltinVaListDecl();
5891 }
5892 }
5893
5894 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5895
5896 if (Index >= DeclsLoaded.size()) {
5897 assert(0 && "declaration ID out-of-range for AST file");
5898 Error("declaration ID out-of-range for AST file");
5899 return 0;
5900 }
5901
5902 if (!DeclsLoaded[Index]) {
5903 ReadDeclRecord(ID);
5904 if (DeserializationListener)
5905 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5906 }
5907
5908 return DeclsLoaded[Index];
5909}
5910
5911DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5912 DeclID GlobalID) {
5913 if (GlobalID < NUM_PREDEF_DECL_IDS)
5914 return GlobalID;
5915
5916 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5917 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5918 ModuleFile *Owner = I->second;
5919
5920 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5921 = M.GlobalToLocalDeclIDs.find(Owner);
5922 if (Pos == M.GlobalToLocalDeclIDs.end())
5923 return 0;
5924
5925 return GlobalID - Owner->BaseDeclID + Pos->second;
5926}
5927
5928serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5929 const RecordData &Record,
5930 unsigned &Idx) {
5931 if (Idx >= Record.size()) {
5932 Error("Corrupted AST file");
5933 return 0;
5934 }
5935
5936 return getGlobalDeclID(F, Record[Idx++]);
5937}
5938
5939/// \brief Resolve the offset of a statement into a statement.
5940///
5941/// This operation will read a new statement from the external
5942/// source each time it is called, and is meant to be used via a
5943/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5944Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5945 // Switch case IDs are per Decl.
5946 ClearSwitchCaseIDs();
5947
5948 // Offset here is a global offset across the entire chain.
5949 RecordLocation Loc = getLocalBitOffset(Offset);
5950 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5951 return ReadStmtFromStream(*Loc.F);
5952}
5953
5954namespace {
5955 class FindExternalLexicalDeclsVisitor {
5956 ASTReader &Reader;
5957 const DeclContext *DC;
5958 bool (*isKindWeWant)(Decl::Kind);
5959
5960 SmallVectorImpl<Decl*> &Decls;
5961 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5962
5963 public:
5964 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5965 bool (*isKindWeWant)(Decl::Kind),
5966 SmallVectorImpl<Decl*> &Decls)
5967 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5968 {
5969 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5970 PredefsVisited[I] = false;
5971 }
5972
5973 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5974 if (Preorder)
5975 return false;
5976
5977 FindExternalLexicalDeclsVisitor *This
5978 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5979
5980 ModuleFile::DeclContextInfosMap::iterator Info
5981 = M.DeclContextInfos.find(This->DC);
5982 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5983 return false;
5984
5985 // Load all of the declaration IDs
5986 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5987 *IDE = ID + Info->second.NumLexicalDecls;
5988 ID != IDE; ++ID) {
5989 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5990 continue;
5991
5992 // Don't add predefined declarations to the lexical context more
5993 // than once.
5994 if (ID->second < NUM_PREDEF_DECL_IDS) {
5995 if (This->PredefsVisited[ID->second])
5996 continue;
5997
5998 This->PredefsVisited[ID->second] = true;
5999 }
6000
6001 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6002 if (!This->DC->isDeclInLexicalTraversal(D))
6003 This->Decls.push_back(D);
6004 }
6005 }
6006
6007 return false;
6008 }
6009 };
6010}
6011
6012ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6013 bool (*isKindWeWant)(Decl::Kind),
6014 SmallVectorImpl<Decl*> &Decls) {
6015 // There might be lexical decls in multiple modules, for the TU at
6016 // least. Walk all of the modules in the order they were loaded.
6017 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6018 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6019 ++NumLexicalDeclContextsRead;
6020 return ELR_Success;
6021}
6022
6023namespace {
6024
6025class DeclIDComp {
6026 ASTReader &Reader;
6027 ModuleFile &Mod;
6028
6029public:
6030 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6031
6032 bool operator()(LocalDeclID L, LocalDeclID R) const {
6033 SourceLocation LHS = getLocation(L);
6034 SourceLocation RHS = getLocation(R);
6035 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6036 }
6037
6038 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6039 SourceLocation RHS = getLocation(R);
6040 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6041 }
6042
6043 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6044 SourceLocation LHS = getLocation(L);
6045 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6046 }
6047
6048 SourceLocation getLocation(LocalDeclID ID) const {
6049 return Reader.getSourceManager().getFileLoc(
6050 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6051 }
6052};
6053
6054}
6055
6056void ASTReader::FindFileRegionDecls(FileID File,
6057 unsigned Offset, unsigned Length,
6058 SmallVectorImpl<Decl *> &Decls) {
6059 SourceManager &SM = getSourceManager();
6060
6061 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6062 if (I == FileDeclIDs.end())
6063 return;
6064
6065 FileDeclsInfo &DInfo = I->second;
6066 if (DInfo.Decls.empty())
6067 return;
6068
6069 SourceLocation
6070 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6071 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6072
6073 DeclIDComp DIDComp(*this, *DInfo.Mod);
6074 ArrayRef<serialization::LocalDeclID>::iterator
6075 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6076 BeginLoc, DIDComp);
6077 if (BeginIt != DInfo.Decls.begin())
6078 --BeginIt;
6079
6080 // If we are pointing at a top-level decl inside an objc container, we need
6081 // to backtrack until we find it otherwise we will fail to report that the
6082 // region overlaps with an objc container.
6083 while (BeginIt != DInfo.Decls.begin() &&
6084 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6085 ->isTopLevelDeclInObjCContainer())
6086 --BeginIt;
6087
6088 ArrayRef<serialization::LocalDeclID>::iterator
6089 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6090 EndLoc, DIDComp);
6091 if (EndIt != DInfo.Decls.end())
6092 ++EndIt;
6093
6094 for (ArrayRef<serialization::LocalDeclID>::iterator
6095 DIt = BeginIt; DIt != EndIt; ++DIt)
6096 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6097}
6098
6099namespace {
6100 /// \brief ModuleFile visitor used to perform name lookup into a
6101 /// declaration context.
6102 class DeclContextNameLookupVisitor {
6103 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006104 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006105 DeclarationName Name;
6106 SmallVectorImpl<NamedDecl *> &Decls;
6107
6108 public:
6109 DeclContextNameLookupVisitor(ASTReader &Reader,
6110 SmallVectorImpl<const DeclContext *> &Contexts,
6111 DeclarationName Name,
6112 SmallVectorImpl<NamedDecl *> &Decls)
6113 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6114
6115 static bool visit(ModuleFile &M, void *UserData) {
6116 DeclContextNameLookupVisitor *This
6117 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6118
6119 // Check whether we have any visible declaration information for
6120 // this context in this module.
6121 ModuleFile::DeclContextInfosMap::iterator Info;
6122 bool FoundInfo = false;
6123 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6124 Info = M.DeclContextInfos.find(This->Contexts[I]);
6125 if (Info != M.DeclContextInfos.end() &&
6126 Info->second.NameLookupTableData) {
6127 FoundInfo = true;
6128 break;
6129 }
6130 }
6131
6132 if (!FoundInfo)
6133 return false;
6134
6135 // Look for this name within this module.
6136 ASTDeclContextNameLookupTable *LookupTable =
6137 Info->second.NameLookupTableData;
6138 ASTDeclContextNameLookupTable::iterator Pos
6139 = LookupTable->find(This->Name);
6140 if (Pos == LookupTable->end())
6141 return false;
6142
6143 bool FoundAnything = false;
6144 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6145 for (; Data.first != Data.second; ++Data.first) {
6146 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6147 if (!ND)
6148 continue;
6149
6150 if (ND->getDeclName() != This->Name) {
6151 // A name might be null because the decl's redeclarable part is
6152 // currently read before reading its name. The lookup is triggered by
6153 // building that decl (likely indirectly), and so it is later in the
6154 // sense of "already existing" and can be ignored here.
6155 continue;
6156 }
6157
6158 // Record this declaration.
6159 FoundAnything = true;
6160 This->Decls.push_back(ND);
6161 }
6162
6163 return FoundAnything;
6164 }
6165 };
6166}
6167
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00006168/// \brief Retrieve the "definitive" module file for the definition of the
6169/// given declaration context, if there is one.
6170///
6171/// The "definitive" module file is the only place where we need to look to
6172/// find information about the declarations within the given declaration
6173/// context. For example, C++ and Objective-C classes, C structs/unions, and
6174/// Objective-C protocols, categories, and extensions are all defined in a
6175/// single place in the source code, so they have definitive module files
6176/// associated with them. C++ namespaces, on the other hand, can have
6177/// definitions in multiple different module files.
6178///
6179/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6180/// NDEBUG checking.
6181static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6182 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00006183 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6184 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00006185
6186 return 0;
6187}
6188
Richard Smith3646c682013-02-07 03:30:24 +00006189bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006190ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6191 DeclarationName Name) {
6192 assert(DC->hasExternalVisibleStorage() &&
6193 "DeclContext has no visible decls in storage");
6194 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00006195 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006196
6197 SmallVector<NamedDecl *, 64> Decls;
6198
6199 // Compute the declaration contexts we need to look into. Multiple such
6200 // declaration contexts occur when two declaration contexts from disjoint
6201 // modules get merged, e.g., when two namespaces with the same name are
6202 // independently defined in separate modules.
6203 SmallVector<const DeclContext *, 2> Contexts;
6204 Contexts.push_back(DC);
6205
6206 if (DC->isNamespace()) {
6207 MergedDeclsMap::iterator Merged
6208 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6209 if (Merged != MergedDecls.end()) {
6210 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6211 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6212 }
6213 }
6214
6215 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00006216
6217 // If we can definitively determine which module file to look into,
6218 // only look there. Otherwise, look in all module files.
6219 ModuleFile *Definitive;
6220 if (Contexts.size() == 1 &&
6221 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6222 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6223 } else {
6224 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6225 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006226 ++NumVisibleDeclContextsRead;
6227 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00006228 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006229}
6230
6231namespace {
6232 /// \brief ModuleFile visitor used to retrieve all visible names in a
6233 /// declaration context.
6234 class DeclContextAllNamesVisitor {
6235 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006236 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper8ae63872013-07-05 04:43:31 +00006237 DeclsMap &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00006238 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006239
6240 public:
6241 DeclContextAllNamesVisitor(ASTReader &Reader,
6242 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper8ae63872013-07-05 04:43:31 +00006243 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00006244 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006245
6246 static bool visit(ModuleFile &M, void *UserData) {
6247 DeclContextAllNamesVisitor *This
6248 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6249
6250 // Check whether we have any visible declaration information for
6251 // this context in this module.
6252 ModuleFile::DeclContextInfosMap::iterator Info;
6253 bool FoundInfo = false;
6254 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6255 Info = M.DeclContextInfos.find(This->Contexts[I]);
6256 if (Info != M.DeclContextInfos.end() &&
6257 Info->second.NameLookupTableData) {
6258 FoundInfo = true;
6259 break;
6260 }
6261 }
6262
6263 if (!FoundInfo)
6264 return false;
6265
6266 ASTDeclContextNameLookupTable *LookupTable =
6267 Info->second.NameLookupTableData;
6268 bool FoundAnything = false;
6269 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00006270 I = LookupTable->data_begin(), E = LookupTable->data_end();
6271 I != E;
6272 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006273 ASTDeclContextNameLookupTrait::data_type Data = *I;
6274 for (; Data.first != Data.second; ++Data.first) {
6275 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6276 *Data.first);
6277 if (!ND)
6278 continue;
6279
6280 // Record this declaration.
6281 FoundAnything = true;
6282 This->Decls[ND->getDeclName()].push_back(ND);
6283 }
6284 }
6285
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00006286 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006287 }
6288 };
6289}
6290
6291void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6292 if (!DC->hasExternalVisibleStorage())
6293 return;
Craig Topperee0a4792013-07-05 04:33:53 +00006294 DeclsMap Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006295
6296 // Compute the declaration contexts we need to look into. Multiple such
6297 // declaration contexts occur when two declaration contexts from disjoint
6298 // modules get merged, e.g., when two namespaces with the same name are
6299 // independently defined in separate modules.
6300 SmallVector<const DeclContext *, 2> Contexts;
6301 Contexts.push_back(DC);
6302
6303 if (DC->isNamespace()) {
6304 MergedDeclsMap::iterator Merged
6305 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6306 if (Merged != MergedDecls.end()) {
6307 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6308 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6309 }
6310 }
6311
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00006312 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6313 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006314 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6315 ++NumVisibleDeclContextsRead;
6316
Craig Topperee0a4792013-07-05 04:33:53 +00006317 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006318 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6319 }
6320 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6321}
6322
6323/// \brief Under non-PCH compilation the consumer receives the objc methods
6324/// before receiving the implementation, and codegen depends on this.
6325/// We simulate this by deserializing and passing to consumer the methods of the
6326/// implementation before passing the deserialized implementation decl.
6327static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6328 ASTConsumer *Consumer) {
6329 assert(ImplD && Consumer);
6330
Stephen Hines651f13c2014-04-23 16:59:28 -07006331 for (auto *I : ImplD->methods())
6332 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006333
6334 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6335}
6336
6337void ASTReader::PassInterestingDeclsToConsumer() {
6338 assert(Consumer);
Stephen Hines651f13c2014-04-23 16:59:28 -07006339
6340 if (PassingDeclsToConsumer)
6341 return;
6342
6343 // Guard variable to avoid recursively redoing the process of passing
6344 // decls to consumer.
6345 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6346 true);
6347
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006348 while (!InterestingDecls.empty()) {
6349 Decl *D = InterestingDecls.front();
6350 InterestingDecls.pop_front();
6351
6352 PassInterestingDeclToConsumer(D);
6353 }
6354}
6355
6356void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6357 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6358 PassObjCImplDeclToConsumer(ImplD, Consumer);
6359 else
6360 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6361}
6362
6363void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6364 this->Consumer = Consumer;
6365
6366 if (!Consumer)
6367 return;
6368
Stephen Hines651f13c2014-04-23 16:59:28 -07006369 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006370 // Force deserialization of this decl, which will cause it to be queued for
6371 // passing to the consumer.
Stephen Hines651f13c2014-04-23 16:59:28 -07006372 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006373 }
Stephen Hines651f13c2014-04-23 16:59:28 -07006374 EagerlyDeserializedDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006375
6376 PassInterestingDeclsToConsumer();
6377}
6378
6379void ASTReader::PrintStats() {
6380 std::fprintf(stderr, "*** AST File Statistics:\n");
6381
6382 unsigned NumTypesLoaded
6383 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6384 QualType());
6385 unsigned NumDeclsLoaded
6386 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6387 (Decl *)0);
6388 unsigned NumIdentifiersLoaded
6389 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6390 IdentifiersLoaded.end(),
6391 (IdentifierInfo *)0);
6392 unsigned NumMacrosLoaded
6393 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6394 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006395 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006396 unsigned NumSelectorsLoaded
6397 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6398 SelectorsLoaded.end(),
6399 Selector());
6400
6401 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6402 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6403 NumSLocEntriesRead, TotalNumSLocEntries,
6404 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6405 if (!TypesLoaded.empty())
6406 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6407 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6408 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6409 if (!DeclsLoaded.empty())
6410 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6411 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6412 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6413 if (!IdentifiersLoaded.empty())
6414 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6415 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6416 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6417 if (!MacrosLoaded.empty())
6418 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6419 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6420 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6421 if (!SelectorsLoaded.empty())
6422 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6423 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6424 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6425 if (TotalNumStatements)
6426 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6427 NumStatementsRead, TotalNumStatements,
6428 ((float)NumStatementsRead/TotalNumStatements * 100));
6429 if (TotalNumMacros)
6430 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6431 NumMacrosRead, TotalNumMacros,
6432 ((float)NumMacrosRead/TotalNumMacros * 100));
6433 if (TotalLexicalDeclContexts)
6434 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6435 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6436 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6437 * 100));
6438 if (TotalVisibleDeclContexts)
6439 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6440 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6441 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6442 * 100));
6443 if (TotalNumMethodPoolEntries) {
6444 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6445 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6446 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6447 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006448 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006449 if (NumMethodPoolLookups) {
6450 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6451 NumMethodPoolHits, NumMethodPoolLookups,
6452 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6453 }
6454 if (NumMethodPoolTableLookups) {
6455 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6456 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6457 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6458 * 100.0));
6459 }
6460
Douglas Gregore1698072013-01-25 00:38:33 +00006461 if (NumIdentifierLookupHits) {
6462 std::fprintf(stderr,
6463 " %u / %u identifier table lookups succeeded (%f%%)\n",
6464 NumIdentifierLookupHits, NumIdentifierLookups,
6465 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6466 }
6467
Douglas Gregor1a49d972013-01-25 01:03:03 +00006468 if (GlobalIndex) {
6469 std::fprintf(stderr, "\n");
6470 GlobalIndex->printStats();
6471 }
6472
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006473 std::fprintf(stderr, "\n");
6474 dump();
6475 std::fprintf(stderr, "\n");
6476}
6477
6478template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6479static void
6480dumpModuleIDMap(StringRef Name,
6481 const ContinuousRangeMap<Key, ModuleFile *,
6482 InitialCapacity> &Map) {
6483 if (Map.begin() == Map.end())
6484 return;
6485
6486 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6487 llvm::errs() << Name << ":\n";
6488 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6489 I != IEnd; ++I) {
6490 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6491 << "\n";
6492 }
6493}
6494
6495void ASTReader::dump() {
6496 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6497 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6498 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6499 dumpModuleIDMap("Global type map", GlobalTypeMap);
6500 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6501 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6502 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6503 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6504 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6505 dumpModuleIDMap("Global preprocessed entity map",
6506 GlobalPreprocessedEntityMap);
6507
6508 llvm::errs() << "\n*** PCH/Modules Loaded:";
6509 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6510 MEnd = ModuleMgr.end();
6511 M != MEnd; ++M)
6512 (*M)->dump();
6513}
6514
6515/// Return the amount of memory used by memory buffers, breaking down
6516/// by heap-backed versus mmap'ed memory.
6517void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6518 for (ModuleConstIterator I = ModuleMgr.begin(),
6519 E = ModuleMgr.end(); I != E; ++I) {
6520 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6521 size_t bytes = buf->getBufferSize();
6522 switch (buf->getBufferKind()) {
6523 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6524 sizes.malloc_bytes += bytes;
6525 break;
6526 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6527 sizes.mmap_bytes += bytes;
6528 break;
6529 }
6530 }
6531 }
6532}
6533
6534void ASTReader::InitializeSema(Sema &S) {
6535 SemaObj = &S;
6536 S.addExternalSource(this);
6537
6538 // Makes sure any declarations that were deserialized "too early"
6539 // still get added to the identifier's declaration chains.
6540 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006541 pushExternalDeclIntoScope(PreloadedDecls[I],
6542 PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006543 }
6544 PreloadedDecls.clear();
6545
Richard Smith9b671182013-10-18 06:54:39 +00006546 // FIXME: What happens if these are changed by a module import?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006547 if (!FPPragmaOptions.empty()) {
6548 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6549 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6550 }
6551
Richard Smith9b671182013-10-18 06:54:39 +00006552 // FIXME: What happens if these are changed by a module import?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006553 if (!OpenCLExtensions.empty()) {
6554 unsigned I = 0;
6555#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6556#include "clang/Basic/OpenCLExtensions.def"
6557
6558 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6559 }
Richard Smith9b671182013-10-18 06:54:39 +00006560
6561 UpdateSema();
6562}
6563
6564void ASTReader::UpdateSema() {
6565 assert(SemaObj && "no Sema to update");
6566
6567 // Load the offsets of the declarations that Sema references.
6568 // They will be lazily deserialized when needed.
6569 if (!SemaDeclRefs.empty()) {
6570 assert(SemaDeclRefs.size() % 2 == 0);
6571 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6572 if (!SemaObj->StdNamespace)
6573 SemaObj->StdNamespace = SemaDeclRefs[I];
6574 if (!SemaObj->StdBadAlloc)
6575 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6576 }
6577 SemaDeclRefs.clear();
6578 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006579}
6580
6581IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6582 // Note that we are loading an identifier.
6583 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006584 StringRef Name(NameStart, NameEnd - NameStart);
6585
6586 // If there is a global index, look there first to determine which modules
6587 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006588 GlobalModuleIndex::HitSet Hits;
6589 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006590 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006591 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6592 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006593 }
6594 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006595 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006596 NumIdentifierLookups,
6597 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006598 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006599 IdentifierInfo *II = Visitor.getIdentifierInfo();
6600 markIdentifierUpToDate(II);
6601 return II;
6602}
6603
6604namespace clang {
6605 /// \brief An identifier-lookup iterator that enumerates all of the
6606 /// identifiers stored within a set of AST files.
6607 class ASTIdentifierIterator : public IdentifierIterator {
6608 /// \brief The AST reader whose identifiers are being enumerated.
6609 const ASTReader &Reader;
6610
6611 /// \brief The current index into the chain of AST files stored in
6612 /// the AST reader.
6613 unsigned Index;
6614
6615 /// \brief The current position within the identifier lookup table
6616 /// of the current AST file.
6617 ASTIdentifierLookupTable::key_iterator Current;
6618
6619 /// \brief The end position within the identifier lookup table of
6620 /// the current AST file.
6621 ASTIdentifierLookupTable::key_iterator End;
6622
6623 public:
6624 explicit ASTIdentifierIterator(const ASTReader &Reader);
6625
Stephen Hines651f13c2014-04-23 16:59:28 -07006626 StringRef Next() override;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006627 };
6628}
6629
6630ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6631 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6632 ASTIdentifierLookupTable *IdTable
6633 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6634 Current = IdTable->key_begin();
6635 End = IdTable->key_end();
6636}
6637
6638StringRef ASTIdentifierIterator::Next() {
6639 while (Current == End) {
6640 // If we have exhausted all of our AST files, we're done.
6641 if (Index == 0)
6642 return StringRef();
6643
6644 --Index;
6645 ASTIdentifierLookupTable *IdTable
6646 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6647 IdentifierLookupTable;
6648 Current = IdTable->key_begin();
6649 End = IdTable->key_end();
6650 }
6651
6652 // We have any identifiers remaining in the current AST file; return
6653 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006654 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006655 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006656 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006657}
6658
Argyrios Kyrtzidis87f9d812013-04-17 22:10:55 +00006659IdentifierIterator *ASTReader::getIdentifiers() {
6660 if (!loadGlobalIndex())
6661 return GlobalIndex->createIdentifierIterator();
6662
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006663 return new ASTIdentifierIterator(*this);
6664}
6665
6666namespace clang { namespace serialization {
6667 class ReadMethodPoolVisitor {
6668 ASTReader &Reader;
6669 Selector Sel;
6670 unsigned PriorGeneration;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006671 unsigned InstanceBits;
6672 unsigned FactoryBits;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006673 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6674 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006675
6676 public:
6677 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6678 unsigned PriorGeneration)
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006679 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6680 InstanceBits(0), FactoryBits(0) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006681
6682 static bool visit(ModuleFile &M, void *UserData) {
6683 ReadMethodPoolVisitor *This
6684 = static_cast<ReadMethodPoolVisitor *>(UserData);
6685
6686 if (!M.SelectorLookupTable)
6687 return false;
6688
6689 // If we've already searched this module file, skip it now.
6690 if (M.Generation <= This->PriorGeneration)
6691 return true;
6692
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006693 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006694 ASTSelectorLookupTable *PoolTable
6695 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6696 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6697 if (Pos == PoolTable->end())
6698 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006699
6700 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006701 ++This->Reader.NumSelectorsRead;
6702 // FIXME: Not quite happy with the statistics here. We probably should
6703 // disable this tracking when called via LoadSelector.
6704 // Also, should entries without methods count as misses?
6705 ++This->Reader.NumMethodPoolEntriesRead;
6706 ASTSelectorLookupTrait::data_type Data = *Pos;
6707 if (This->Reader.DeserializationListener)
6708 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6709 This->Sel);
6710
6711 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6712 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006713 This->InstanceBits = Data.InstanceBits;
6714 This->FactoryBits = Data.FactoryBits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006715 return true;
6716 }
6717
6718 /// \brief Retrieve the instance methods found by this visitor.
6719 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6720 return InstanceMethods;
6721 }
6722
6723 /// \brief Retrieve the instance methods found by this visitor.
6724 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6725 return FactoryMethods;
6726 }
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006727
6728 unsigned getInstanceBits() const { return InstanceBits; }
6729 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006730 };
6731} } // end namespace clang::serialization
6732
6733/// \brief Add the given set of methods to the method list.
6734static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6735 ObjCMethodList &List) {
6736 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6737 S.addMethodToGlobalList(&List, Methods[I]);
6738 }
6739}
6740
6741void ASTReader::ReadMethodPool(Selector Sel) {
6742 // Get the selector generation and update it to the current generation.
6743 unsigned &Generation = SelectorGeneration[Sel];
6744 unsigned PriorGeneration = Generation;
6745 Generation = CurrentGeneration;
6746
6747 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006748 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006749 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6750 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6751
6752 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006753 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006754 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006755
6756 ++NumMethodPoolHits;
6757
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006758 if (!getSema())
6759 return;
6760
6761 Sema &S = *getSema();
6762 Sema::GlobalMethodPool::iterator Pos
6763 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6764
6765 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6766 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006767 Pos->second.first.setBits(Visitor.getInstanceBits());
6768 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006769}
6770
6771void ASTReader::ReadKnownNamespaces(
6772 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6773 Namespaces.clear();
6774
6775 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6776 if (NamespaceDecl *Namespace
6777 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6778 Namespaces.push_back(Namespace);
6779 }
6780}
6781
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006782void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006783 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006784 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6785 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006786 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006787 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006788 Undefined.insert(std::make_pair(D, Loc));
6789 }
6790}
Nick Lewycky01a41142013-01-26 00:35:08 +00006791
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006792void ASTReader::ReadTentativeDefinitions(
6793 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6794 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6795 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6796 if (Var)
6797 TentativeDefs.push_back(Var);
6798 }
6799 TentativeDefinitions.clear();
6800}
6801
6802void ASTReader::ReadUnusedFileScopedDecls(
6803 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6804 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6805 DeclaratorDecl *D
6806 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6807 if (D)
6808 Decls.push_back(D);
6809 }
6810 UnusedFileScopedDecls.clear();
6811}
6812
6813void ASTReader::ReadDelegatingConstructors(
6814 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6815 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6816 CXXConstructorDecl *D
6817 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6818 if (D)
6819 Decls.push_back(D);
6820 }
6821 DelegatingCtorDecls.clear();
6822}
6823
6824void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6825 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6826 TypedefNameDecl *D
6827 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6828 if (D)
6829 Decls.push_back(D);
6830 }
6831 ExtVectorDecls.clear();
6832}
6833
6834void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6835 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6836 CXXRecordDecl *D
6837 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6838 if (D)
6839 Decls.push_back(D);
6840 }
6841 DynamicClasses.clear();
6842}
6843
6844void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006845ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6846 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6847 NamedDecl *D
6848 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006849 if (D)
6850 Decls.push_back(D);
6851 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006852 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006853}
6854
6855void ASTReader::ReadReferencedSelectors(
6856 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6857 if (ReferencedSelectorsData.empty())
6858 return;
6859
6860 // If there are @selector references added them to its pool. This is for
6861 // implementation of -Wselector.
6862 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6863 unsigned I = 0;
6864 while (I < DataSize) {
6865 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6866 SourceLocation SelLoc
6867 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6868 Sels.push_back(std::make_pair(Sel, SelLoc));
6869 }
6870 ReferencedSelectorsData.clear();
6871}
6872
6873void ASTReader::ReadWeakUndeclaredIdentifiers(
6874 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6875 if (WeakUndeclaredIdentifiers.empty())
6876 return;
6877
6878 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6879 IdentifierInfo *WeakId
6880 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6881 IdentifierInfo *AliasId
6882 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6883 SourceLocation Loc
6884 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6885 bool Used = WeakUndeclaredIdentifiers[I++];
6886 WeakInfo WI(AliasId, Loc);
6887 WI.setUsed(Used);
6888 WeakIDs.push_back(std::make_pair(WeakId, WI));
6889 }
6890 WeakUndeclaredIdentifiers.clear();
6891}
6892
6893void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6894 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6895 ExternalVTableUse VT;
6896 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6897 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6898 VT.DefinitionRequired = VTableUses[Idx++];
6899 VTables.push_back(VT);
6900 }
6901
6902 VTableUses.clear();
6903}
6904
6905void ASTReader::ReadPendingInstantiations(
6906 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6907 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6908 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6909 SourceLocation Loc
6910 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6911
6912 Pending.push_back(std::make_pair(D, Loc));
6913 }
6914 PendingInstantiations.clear();
6915}
6916
Richard Smithac32d902013-08-07 21:41:30 +00006917void ASTReader::ReadLateParsedTemplates(
6918 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6919 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6920 /* In loop */) {
6921 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6922
6923 LateParsedTemplate *LT = new LateParsedTemplate;
6924 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6925
6926 ModuleFile *F = getOwningModuleFile(LT->D);
6927 assert(F && "No module");
6928
6929 unsigned TokN = LateParsedTemplates[Idx++];
6930 LT->Toks.reserve(TokN);
6931 for (unsigned T = 0; T < TokN; ++T)
6932 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6933
6934 LPTMap[FD] = LT;
6935 }
6936
6937 LateParsedTemplates.clear();
6938}
6939
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006940void ASTReader::LoadSelector(Selector Sel) {
6941 // It would be complicated to avoid reading the methods anyway. So don't.
6942 ReadMethodPool(Sel);
6943}
6944
6945void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6946 assert(ID && "Non-zero identifier ID required");
6947 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6948 IdentifiersLoaded[ID - 1] = II;
6949 if (DeserializationListener)
6950 DeserializationListener->IdentifierRead(ID, II);
6951}
6952
6953/// \brief Set the globally-visible declarations associated with the given
6954/// identifier.
6955///
6956/// If the AST reader is currently in a state where the given declaration IDs
6957/// cannot safely be resolved, they are queued until it is safe to resolve
6958/// them.
6959///
6960/// \param II an IdentifierInfo that refers to one or more globally-visible
6961/// declarations.
6962///
6963/// \param DeclIDs the set of declaration IDs with the name @p II that are
6964/// visible at global scope.
6965///
Douglas Gregoraa945902013-02-18 15:53:43 +00006966/// \param Decls if non-null, this vector will be populated with the set of
6967/// deserialized declarations. These declarations will not be pushed into
6968/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006969void
6970ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6971 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006972 SmallVectorImpl<Decl *> *Decls) {
6973 if (NumCurrentElementsDeserializing && !Decls) {
6974 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006975 return;
6976 }
6977
6978 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6979 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6980 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006981 // If we're simply supposed to record the declarations, do so now.
6982 if (Decls) {
6983 Decls->push_back(D);
6984 continue;
6985 }
6986
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006987 // Introduce this declaration into the translation-unit scope
6988 // and add it to the declaration chain for this identifier, so
6989 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006990 pushExternalDeclIntoScope(D, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006991 } else {
6992 // Queue this declaration so that it will be added to the
6993 // translation unit scope and identifier's declaration chain
6994 // once a Sema object is known.
6995 PreloadedDecls.push_back(D);
6996 }
6997 }
6998}
6999
Douglas Gregor8222b892013-01-21 16:52:34 +00007000IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007001 if (ID == 0)
7002 return 0;
7003
7004 if (IdentifiersLoaded.empty()) {
7005 Error("no identifier table in AST file");
7006 return 0;
7007 }
7008
7009 ID -= 1;
7010 if (!IdentifiersLoaded[ID]) {
7011 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7012 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7013 ModuleFile *M = I->second;
7014 unsigned Index = ID - M->BaseIdentifierID;
7015 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7016
7017 // All of the strings in the AST file are preceded by a 16-bit length.
7018 // Extract that 16-bit length to avoid having to execute strlen().
7019 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7020 // unsigned integers. This is important to avoid integer overflow when
7021 // we cast them to 'unsigned'.
7022 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7023 unsigned StrLen = (((unsigned) StrLenPtr[0])
7024 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00007025 IdentifiersLoaded[ID]
7026 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007027 if (DeserializationListener)
7028 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7029 }
7030
7031 return IdentifiersLoaded[ID];
7032}
7033
Douglas Gregor8222b892013-01-21 16:52:34 +00007034IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7035 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007036}
7037
7038IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7039 if (LocalID < NUM_PREDEF_IDENT_IDS)
7040 return LocalID;
7041
7042 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7043 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7044 assert(I != M.IdentifierRemap.end()
7045 && "Invalid index into identifier index remap");
7046
7047 return LocalID + I->second;
7048}
7049
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007050MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007051 if (ID == 0)
7052 return 0;
7053
7054 if (MacrosLoaded.empty()) {
7055 Error("no macro table in AST file");
7056 return 0;
7057 }
7058
7059 ID -= NUM_PREDEF_MACRO_IDS;
7060 if (!MacrosLoaded[ID]) {
7061 GlobalMacroMapType::iterator I
7062 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7063 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7064 ModuleFile *M = I->second;
7065 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007066 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7067
7068 if (DeserializationListener)
7069 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7070 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007071 }
7072
7073 return MacrosLoaded[ID];
7074}
7075
7076MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7077 if (LocalID < NUM_PREDEF_MACRO_IDS)
7078 return LocalID;
7079
7080 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7081 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7082 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7083
7084 return LocalID + I->second;
7085}
7086
7087serialization::SubmoduleID
7088ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7089 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7090 return LocalID;
7091
7092 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7093 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7094 assert(I != M.SubmoduleRemap.end()
7095 && "Invalid index into submodule index remap");
7096
7097 return LocalID + I->second;
7098}
7099
7100Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7101 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7102 assert(GlobalID == 0 && "Unhandled global submodule ID");
7103 return 0;
7104 }
7105
7106 if (GlobalID > SubmodulesLoaded.size()) {
7107 Error("submodule ID out of range in AST file");
7108 return 0;
7109 }
7110
7111 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7112}
Douglas Gregorca2ab452013-01-12 01:29:50 +00007113
7114Module *ASTReader::getModule(unsigned ID) {
7115 return getSubmodule(ID);
7116}
7117
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007118Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7119 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7120}
7121
7122Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7123 if (ID == 0)
7124 return Selector();
7125
7126 if (ID > SelectorsLoaded.size()) {
7127 Error("selector ID out of range in AST file");
7128 return Selector();
7129 }
7130
7131 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7132 // Load this selector from the selector table.
7133 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7134 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7135 ModuleFile &M = *I->second;
7136 ASTSelectorLookupTrait Trait(*this, M);
7137 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7138 SelectorsLoaded[ID - 1] =
7139 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7140 if (DeserializationListener)
7141 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7142 }
7143
7144 return SelectorsLoaded[ID - 1];
7145}
7146
7147Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7148 return DecodeSelector(ID);
7149}
7150
7151uint32_t ASTReader::GetNumExternalSelectors() {
7152 // ID 0 (the null selector) is considered an external selector.
7153 return getTotalNumSelectors() + 1;
7154}
7155
7156serialization::SelectorID
7157ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7158 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7159 return LocalID;
7160
7161 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7162 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7163 assert(I != M.SelectorRemap.end()
7164 && "Invalid index into selector index remap");
7165
7166 return LocalID + I->second;
7167}
7168
7169DeclarationName
7170ASTReader::ReadDeclarationName(ModuleFile &F,
7171 const RecordData &Record, unsigned &Idx) {
7172 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7173 switch (Kind) {
7174 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00007175 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007176
7177 case DeclarationName::ObjCZeroArgSelector:
7178 case DeclarationName::ObjCOneArgSelector:
7179 case DeclarationName::ObjCMultiArgSelector:
7180 return DeclarationName(ReadSelector(F, Record, Idx));
7181
7182 case DeclarationName::CXXConstructorName:
7183 return Context.DeclarationNames.getCXXConstructorName(
7184 Context.getCanonicalType(readType(F, Record, Idx)));
7185
7186 case DeclarationName::CXXDestructorName:
7187 return Context.DeclarationNames.getCXXDestructorName(
7188 Context.getCanonicalType(readType(F, Record, Idx)));
7189
7190 case DeclarationName::CXXConversionFunctionName:
7191 return Context.DeclarationNames.getCXXConversionFunctionName(
7192 Context.getCanonicalType(readType(F, Record, Idx)));
7193
7194 case DeclarationName::CXXOperatorName:
7195 return Context.DeclarationNames.getCXXOperatorName(
7196 (OverloadedOperatorKind)Record[Idx++]);
7197
7198 case DeclarationName::CXXLiteralOperatorName:
7199 return Context.DeclarationNames.getCXXLiteralOperatorName(
7200 GetIdentifierInfo(F, Record, Idx));
7201
7202 case DeclarationName::CXXUsingDirective:
7203 return DeclarationName::getUsingDirectiveName();
7204 }
7205
7206 llvm_unreachable("Invalid NameKind!");
7207}
7208
7209void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7210 DeclarationNameLoc &DNLoc,
7211 DeclarationName Name,
7212 const RecordData &Record, unsigned &Idx) {
7213 switch (Name.getNameKind()) {
7214 case DeclarationName::CXXConstructorName:
7215 case DeclarationName::CXXDestructorName:
7216 case DeclarationName::CXXConversionFunctionName:
7217 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7218 break;
7219
7220 case DeclarationName::CXXOperatorName:
7221 DNLoc.CXXOperatorName.BeginOpNameLoc
7222 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7223 DNLoc.CXXOperatorName.EndOpNameLoc
7224 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7225 break;
7226
7227 case DeclarationName::CXXLiteralOperatorName:
7228 DNLoc.CXXLiteralOperatorName.OpNameLoc
7229 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7230 break;
7231
7232 case DeclarationName::Identifier:
7233 case DeclarationName::ObjCZeroArgSelector:
7234 case DeclarationName::ObjCOneArgSelector:
7235 case DeclarationName::ObjCMultiArgSelector:
7236 case DeclarationName::CXXUsingDirective:
7237 break;
7238 }
7239}
7240
7241void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7242 DeclarationNameInfo &NameInfo,
7243 const RecordData &Record, unsigned &Idx) {
7244 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7245 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7246 DeclarationNameLoc DNLoc;
7247 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7248 NameInfo.setInfo(DNLoc);
7249}
7250
7251void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7252 const RecordData &Record, unsigned &Idx) {
7253 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7254 unsigned NumTPLists = Record[Idx++];
7255 Info.NumTemplParamLists = NumTPLists;
7256 if (NumTPLists) {
7257 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7258 for (unsigned i=0; i != NumTPLists; ++i)
7259 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7260 }
7261}
7262
7263TemplateName
7264ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7265 unsigned &Idx) {
7266 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7267 switch (Kind) {
7268 case TemplateName::Template:
7269 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7270
7271 case TemplateName::OverloadedTemplate: {
7272 unsigned size = Record[Idx++];
7273 UnresolvedSet<8> Decls;
7274 while (size--)
7275 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7276
7277 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7278 }
7279
7280 case TemplateName::QualifiedTemplate: {
7281 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7282 bool hasTemplKeyword = Record[Idx++];
7283 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7284 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7285 }
7286
7287 case TemplateName::DependentTemplate: {
7288 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7289 if (Record[Idx++]) // isIdentifier
7290 return Context.getDependentTemplateName(NNS,
7291 GetIdentifierInfo(F, Record,
7292 Idx));
7293 return Context.getDependentTemplateName(NNS,
7294 (OverloadedOperatorKind)Record[Idx++]);
7295 }
7296
7297 case TemplateName::SubstTemplateTemplateParm: {
7298 TemplateTemplateParmDecl *param
7299 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7300 if (!param) return TemplateName();
7301 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7302 return Context.getSubstTemplateTemplateParm(param, replacement);
7303 }
7304
7305 case TemplateName::SubstTemplateTemplateParmPack: {
7306 TemplateTemplateParmDecl *Param
7307 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7308 if (!Param)
7309 return TemplateName();
7310
7311 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7312 if (ArgPack.getKind() != TemplateArgument::Pack)
7313 return TemplateName();
7314
7315 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7316 }
7317 }
7318
7319 llvm_unreachable("Unhandled template name kind!");
7320}
7321
7322TemplateArgument
7323ASTReader::ReadTemplateArgument(ModuleFile &F,
7324 const RecordData &Record, unsigned &Idx) {
7325 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7326 switch (Kind) {
7327 case TemplateArgument::Null:
7328 return TemplateArgument();
7329 case TemplateArgument::Type:
7330 return TemplateArgument(readType(F, Record, Idx));
7331 case TemplateArgument::Declaration: {
7332 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7333 bool ForReferenceParam = Record[Idx++];
7334 return TemplateArgument(D, ForReferenceParam);
7335 }
7336 case TemplateArgument::NullPtr:
7337 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7338 case TemplateArgument::Integral: {
7339 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7340 QualType T = readType(F, Record, Idx);
7341 return TemplateArgument(Context, Value, T);
7342 }
7343 case TemplateArgument::Template:
7344 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7345 case TemplateArgument::TemplateExpansion: {
7346 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00007347 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007348 if (unsigned NumExpansions = Record[Idx++])
7349 NumTemplateExpansions = NumExpansions - 1;
7350 return TemplateArgument(Name, NumTemplateExpansions);
7351 }
7352 case TemplateArgument::Expression:
7353 return TemplateArgument(ReadExpr(F));
7354 case TemplateArgument::Pack: {
7355 unsigned NumArgs = Record[Idx++];
7356 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7357 for (unsigned I = 0; I != NumArgs; ++I)
7358 Args[I] = ReadTemplateArgument(F, Record, Idx);
7359 return TemplateArgument(Args, NumArgs);
7360 }
7361 }
7362
7363 llvm_unreachable("Unhandled template argument kind!");
7364}
7365
7366TemplateParameterList *
7367ASTReader::ReadTemplateParameterList(ModuleFile &F,
7368 const RecordData &Record, unsigned &Idx) {
7369 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7370 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7371 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7372
7373 unsigned NumParams = Record[Idx++];
7374 SmallVector<NamedDecl *, 16> Params;
7375 Params.reserve(NumParams);
7376 while (NumParams--)
7377 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7378
7379 TemplateParameterList* TemplateParams =
7380 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7381 Params.data(), Params.size(), RAngleLoc);
7382 return TemplateParams;
7383}
7384
7385void
7386ASTReader::
Craig Topper6b9240e2013-07-05 19:34:19 +00007387ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007388 ModuleFile &F, const RecordData &Record,
7389 unsigned &Idx) {
7390 unsigned NumTemplateArgs = Record[Idx++];
7391 TemplArgs.reserve(NumTemplateArgs);
7392 while (NumTemplateArgs--)
7393 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7394}
7395
7396/// \brief Read a UnresolvedSet structure.
Richard Smithc2d77572013-08-30 04:46:40 +00007397void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007398 const RecordData &Record, unsigned &Idx) {
7399 unsigned NumDecls = Record[Idx++];
7400 Set.reserve(Context, NumDecls);
7401 while (NumDecls--) {
Richard Smithc2d77572013-08-30 04:46:40 +00007402 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007403 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithc2d77572013-08-30 04:46:40 +00007404 Set.addLazyDecl(Context, ID, AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007405 }
7406}
7407
7408CXXBaseSpecifier
7409ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7410 const RecordData &Record, unsigned &Idx) {
7411 bool isVirtual = static_cast<bool>(Record[Idx++]);
7412 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7413 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7414 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7415 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7416 SourceRange Range = ReadSourceRange(F, Record, Idx);
7417 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7418 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7419 EllipsisLoc);
7420 Result.setInheritConstructors(inheritConstructors);
7421 return Result;
7422}
7423
7424std::pair<CXXCtorInitializer **, unsigned>
7425ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7426 unsigned &Idx) {
7427 CXXCtorInitializer **CtorInitializers = 0;
7428 unsigned NumInitializers = Record[Idx++];
7429 if (NumInitializers) {
7430 CtorInitializers
7431 = new (Context) CXXCtorInitializer*[NumInitializers];
7432 for (unsigned i=0; i != NumInitializers; ++i) {
7433 TypeSourceInfo *TInfo = 0;
7434 bool IsBaseVirtual = false;
7435 FieldDecl *Member = 0;
7436 IndirectFieldDecl *IndirectMember = 0;
7437
7438 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7439 switch (Type) {
7440 case CTOR_INITIALIZER_BASE:
7441 TInfo = GetTypeSourceInfo(F, Record, Idx);
7442 IsBaseVirtual = Record[Idx++];
7443 break;
7444
7445 case CTOR_INITIALIZER_DELEGATING:
7446 TInfo = GetTypeSourceInfo(F, Record, Idx);
7447 break;
7448
7449 case CTOR_INITIALIZER_MEMBER:
7450 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7451 break;
7452
7453 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7454 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7455 break;
7456 }
7457
7458 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7459 Expr *Init = ReadExpr(F);
7460 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7461 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7462 bool IsWritten = Record[Idx++];
7463 unsigned SourceOrderOrNumArrayIndices;
7464 SmallVector<VarDecl *, 8> Indices;
7465 if (IsWritten) {
7466 SourceOrderOrNumArrayIndices = Record[Idx++];
7467 } else {
7468 SourceOrderOrNumArrayIndices = Record[Idx++];
7469 Indices.reserve(SourceOrderOrNumArrayIndices);
7470 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7471 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7472 }
7473
7474 CXXCtorInitializer *BOMInit;
7475 if (Type == CTOR_INITIALIZER_BASE) {
7476 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7477 LParenLoc, Init, RParenLoc,
7478 MemberOrEllipsisLoc);
7479 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7480 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7481 Init, RParenLoc);
7482 } else if (IsWritten) {
7483 if (Member)
7484 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7485 LParenLoc, Init, RParenLoc);
7486 else
7487 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7488 MemberOrEllipsisLoc, LParenLoc,
7489 Init, RParenLoc);
7490 } else {
Argyrios Kyrtzidisf8f480f2013-05-30 23:59:46 +00007491 if (IndirectMember) {
7492 assert(Indices.empty() && "Indirect field improperly initialized");
7493 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7494 MemberOrEllipsisLoc, LParenLoc,
7495 Init, RParenLoc);
7496 } else {
7497 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7498 LParenLoc, Init, RParenLoc,
7499 Indices.data(), Indices.size());
7500 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007501 }
7502
7503 if (IsWritten)
7504 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7505 CtorInitializers[i] = BOMInit;
7506 }
7507 }
7508
7509 return std::make_pair(CtorInitializers, NumInitializers);
7510}
7511
7512NestedNameSpecifier *
7513ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7514 const RecordData &Record, unsigned &Idx) {
7515 unsigned N = Record[Idx++];
7516 NestedNameSpecifier *NNS = 0, *Prev = 0;
7517 for (unsigned I = 0; I != N; ++I) {
7518 NestedNameSpecifier::SpecifierKind Kind
7519 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7520 switch (Kind) {
7521 case NestedNameSpecifier::Identifier: {
7522 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7523 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7524 break;
7525 }
7526
7527 case NestedNameSpecifier::Namespace: {
7528 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7529 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7530 break;
7531 }
7532
7533 case NestedNameSpecifier::NamespaceAlias: {
7534 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7535 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7536 break;
7537 }
7538
7539 case NestedNameSpecifier::TypeSpec:
7540 case NestedNameSpecifier::TypeSpecWithTemplate: {
7541 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7542 if (!T)
7543 return 0;
7544
7545 bool Template = Record[Idx++];
7546 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7547 break;
7548 }
7549
7550 case NestedNameSpecifier::Global: {
7551 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7552 // No associated value, and there can't be a prefix.
7553 break;
7554 }
7555 }
7556 Prev = NNS;
7557 }
7558 return NNS;
7559}
7560
7561NestedNameSpecifierLoc
7562ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7563 unsigned &Idx) {
7564 unsigned N = Record[Idx++];
7565 NestedNameSpecifierLocBuilder Builder;
7566 for (unsigned I = 0; I != N; ++I) {
7567 NestedNameSpecifier::SpecifierKind Kind
7568 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7569 switch (Kind) {
7570 case NestedNameSpecifier::Identifier: {
7571 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7572 SourceRange Range = ReadSourceRange(F, Record, Idx);
7573 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7574 break;
7575 }
7576
7577 case NestedNameSpecifier::Namespace: {
7578 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7579 SourceRange Range = ReadSourceRange(F, Record, Idx);
7580 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7581 break;
7582 }
7583
7584 case NestedNameSpecifier::NamespaceAlias: {
7585 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7586 SourceRange Range = ReadSourceRange(F, Record, Idx);
7587 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7588 break;
7589 }
7590
7591 case NestedNameSpecifier::TypeSpec:
7592 case NestedNameSpecifier::TypeSpecWithTemplate: {
7593 bool Template = Record[Idx++];
7594 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7595 if (!T)
7596 return NestedNameSpecifierLoc();
7597 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7598
7599 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7600 Builder.Extend(Context,
7601 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7602 T->getTypeLoc(), ColonColonLoc);
7603 break;
7604 }
7605
7606 case NestedNameSpecifier::Global: {
7607 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7608 Builder.MakeGlobal(Context, ColonColonLoc);
7609 break;
7610 }
7611 }
7612 }
7613
7614 return Builder.getWithLocInContext(Context);
7615}
7616
7617SourceRange
7618ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7619 unsigned &Idx) {
7620 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7621 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7622 return SourceRange(beg, end);
7623}
7624
7625/// \brief Read an integral value
7626llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7627 unsigned BitWidth = Record[Idx++];
7628 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7629 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7630 Idx += NumWords;
7631 return Result;
7632}
7633
7634/// \brief Read a signed integral value
7635llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7636 bool isUnsigned = Record[Idx++];
7637 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7638}
7639
7640/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007641llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7642 const llvm::fltSemantics &Sem,
7643 unsigned &Idx) {
7644 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007645}
7646
7647// \brief Read a string
7648std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7649 unsigned Len = Record[Idx++];
7650 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7651 Idx += Len;
7652 return Result;
7653}
7654
7655VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7656 unsigned &Idx) {
7657 unsigned Major = Record[Idx++];
7658 unsigned Minor = Record[Idx++];
7659 unsigned Subminor = Record[Idx++];
7660 if (Minor == 0)
7661 return VersionTuple(Major);
7662 if (Subminor == 0)
7663 return VersionTuple(Major, Minor - 1);
7664 return VersionTuple(Major, Minor - 1, Subminor - 1);
7665}
7666
7667CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7668 const RecordData &Record,
7669 unsigned &Idx) {
7670 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7671 return CXXTemporary::Create(Context, Decl);
7672}
7673
7674DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00007675 return Diag(CurrentImportLoc, DiagID);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007676}
7677
7678DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7679 return Diags.Report(Loc, DiagID);
7680}
7681
7682/// \brief Retrieve the identifier table associated with the
7683/// preprocessor.
7684IdentifierTable &ASTReader::getIdentifierTable() {
7685 return PP.getIdentifierTable();
7686}
7687
7688/// \brief Record that the given ID maps to the given switch-case
7689/// statement.
7690void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7691 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7692 "Already have a SwitchCase with this ID");
7693 (*CurrSwitchCaseStmts)[ID] = SC;
7694}
7695
7696/// \brief Retrieve the switch-case statement with the given ID.
7697SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7698 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7699 return (*CurrSwitchCaseStmts)[ID];
7700}
7701
7702void ASTReader::ClearSwitchCaseIDs() {
7703 CurrSwitchCaseStmts->clear();
7704}
7705
7706void ASTReader::ReadComments() {
7707 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007708 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007709 serialization::ModuleFile *> >::iterator
7710 I = CommentsCursors.begin(),
7711 E = CommentsCursors.end();
7712 I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007713 Comments.clear();
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007714 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007715 serialization::ModuleFile &F = *I->second;
7716 SavedStreamPosition SavedPosition(Cursor);
7717
7718 RecordData Record;
7719 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007720 llvm::BitstreamEntry Entry =
7721 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Stephen Hines651f13c2014-04-23 16:59:28 -07007722
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007723 switch (Entry.Kind) {
7724 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7725 case llvm::BitstreamEntry::Error:
7726 Error("malformed block record in AST file");
7727 return;
7728 case llvm::BitstreamEntry::EndBlock:
7729 goto NextCursor;
7730 case llvm::BitstreamEntry::Record:
7731 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007732 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007733 }
7734
7735 // Read a record.
7736 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007737 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007738 case COMMENTS_RAW_COMMENT: {
7739 unsigned Idx = 0;
7740 SourceRange SR = ReadSourceRange(F, Record, Idx);
7741 RawComment::CommentKind Kind =
7742 (RawComment::CommentKind) Record[Idx++];
7743 bool IsTrailingComment = Record[Idx++];
7744 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00007745 Comments.push_back(new (Context) RawComment(
7746 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7747 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007748 break;
7749 }
7750 }
7751 }
Stephen Hines651f13c2014-04-23 16:59:28 -07007752 NextCursor:
7753 Context.Comments.addDeserializedComments(Comments);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007754 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007755}
7756
7757void ASTReader::finishPendingActions() {
7758 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith3c40a282013-10-18 06:05:18 +00007759 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7760 !PendingOdrMergeChecks.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007761 // If any identifiers with corresponding top-level declarations have
7762 // been loaded, load those declarations now.
Craig Topperee0a4792013-07-05 04:33:53 +00007763 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7764 TopLevelDeclsMap;
7765 TopLevelDeclsMap TopLevelDecls;
7766
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007767 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007768 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Stephen Hines651f13c2014-04-23 16:59:28 -07007769 SmallVector<uint32_t, 4> DeclIDs =
7770 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007771 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007772
7773 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007774 }
Stephen Hines651f13c2014-04-23 16:59:28 -07007775
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007776 // Load pending declaration chains.
7777 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7778 loadPendingDeclChain(PendingDeclChains[I]);
7779 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7780 }
7781 PendingDeclChains.clear();
7782
Douglas Gregoraa945902013-02-18 15:53:43 +00007783 // Make the most recent of the top-level declarations visible.
Craig Topperee0a4792013-07-05 04:33:53 +00007784 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7785 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007786 IdentifierInfo *II = TLD->first;
7787 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007788 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregoraa945902013-02-18 15:53:43 +00007789 }
7790 }
7791
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007792 // Load any pending macro definitions.
7793 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007794 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7795 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7796 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7797 // Initialize the macro history from chained-PCHs ahead of module imports.
Stephen Hines651f13c2014-04-23 16:59:28 -07007798 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007799 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007800 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7801 if (Info.M->Kind != MK_Module)
7802 resolvePendingMacro(II, Info);
7803 }
7804 // Handle module imports.
Stephen Hines651f13c2014-04-23 16:59:28 -07007805 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007806 ++IDIdx) {
7807 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7808 if (Info.M->Kind == MK_Module)
7809 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007810 }
7811 }
7812 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007813
7814 // Wire up the DeclContexts for Decls that we delayed setting until
7815 // recursive loading is completed.
7816 while (!PendingDeclContextInfos.empty()) {
7817 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7818 PendingDeclContextInfos.pop_front();
7819 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7820 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7821 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7822 }
Richard Smith3c40a282013-10-18 06:05:18 +00007823
7824 // For each declaration from a merged context, check that the canonical
7825 // definition of that context also contains a declaration of the same
7826 // entity.
7827 while (!PendingOdrMergeChecks.empty()) {
7828 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7829
7830 // FIXME: Skip over implicit declarations for now. This matters for things
7831 // like implicitly-declared special member functions. This isn't entirely
7832 // correct; we can end up with multiple unmerged declarations of the same
7833 // implicit entity.
7834 if (D->isImplicit())
7835 continue;
7836
7837 DeclContext *CanonDef = D->getDeclContext();
7838 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7839
7840 bool Found = false;
7841 const Decl *DCanon = D->getCanonicalDecl();
7842
7843 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7844 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7845 !Found && I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007846 for (auto RI : (*I)->redecls()) {
7847 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith3c40a282013-10-18 06:05:18 +00007848 // This declaration is present in the canonical definition. If it's
7849 // in the same redecl chain, it's the one we're looking for.
Stephen Hines651f13c2014-04-23 16:59:28 -07007850 if (RI->getCanonicalDecl() == DCanon)
Richard Smith3c40a282013-10-18 06:05:18 +00007851 Found = true;
7852 else
Stephen Hines651f13c2014-04-23 16:59:28 -07007853 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith3c40a282013-10-18 06:05:18 +00007854 break;
7855 }
7856 }
7857 }
7858
7859 if (!Found) {
7860 D->setInvalidDecl();
7861
7862 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7863 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7864 << D << D->getOwningModule()->getFullModuleName()
7865 << CanonDef << !CanonDefModule
7866 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7867
7868 if (Candidates.empty())
7869 Diag(cast<Decl>(CanonDef)->getLocation(),
7870 diag::note_module_odr_violation_no_possible_decls) << D;
7871 else {
7872 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7873 Diag(Candidates[I]->getLocation(),
7874 diag::note_module_odr_violation_possible_decl)
7875 << Candidates[I];
7876 }
7877 }
7878 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007879 }
7880
7881 // If we deserialized any C++ or Objective-C class definitions, any
7882 // Objective-C protocol definitions, or any redeclarable templates, make sure
7883 // that all redeclarations point to the definitions. Note that this can only
7884 // happen now, after the redeclaration chains have been fully wired.
7885 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7886 DEnd = PendingDefinitions.end();
7887 D != DEnd; ++D) {
7888 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7889 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7890 // Make sure that the TagType points at the definition.
7891 const_cast<TagType*>(TagT)->decl = TD;
7892 }
7893
Stephen Hines651f13c2014-04-23 16:59:28 -07007894 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7895 for (auto R : RD->redecls())
7896 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007897
7898 }
7899
7900 continue;
7901 }
7902
Stephen Hines651f13c2014-04-23 16:59:28 -07007903 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007904 // Make sure that the ObjCInterfaceType points at the definition.
7905 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7906 ->Decl = ID;
7907
Stephen Hines651f13c2014-04-23 16:59:28 -07007908 for (auto R : ID->redecls())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007909 R->Data = ID->Data;
7910
7911 continue;
7912 }
7913
Stephen Hines651f13c2014-04-23 16:59:28 -07007914 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7915 for (auto R : PD->redecls())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007916 R->Data = PD->Data;
7917
7918 continue;
7919 }
7920
Stephen Hines651f13c2014-04-23 16:59:28 -07007921 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7922 for (auto R : RTD->redecls())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007923 R->Common = RTD->Common;
7924 }
7925 PendingDefinitions.clear();
7926
7927 // Load the bodies of any functions or methods we've encountered. We do
7928 // this now (delayed) so that we can be sure that the declaration chains
7929 // have been fully wired up.
7930 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7931 PBEnd = PendingBodies.end();
7932 PB != PBEnd; ++PB) {
7933 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7934 // FIXME: Check for =delete/=default?
7935 // FIXME: Complain about ODR violations here?
7936 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7937 FD->setLazyBody(PB->second);
7938 continue;
7939 }
7940
7941 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7942 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7943 MD->setLazyBody(PB->second);
7944 }
7945 PendingBodies.clear();
7946}
7947
7948void ASTReader::FinishedDeserializing() {
7949 assert(NumCurrentElementsDeserializing &&
7950 "FinishedDeserializing not paired with StartedDeserializing");
7951 if (NumCurrentElementsDeserializing == 1) {
7952 // We decrease NumCurrentElementsDeserializing only after pending actions
7953 // are finished, to avoid recursively re-calling finishPendingActions().
7954 finishPendingActions();
7955 }
7956 --NumCurrentElementsDeserializing;
7957
Stephen Hines651f13c2014-04-23 16:59:28 -07007958 if (NumCurrentElementsDeserializing == 0 && Consumer) {
7959 // We are not in recursive loading, so it's safe to pass the "interesting"
7960 // decls to the consumer.
7961 PassInterestingDeclsToConsumer();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007962 }
7963}
7964
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007965void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola87bcee82013-10-19 16:55:03 +00007966 D = D->getMostRecentDecl();
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007967
7968 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7969 SemaObj->TUScope->AddDecl(D);
7970 } else if (SemaObj->TUScope) {
7971 // Adding the decl to IdResolver may have failed because it was already in
7972 // (even though it was not added in scope). If it is already in, make sure
7973 // it gets in the scope as well.
7974 if (std::find(SemaObj->IdResolver.begin(Name),
7975 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7976 SemaObj->TUScope->AddDecl(D);
7977 }
7978}
7979
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007980ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7981 StringRef isysroot, bool DisableValidation,
Stephen Hines651f13c2014-04-23 16:59:28 -07007982 bool AllowASTWithCompilerErrors,
7983 bool AllowConfigurationMismatch,
7984 bool ValidateSystemInputs,
7985 bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007986 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7987 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7988 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7989 Consumer(0), ModuleMgr(PP.getFileManager()),
7990 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007991 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Stephen Hines651f13c2014-04-23 16:59:28 -07007992 AllowConfigurationMismatch(AllowConfigurationMismatch),
7993 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007994 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007995 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7996 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007997 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7998 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7999 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00008000 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8001 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8002 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00008003 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8004 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8005 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8006 PassingDeclsToConsumer(false),
Richard Smithafb90df2013-07-31 00:26:46 +00008007 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00008008{
8009 SourceMgr.setExternalSLocEntrySource(this);
8010}
8011
8012ASTReader::~ASTReader() {
8013 for (DeclContextVisibleUpdatesPending::iterator
8014 I = PendingVisibleUpdates.begin(),
8015 E = PendingVisibleUpdates.end();
8016 I != E; ++I) {
8017 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8018 F = I->second.end();
8019 J != F; ++J)
8020 delete J->first;
8021 }
8022}