blob: 676bd9de58be407d1f3ed294967f9f0aadfe32ae [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2//
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"
26#include "clang/Basic/FileSystemStatCache.h"
27#include "clang/Basic/OnDiskHashTable.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
43#include "clang/Serialization/ModuleManager.h"
44#include "clang/Serialization/SerializationDiagnostic.h"
45#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"
52#include "llvm/Support/system_error.h"
53#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000054#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000055#include <iterator>
56
57using namespace clang;
58using namespace clang::serialization;
59using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000060using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000061
62//===----------------------------------------------------------------------===//
63// PCH validator implementation
64//===----------------------------------------------------------------------===//
65
66ASTReaderListener::~ASTReaderListener() {}
67
68/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
79 if (Diags) \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
82 return true; \
83 }
84
85#define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
87 if (Diags) \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
89 << Description; \
90 return true; \
91 }
92
93#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
95 if (Diags) \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
97 << Description; \
98 return true; \
99 }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
104
105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106 if (Diags)
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
109 return true;
110 }
111
112 return false;
113}
114
115/// \brief Compare the given set of target options against an existing set of
116/// target options.
117///
118/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
119///
120/// \returns true if the target options mis-match, false otherwise.
121static bool checkTargetOptions(const TargetOptions &TargetOpts,
122 const TargetOptions &ExistingTargetOpts,
123 DiagnosticsEngine *Diags) {
124#define CHECK_TARGET_OPT(Field, Name) \
125 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
126 if (Diags) \
127 Diags->Report(diag::err_pch_targetopt_mismatch) \
128 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
129 return true; \
130 }
131
132 CHECK_TARGET_OPT(Triple, "target");
133 CHECK_TARGET_OPT(CPU, "target CPU");
134 CHECK_TARGET_OPT(ABI, "target ABI");
135 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
136 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
137#undef CHECK_TARGET_OPT
138
139 // Compare feature sets.
140 SmallVector<StringRef, 4> ExistingFeatures(
141 ExistingTargetOpts.FeaturesAsWritten.begin(),
142 ExistingTargetOpts.FeaturesAsWritten.end());
143 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
144 TargetOpts.FeaturesAsWritten.end());
145 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
146 std::sort(ReadFeatures.begin(), ReadFeatures.end());
147
148 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
149 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
150 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
151 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
152 ++ExistingIdx;
153 ++ReadIdx;
154 continue;
155 }
156
157 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
158 if (Diags)
159 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
160 << false << ReadFeatures[ReadIdx];
161 return true;
162 }
163
164 if (Diags)
165 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
166 << true << ExistingFeatures[ExistingIdx];
167 return true;
168 }
169
170 if (ExistingIdx < ExistingN) {
171 if (Diags)
172 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
173 << true << ExistingFeatures[ExistingIdx];
174 return true;
175 }
176
177 if (ReadIdx < ReadN) {
178 if (Diags)
179 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
180 << false << ReadFeatures[ReadIdx];
181 return true;
182 }
183
184 return false;
185}
186
187bool
188PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
189 bool Complain) {
190 const LangOptions &ExistingLangOpts = PP.getLangOpts();
191 return checkLanguageOptions(LangOpts, ExistingLangOpts,
192 Complain? &Reader.Diags : 0);
193}
194
195bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
196 bool Complain) {
197 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
198 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
199 Complain? &Reader.Diags : 0);
200}
201
202namespace {
203 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
204 MacroDefinitionsMap;
205}
206
207/// \brief Collect the macro definitions provided by the given preprocessor
208/// options.
209static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
210 MacroDefinitionsMap &Macros,
211 SmallVectorImpl<StringRef> *MacroNames = 0){
212 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
213 StringRef Macro = PPOpts.Macros[I].first;
214 bool IsUndef = PPOpts.Macros[I].second;
215
216 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
217 StringRef MacroName = MacroPair.first;
218 StringRef MacroBody = MacroPair.second;
219
220 // For an #undef'd macro, we only care about the name.
221 if (IsUndef) {
222 if (MacroNames && !Macros.count(MacroName))
223 MacroNames->push_back(MacroName);
224
225 Macros[MacroName] = std::make_pair("", true);
226 continue;
227 }
228
229 // For a #define'd macro, figure out the actual definition.
230 if (MacroName.size() == Macro.size())
231 MacroBody = "1";
232 else {
233 // Note: GCC drops anything following an end-of-line character.
234 StringRef::size_type End = MacroBody.find_first_of("\n\r");
235 MacroBody = MacroBody.substr(0, End);
236 }
237
238 if (MacroNames && !Macros.count(MacroName))
239 MacroNames->push_back(MacroName);
240 Macros[MacroName] = std::make_pair(MacroBody, false);
241 }
242}
243
244/// \brief Check the preprocessor options deserialized from the control block
245/// against the preprocessor options in an existing preprocessor.
246///
247/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
248static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
249 const PreprocessorOptions &ExistingPPOpts,
250 DiagnosticsEngine *Diags,
251 FileManager &FileMgr,
252 std::string &SuggestedPredefines) {
253 // Check macro definitions.
254 MacroDefinitionsMap ASTFileMacros;
255 collectMacroDefinitions(PPOpts, ASTFileMacros);
256 MacroDefinitionsMap ExistingMacros;
257 SmallVector<StringRef, 4> ExistingMacroNames;
258 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
259
260 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
261 // Dig out the macro definition in the existing preprocessor options.
262 StringRef MacroName = ExistingMacroNames[I];
263 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
264
265 // Check whether we know anything about this macro name or not.
266 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
267 = ASTFileMacros.find(MacroName);
268 if (Known == ASTFileMacros.end()) {
269 // FIXME: Check whether this identifier was referenced anywhere in the
270 // AST file. If so, we should reject the AST file. Unfortunately, this
271 // information isn't in the control block. What shall we do about it?
272
273 if (Existing.second) {
274 SuggestedPredefines += "#undef ";
275 SuggestedPredefines += MacroName.str();
276 SuggestedPredefines += '\n';
277 } else {
278 SuggestedPredefines += "#define ";
279 SuggestedPredefines += MacroName.str();
280 SuggestedPredefines += ' ';
281 SuggestedPredefines += Existing.first.str();
282 SuggestedPredefines += '\n';
283 }
284 continue;
285 }
286
287 // If the macro was defined in one but undef'd in the other, we have a
288 // conflict.
289 if (Existing.second != Known->second.second) {
290 if (Diags) {
291 Diags->Report(diag::err_pch_macro_def_undef)
292 << MacroName << Known->second.second;
293 }
294 return true;
295 }
296
297 // If the macro was #undef'd in both, or if the macro bodies are identical,
298 // it's fine.
299 if (Existing.second || Existing.first == Known->second.first)
300 continue;
301
302 // The macro bodies differ; complain.
303 if (Diags) {
304 Diags->Report(diag::err_pch_macro_def_conflict)
305 << MacroName << Known->second.first << Existing.first;
306 }
307 return true;
308 }
309
310 // Check whether we're using predefines.
311 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
312 if (Diags) {
313 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
314 }
315 return true;
316 }
317
318 // Compute the #include and #include_macros lines we need.
319 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
320 StringRef File = ExistingPPOpts.Includes[I];
321 if (File == ExistingPPOpts.ImplicitPCHInclude)
322 continue;
323
324 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
325 != PPOpts.Includes.end())
326 continue;
327
328 SuggestedPredefines += "#include \"";
329 SuggestedPredefines +=
330 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
331 SuggestedPredefines += "\"\n";
332 }
333
334 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
335 StringRef File = ExistingPPOpts.MacroIncludes[I];
336 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
337 File)
338 != PPOpts.MacroIncludes.end())
339 continue;
340
341 SuggestedPredefines += "#__include_macros \"";
342 SuggestedPredefines +=
343 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
344 SuggestedPredefines += "\"\n##\n";
345 }
346
347 return false;
348}
349
350bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
351 bool Complain,
352 std::string &SuggestedPredefines) {
353 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
354
355 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
356 Complain? &Reader.Diags : 0,
357 PP.getFileManager(),
358 SuggestedPredefines);
359}
360
361void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
362 unsigned ID) {
363 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
364 ++NumHeaderInfos;
365}
366
367void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
368 PP.setCounterValue(Value);
369}
370
371//===----------------------------------------------------------------------===//
372// AST reader implementation
373//===----------------------------------------------------------------------===//
374
375void
376ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
377 DeserializationListener = Listener;
378}
379
380
381
382unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
383 return serialization::ComputeHash(Sel);
384}
385
386
387std::pair<unsigned, unsigned>
388ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
389 using namespace clang::io;
390 unsigned KeyLen = ReadUnalignedLE16(d);
391 unsigned DataLen = ReadUnalignedLE16(d);
392 return std::make_pair(KeyLen, DataLen);
393}
394
395ASTSelectorLookupTrait::internal_key_type
396ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
397 using namespace clang::io;
398 SelectorTable &SelTable = Reader.getContext().Selectors;
399 unsigned N = ReadUnalignedLE16(d);
400 IdentifierInfo *FirstII
401 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
402 if (N == 0)
403 return SelTable.getNullarySelector(FirstII);
404 else if (N == 1)
405 return SelTable.getUnarySelector(FirstII);
406
407 SmallVector<IdentifierInfo *, 16> Args;
408 Args.push_back(FirstII);
409 for (unsigned I = 1; I != N; ++I)
410 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
411
412 return SelTable.getSelector(N, Args.data());
413}
414
415ASTSelectorLookupTrait::data_type
416ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
417 unsigned DataLen) {
418 using namespace clang::io;
419
420 data_type Result;
421
422 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
423 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
424 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
425
426 // Load instance methods
427 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
428 if (ObjCMethodDecl *Method
429 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
430 Result.Instance.push_back(Method);
431 }
432
433 // Load factory methods
434 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
435 if (ObjCMethodDecl *Method
436 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
437 Result.Factory.push_back(Method);
438 }
439
440 return Result;
441}
442
443unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
444 return llvm::HashString(StringRef(a.first, a.second));
445}
446
447std::pair<unsigned, unsigned>
448ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
449 using namespace clang::io;
450 unsigned DataLen = ReadUnalignedLE16(d);
451 unsigned KeyLen = ReadUnalignedLE16(d);
452 return std::make_pair(KeyLen, DataLen);
453}
454
455std::pair<const char*, unsigned>
456ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
457 assert(n >= 2 && d[n-1] == '\0');
458 return std::make_pair((const char*) d, n-1);
459}
460
461IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
462 const unsigned char* d,
463 unsigned DataLen) {
464 using namespace clang::io;
465 unsigned RawID = ReadUnalignedLE32(d);
466 bool IsInteresting = RawID & 0x01;
467
468 // Wipe out the "is interesting" bit.
469 RawID = RawID >> 1;
470
471 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
472 if (!IsInteresting) {
473 // For uninteresting identifiers, just build the IdentifierInfo
474 // and associate it with the persistent ID.
475 IdentifierInfo *II = KnownII;
476 if (!II) {
477 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
478 KnownII = II;
479 }
480 Reader.SetIdentifierInfo(ID, II);
481 II->setIsFromAST();
482 Reader.markIdentifierUpToDate(II);
483 return II;
484 }
485
486 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
487 unsigned Bits = ReadUnalignedLE16(d);
488 bool CPlusPlusOperatorKeyword = Bits & 0x01;
489 Bits >>= 1;
490 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
491 Bits >>= 1;
492 bool Poisoned = Bits & 0x01;
493 Bits >>= 1;
494 bool ExtensionToken = Bits & 0x01;
495 Bits >>= 1;
496 bool hadMacroDefinition = Bits & 0x01;
497 Bits >>= 1;
498
499 assert(Bits == 0 && "Extra bits in the identifier?");
500 DataLen -= 8;
501
502 // Build the IdentifierInfo itself and link the identifier ID with
503 // the new IdentifierInfo.
504 IdentifierInfo *II = KnownII;
505 if (!II) {
506 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
507 KnownII = II;
508 }
509 Reader.markIdentifierUpToDate(II);
510 II->setIsFromAST();
511
512 // Set or check the various bits in the IdentifierInfo structure.
513 // Token IDs are read-only.
514 if (HasRevertedTokenIDToIdentifier)
515 II->RevertTokenIDToIdentifier();
516 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
517 assert(II->isExtensionToken() == ExtensionToken &&
518 "Incorrect extension token flag");
519 (void)ExtensionToken;
520 if (Poisoned)
521 II->setIsPoisoned(true);
522 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
523 "Incorrect C++ operator keyword flag");
524 (void)CPlusPlusOperatorKeyword;
525
526 // If this identifier is a macro, deserialize the macro
527 // definition.
528 if (hadMacroDefinition) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000529 SmallVector<MacroID, 4> MacroIDs;
530 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
531 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
532 DataLen -= 4;
533 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000534 DataLen -= 4;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000535 Reader.setIdentifierIsMacro(II, MacroIDs);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 }
537
538 Reader.SetIdentifierInfo(ID, II);
539
540 // Read all of the declarations visible at global scope with this
541 // name.
542 if (DataLen > 0) {
543 SmallVector<uint32_t, 4> DeclIDs;
544 for (; DataLen > 0; DataLen -= 4)
545 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
546 Reader.SetGloballyVisibleDecls(II, DeclIDs);
547 }
548
549 return II;
550}
551
552unsigned
553ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
554 llvm::FoldingSetNodeID ID;
555 ID.AddInteger(Key.Kind);
556
557 switch (Key.Kind) {
558 case DeclarationName::Identifier:
559 case DeclarationName::CXXLiteralOperatorName:
560 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
561 break;
562 case DeclarationName::ObjCZeroArgSelector:
563 case DeclarationName::ObjCOneArgSelector:
564 case DeclarationName::ObjCMultiArgSelector:
565 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
566 break;
567 case DeclarationName::CXXOperatorName:
568 ID.AddInteger((OverloadedOperatorKind)Key.Data);
569 break;
570 case DeclarationName::CXXConstructorName:
571 case DeclarationName::CXXDestructorName:
572 case DeclarationName::CXXConversionFunctionName:
573 case DeclarationName::CXXUsingDirective:
574 break;
575 }
576
577 return ID.ComputeHash();
578}
579
580ASTDeclContextNameLookupTrait::internal_key_type
581ASTDeclContextNameLookupTrait::GetInternalKey(
582 const external_key_type& Name) const {
583 DeclNameKey Key;
584 Key.Kind = Name.getNameKind();
585 switch (Name.getNameKind()) {
586 case DeclarationName::Identifier:
587 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
588 break;
589 case DeclarationName::ObjCZeroArgSelector:
590 case DeclarationName::ObjCOneArgSelector:
591 case DeclarationName::ObjCMultiArgSelector:
592 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
593 break;
594 case DeclarationName::CXXOperatorName:
595 Key.Data = Name.getCXXOverloadedOperator();
596 break;
597 case DeclarationName::CXXLiteralOperatorName:
598 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
599 break;
600 case DeclarationName::CXXConstructorName:
601 case DeclarationName::CXXDestructorName:
602 case DeclarationName::CXXConversionFunctionName:
603 case DeclarationName::CXXUsingDirective:
604 Key.Data = 0;
605 break;
606 }
607
608 return Key;
609}
610
611std::pair<unsigned, unsigned>
612ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
613 using namespace clang::io;
614 unsigned KeyLen = ReadUnalignedLE16(d);
615 unsigned DataLen = ReadUnalignedLE16(d);
616 return std::make_pair(KeyLen, DataLen);
617}
618
619ASTDeclContextNameLookupTrait::internal_key_type
620ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
621 using namespace clang::io;
622
623 DeclNameKey Key;
624 Key.Kind = (DeclarationName::NameKind)*d++;
625 switch (Key.Kind) {
626 case DeclarationName::Identifier:
627 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
628 break;
629 case DeclarationName::ObjCZeroArgSelector:
630 case DeclarationName::ObjCOneArgSelector:
631 case DeclarationName::ObjCMultiArgSelector:
632 Key.Data =
633 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
634 .getAsOpaquePtr();
635 break;
636 case DeclarationName::CXXOperatorName:
637 Key.Data = *d++; // OverloadedOperatorKind
638 break;
639 case DeclarationName::CXXLiteralOperatorName:
640 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
641 break;
642 case DeclarationName::CXXConstructorName:
643 case DeclarationName::CXXDestructorName:
644 case DeclarationName::CXXConversionFunctionName:
645 case DeclarationName::CXXUsingDirective:
646 Key.Data = 0;
647 break;
648 }
649
650 return Key;
651}
652
653ASTDeclContextNameLookupTrait::data_type
654ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
655 const unsigned char* d,
656 unsigned DataLen) {
657 using namespace clang::io;
658 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000659 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
660 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000661 return std::make_pair(Start, Start + NumDecls);
662}
663
664bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000665 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000666 const std::pair<uint64_t, uint64_t> &Offsets,
667 DeclContextInfo &Info) {
668 SavedStreamPosition SavedPosition(Cursor);
669 // First the lexical decls.
670 if (Offsets.first != 0) {
671 Cursor.JumpToBit(Offsets.first);
672
673 RecordData Record;
674 const char *Blob;
675 unsigned BlobLen;
676 unsigned Code = Cursor.ReadCode();
Chris Lattner99a5af02013-01-20 00:00:22 +0000677 unsigned RecCode = Cursor.ReadRecord(Code, Record, Blob, BlobLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000678 if (RecCode != DECL_CONTEXT_LEXICAL) {
679 Error("Expected lexical block");
680 return true;
681 }
682
683 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
684 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
685 }
686
687 // Now the lookup table.
688 if (Offsets.second != 0) {
689 Cursor.JumpToBit(Offsets.second);
690
691 RecordData Record;
692 const char *Blob;
693 unsigned BlobLen;
694 unsigned Code = Cursor.ReadCode();
Chris Lattner99a5af02013-01-20 00:00:22 +0000695 unsigned RecCode = Cursor.ReadRecord(Code, Record, Blob, BlobLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000696 if (RecCode != DECL_CONTEXT_VISIBLE) {
697 Error("Expected visible lookup table block");
698 return true;
699 }
700 Info.NameLookupTableData
701 = ASTDeclContextNameLookupTable::Create(
702 (const unsigned char *)Blob + Record[0],
703 (const unsigned char *)Blob,
704 ASTDeclContextNameLookupTrait(*this, M));
705 }
706
707 return false;
708}
709
710void ASTReader::Error(StringRef Msg) {
711 Error(diag::err_fe_pch_malformed, Msg);
712}
713
714void ASTReader::Error(unsigned DiagID,
715 StringRef Arg1, StringRef Arg2) {
716 if (Diags.isDiagnosticInFlight())
717 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
718 else
719 Diag(DiagID) << Arg1 << Arg2;
720}
721
722//===----------------------------------------------------------------------===//
723// Source Manager Deserialization
724//===----------------------------------------------------------------------===//
725
726/// \brief Read the line table in the source manager block.
727/// \returns true if there was an error.
728bool ASTReader::ParseLineTable(ModuleFile &F,
729 SmallVectorImpl<uint64_t> &Record) {
730 unsigned Idx = 0;
731 LineTableInfo &LineTable = SourceMgr.getLineTable();
732
733 // Parse the file names
734 std::map<int, int> FileIDs;
735 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
736 // Extract the file name
737 unsigned FilenameLen = Record[Idx++];
738 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
739 Idx += FilenameLen;
740 MaybeAddSystemRootToFilename(F, Filename);
741 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
742 }
743
744 // Parse the line entries
745 std::vector<LineEntry> Entries;
746 while (Idx < Record.size()) {
747 int FID = Record[Idx++];
748 assert(FID >= 0 && "Serialized line entries for non-local file.");
749 // Remap FileID from 1-based old view.
750 FID += F.SLocEntryBaseID - 1;
751
752 // Extract the line entries
753 unsigned NumEntries = Record[Idx++];
754 assert(NumEntries && "Numentries is 00000");
755 Entries.clear();
756 Entries.reserve(NumEntries);
757 for (unsigned I = 0; I != NumEntries; ++I) {
758 unsigned FileOffset = Record[Idx++];
759 unsigned LineNo = Record[Idx++];
760 int FilenameID = FileIDs[Record[Idx++]];
761 SrcMgr::CharacteristicKind FileKind
762 = (SrcMgr::CharacteristicKind)Record[Idx++];
763 unsigned IncludeOffset = Record[Idx++];
764 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
765 FileKind, IncludeOffset));
766 }
767 LineTable.AddEntry(FileID::get(FID), Entries);
768 }
769
770 return false;
771}
772
773/// \brief Read a source manager block
774bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
775 using namespace SrcMgr;
776
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000777 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000778
779 // Set the source-location entry cursor to the current position in
780 // the stream. This cursor will be used to read the contents of the
781 // source manager block initially, and then lazily read
782 // source-location entries as needed.
783 SLocEntryCursor = F.Stream;
784
785 // The stream itself is going to skip over the source manager block.
786 if (F.Stream.SkipBlock()) {
787 Error("malformed block record in AST file");
788 return true;
789 }
790
791 // Enter the source manager block.
792 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
793 Error("malformed source manager block record in AST file");
794 return true;
795 }
796
797 RecordData Record;
798 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000799 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
800
801 switch (E.Kind) {
802 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
803 case llvm::BitstreamEntry::Error:
804 Error("malformed block record in AST file");
805 return true;
806 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000807 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000808 case llvm::BitstreamEntry::Record:
809 // The interesting case.
810 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000811 }
Chris Lattner88bde502013-01-19 21:39:22 +0000812
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000813 // Read a record.
814 const char *BlobStart;
815 unsigned BlobLen;
816 Record.clear();
Chris Lattner88bde502013-01-19 21:39:22 +0000817 switch (SLocEntryCursor.ReadRecord(E.ID, Record, BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000818 default: // Default behavior: ignore.
819 break;
820
821 case SM_SLOC_FILE_ENTRY:
822 case SM_SLOC_BUFFER_ENTRY:
823 case SM_SLOC_EXPANSION_ENTRY:
824 // Once we hit one of the source location entries, we're done.
825 return false;
826 }
827 }
828}
829
830/// \brief If a header file is not found at the path that we expect it to be
831/// and the PCH file was moved from its original location, try to resolve the
832/// file by assuming that header+PCH were moved together and the header is in
833/// the same place relative to the PCH.
834static std::string
835resolveFileRelativeToOriginalDir(const std::string &Filename,
836 const std::string &OriginalDir,
837 const std::string &CurrDir) {
838 assert(OriginalDir != CurrDir &&
839 "No point trying to resolve the file if the PCH dir didn't change");
840 using namespace llvm::sys;
841 SmallString<128> filePath(Filename);
842 fs::make_absolute(filePath);
843 assert(path::is_absolute(OriginalDir));
844 SmallString<128> currPCHPath(CurrDir);
845
846 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
847 fileDirE = path::end(path::parent_path(filePath));
848 path::const_iterator origDirI = path::begin(OriginalDir),
849 origDirE = path::end(OriginalDir);
850 // Skip the common path components from filePath and OriginalDir.
851 while (fileDirI != fileDirE && origDirI != origDirE &&
852 *fileDirI == *origDirI) {
853 ++fileDirI;
854 ++origDirI;
855 }
856 for (; origDirI != origDirE; ++origDirI)
857 path::append(currPCHPath, "..");
858 path::append(currPCHPath, fileDirI, fileDirE);
859 path::append(currPCHPath, path::filename(Filename));
860 return currPCHPath.str();
861}
862
863bool ASTReader::ReadSLocEntry(int ID) {
864 if (ID == 0)
865 return false;
866
867 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
868 Error("source location entry ID out-of-range for AST file");
869 return true;
870 }
871
872 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
873 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000874 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000875 unsigned BaseOffset = F->SLocEntryBaseOffset;
876
877 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000878 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
879 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000880 Error("incorrectly-formatted source location entry in AST file");
881 return true;
882 }
Chris Lattner88bde502013-01-19 21:39:22 +0000883
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000884 RecordData Record;
885 const char *BlobStart;
886 unsigned BlobLen;
Chris Lattner88bde502013-01-19 21:39:22 +0000887 switch (SLocEntryCursor.ReadRecord(Entry.ID, Record, BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000888 default:
889 Error("incorrectly-formatted source location entry in AST file");
890 return true;
891
892 case SM_SLOC_FILE_ENTRY: {
893 // We will detect whether a file changed and return 'Failure' for it, but
894 // we will also try to fail gracefully by setting up the SLocEntry.
895 unsigned InputID = Record[4];
896 InputFile IF = getInputFile(*F, InputID);
897 const FileEntry *File = IF.getPointer();
898 bool OverriddenBuffer = IF.getInt();
899
900 if (!IF.getPointer())
901 return true;
902
903 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
904 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
905 // This is the module's main file.
906 IncludeLoc = getImportLocation(F);
907 }
908 SrcMgr::CharacteristicKind
909 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
910 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
911 ID, BaseOffset + Record[0]);
912 SrcMgr::FileInfo &FileInfo =
913 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
914 FileInfo.NumCreatedFIDs = Record[5];
915 if (Record[3])
916 FileInfo.setHasLineDirectives();
917
918 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
919 unsigned NumFileDecls = Record[7];
920 if (NumFileDecls) {
921 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
922 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
923 NumFileDecls));
924 }
925
926 const SrcMgr::ContentCache *ContentCache
927 = SourceMgr.getOrCreateContentCache(File,
928 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
929 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
930 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
931 unsigned Code = SLocEntryCursor.ReadCode();
932 Record.clear();
933 unsigned RecCode
Chris Lattner99a5af02013-01-20 00:00:22 +0000934 = SLocEntryCursor.ReadRecord(Code, Record, BlobStart, BlobLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935
936 if (RecCode != SM_SLOC_BUFFER_BLOB) {
937 Error("AST record has invalid code");
938 return true;
939 }
940
941 llvm::MemoryBuffer *Buffer
942 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
943 File->getName());
944 SourceMgr.overrideFileContents(File, Buffer);
945 }
946
947 break;
948 }
949
950 case SM_SLOC_BUFFER_ENTRY: {
951 const char *Name = BlobStart;
952 unsigned Offset = Record[0];
953 SrcMgr::CharacteristicKind
954 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
955 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
956 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
957 IncludeLoc = getImportLocation(F);
958 }
959 unsigned Code = SLocEntryCursor.ReadCode();
960 Record.clear();
961 unsigned RecCode
Chris Lattner99a5af02013-01-20 00:00:22 +0000962 = SLocEntryCursor.ReadRecord(Code, Record, BlobStart, BlobLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000963
964 if (RecCode != SM_SLOC_BUFFER_BLOB) {
965 Error("AST record has invalid code");
966 return true;
967 }
968
969 llvm::MemoryBuffer *Buffer
970 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
971 Name);
972 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
973 BaseOffset + Offset, IncludeLoc);
974 break;
975 }
976
977 case SM_SLOC_EXPANSION_ENTRY: {
978 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
979 SourceMgr.createExpansionLoc(SpellingLoc,
980 ReadSourceLocation(*F, Record[2]),
981 ReadSourceLocation(*F, Record[3]),
982 Record[4],
983 ID,
984 BaseOffset + Record[0]);
985 break;
986 }
987 }
988
989 return false;
990}
991
992std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
993 if (ID == 0)
994 return std::make_pair(SourceLocation(), "");
995
996 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
997 Error("source location entry ID out-of-range for AST file");
998 return std::make_pair(SourceLocation(), "");
999 }
1000
1001 // Find which module file this entry lands in.
1002 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1003 if (M->Kind != MK_Module)
1004 return std::make_pair(SourceLocation(), "");
1005
1006 // FIXME: Can we map this down to a particular submodule? That would be
1007 // ideal.
1008 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1009}
1010
1011/// \brief Find the location where the module F is imported.
1012SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1013 if (F->ImportLoc.isValid())
1014 return F->ImportLoc;
1015
1016 // Otherwise we have a PCH. It's considered to be "imported" at the first
1017 // location of its includer.
1018 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1019 // Main file is the importer. We assume that it is the first entry in the
1020 // entry table. We can't ask the manager, because at the time of PCH loading
1021 // the main file entry doesn't exist yet.
1022 // The very first entry is the invalid instantiation loc, which takes up
1023 // offsets 0 and 1.
1024 return SourceLocation::getFromRawEncoding(2U);
1025 }
1026 //return F->Loaders[0]->FirstLoc;
1027 return F->ImportedBy[0]->FirstLoc;
1028}
1029
1030/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1031/// specified cursor. Read the abbreviations that are at the top of the block
1032/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001033bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001034 if (Cursor.EnterSubBlock(BlockID)) {
1035 Error("malformed block record in AST file");
1036 return Failure;
1037 }
1038
1039 while (true) {
1040 uint64_t Offset = Cursor.GetCurrentBitNo();
1041 unsigned Code = Cursor.ReadCode();
1042
1043 // We expect all abbrevs to be at the start of the block.
1044 if (Code != llvm::bitc::DEFINE_ABBREV) {
1045 Cursor.JumpToBit(Offset);
1046 return false;
1047 }
1048 Cursor.ReadAbbrevRecord();
1049 }
1050}
1051
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001052void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
1053 MacroInfo *Hint) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001054 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001055
1056 // Keep track of where we are in the stream, then jump back there
1057 // after reading this macro.
1058 SavedStreamPosition SavedPosition(Stream);
1059
1060 Stream.JumpToBit(Offset);
1061 RecordData Record;
1062 SmallVector<IdentifierInfo*, 16> MacroArgs;
1063 MacroInfo *Macro = 0;
1064
Douglas Gregord3b036e2013-01-18 04:34:14 +00001065 // RAII object to add the loaded macro information once we're done
1066 // adding tokens.
1067 struct AddLoadedMacroInfoRAII {
1068 Preprocessor &PP;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001069 MacroInfo *Hint;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001070 MacroInfo *MI;
1071 IdentifierInfo *II;
1072
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001073 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroInfo *Hint)
1074 : PP(PP), Hint(Hint), MI(), II() { }
Douglas Gregord3b036e2013-01-18 04:34:14 +00001075 ~AddLoadedMacroInfoRAII( ) {
1076 if (MI) {
1077 // Finally, install the macro.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001078 PP.addLoadedMacroInfo(II, MI, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001079 }
1080 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001081 } AddLoadedMacroInfo(PP, Hint);
Douglas Gregord3b036e2013-01-18 04:34:14 +00001082
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001083 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001084 // Advance to the next record, but if we get to the end of the block, don't
1085 // pop it (removing all the abbreviations from the cursor) since we want to
1086 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001087 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001088 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1089
1090 switch (Entry.Kind) {
1091 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1092 case llvm::BitstreamEntry::Error:
1093 Error("malformed block record in AST file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 return;
Chris Lattner99a5af02013-01-20 00:00:22 +00001095 case llvm::BitstreamEntry::EndBlock:
1096 return;
1097 case llvm::BitstreamEntry::Record:
1098 // The interesting case.
1099 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001100 }
1101
1102 // Read a record.
1103 const char *BlobStart = 0;
1104 unsigned BlobLen = 0;
1105 Record.clear();
1106 PreprocessorRecordTypes RecType =
Chris Lattner99a5af02013-01-20 00:00:22 +00001107 (PreprocessorRecordTypes)Stream.ReadRecord(Entry.ID, Record, BlobStart,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001108 BlobLen);
1109 switch (RecType) {
1110 case PP_MACRO_OBJECT_LIKE:
1111 case PP_MACRO_FUNCTION_LIKE: {
1112 // If we already have a macro, that means that we've hit the end
1113 // of the definition of the macro we were looking for. We're
1114 // done.
1115 if (Macro)
1116 return;
1117
1118 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1119 if (II == 0) {
1120 Error("macro must have a name in AST file");
1121 return;
1122 }
1123
1124 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1125
1126 // If this macro has already been loaded, don't do so again.
1127 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1128 return;
1129
1130 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1131 unsigned NextIndex = 3;
1132 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1133 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001134 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001135
1136 // Record this macro.
1137 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MI;
1138
1139 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1140 if (UndefLoc.isValid())
1141 MI->setUndefLoc(UndefLoc);
1142
1143 MI->setIsUsed(Record[NextIndex++]);
1144 MI->setIsFromAST();
1145
1146 bool IsPublic = Record[NextIndex++];
1147 MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
1148
1149 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1150 // Decode function-like macro info.
1151 bool isC99VarArgs = Record[NextIndex++];
1152 bool isGNUVarArgs = Record[NextIndex++];
1153 bool hasCommaPasting = Record[NextIndex++];
1154 MacroArgs.clear();
1155 unsigned NumArgs = Record[NextIndex++];
1156 for (unsigned i = 0; i != NumArgs; ++i)
1157 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1158
1159 // Install function-like macro info.
1160 MI->setIsFunctionLike();
1161 if (isC99VarArgs) MI->setIsC99Varargs();
1162 if (isGNUVarArgs) MI->setIsGNUVarargs();
1163 if (hasCommaPasting) MI->setHasCommaPasting();
1164 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1165 PP.getPreprocessorAllocator());
1166 }
1167
1168 if (DeserializationListener)
1169 DeserializationListener->MacroRead(GlobalID, MI);
1170
1171 // If an update record marked this as undefined, do so now.
1172 // FIXME: Only if the submodule this update came from is visible?
1173 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1174 if (Update != MacroUpdates.end()) {
1175 if (MI->getUndefLoc().isInvalid()) {
1176 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1177 bool Hidden = false;
1178 if (unsigned SubmoduleID = Update->second[I].first) {
1179 if (Module *Owner = getSubmodule(SubmoduleID)) {
1180 if (Owner->NameVisibility == Module::Hidden) {
1181 // Note that this #undef is hidden.
1182 Hidden = true;
1183
1184 // Record this hiding for later.
1185 HiddenNamesMap[Owner].push_back(
1186 HiddenName(II, MI, Update->second[I].second.UndefLoc));
1187 }
1188 }
1189 }
1190
1191 if (!Hidden) {
1192 MI->setUndefLoc(Update->second[I].second.UndefLoc);
1193 if (PPMutationListener *Listener = PP.getPPMutationListener())
1194 Listener->UndefinedMacro(MI);
1195 break;
1196 }
1197 }
1198 }
1199 MacroUpdates.erase(Update);
1200 }
1201
1202 // Determine whether this macro definition is visible.
1203 bool Hidden = !MI->isPublic();
1204 if (!Hidden && GlobalSubmoduleID) {
1205 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1206 if (Owner->NameVisibility == Module::Hidden) {
1207 // The owning module is not visible, and this macro definition
1208 // should not be, either.
1209 Hidden = true;
1210
1211 // Note that this macro definition was hidden because its owning
1212 // module is not yet visible.
1213 HiddenNamesMap[Owner].push_back(HiddenName(II, MI));
1214 }
1215 }
1216 }
1217 MI->setHidden(Hidden);
1218
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001219 // Make sure we install the macro once we're done.
1220 AddLoadedMacroInfo.MI = MI;
1221 AddLoadedMacroInfo.II = II;
Douglas Gregord3b036e2013-01-18 04:34:14 +00001222
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001223 // Remember that we saw this macro last so that we add the tokens that
1224 // form its body to it.
1225 Macro = MI;
1226
1227 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1228 Record[NextIndex]) {
1229 // We have a macro definition. Register the association
1230 PreprocessedEntityID
1231 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1232 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1233 PPRec.RegisterMacroDefinition(Macro,
1234 PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
1235 }
1236
1237 ++NumMacrosRead;
1238 break;
1239 }
1240
1241 case PP_TOKEN: {
1242 // If we see a TOKEN before a PP_MACRO_*, then the file is
1243 // erroneous, just pretend we didn't see this.
1244 if (Macro == 0) break;
1245
1246 Token Tok;
1247 Tok.startToken();
1248 Tok.setLocation(ReadSourceLocation(F, Record[0]));
1249 Tok.setLength(Record[1]);
1250 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1251 Tok.setIdentifierInfo(II);
1252 Tok.setKind((tok::TokenKind)Record[3]);
1253 Tok.setFlag((Token::TokenFlags)Record[4]);
1254 Macro->AddTokenToBody(Tok);
1255 break;
1256 }
1257 }
1258 }
1259}
1260
1261PreprocessedEntityID
1262ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1263 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1264 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1265 assert(I != M.PreprocessedEntityRemap.end()
1266 && "Invalid index into preprocessed entity index remap");
1267
1268 return LocalID + I->second;
1269}
1270
1271unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1272 return llvm::HashString(llvm::sys::path::filename(path));
1273}
1274
1275HeaderFileInfoTrait::internal_key_type
1276HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1277
1278bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1279 if (strcmp(a, b) == 0)
1280 return true;
1281
1282 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1283 return false;
1284
1285 // Determine whether the actual files are equivalent.
1286 bool Result = false;
1287 if (llvm::sys::fs::equivalent(a, b, Result))
1288 return false;
1289
1290 return Result;
1291}
1292
1293std::pair<unsigned, unsigned>
1294HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1295 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1296 unsigned DataLen = (unsigned) *d++;
1297 return std::make_pair(KeyLen + 1, DataLen);
1298}
1299
1300HeaderFileInfoTrait::data_type
1301HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1302 unsigned DataLen) {
1303 const unsigned char *End = d + DataLen;
1304 using namespace clang::io;
1305 HeaderFileInfo HFI;
1306 unsigned Flags = *d++;
1307 HFI.isImport = (Flags >> 5) & 0x01;
1308 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1309 HFI.DirInfo = (Flags >> 2) & 0x03;
1310 HFI.Resolved = (Flags >> 1) & 0x01;
1311 HFI.IndexHeaderMapHeader = Flags & 0x01;
1312 HFI.NumIncludes = ReadUnalignedLE16(d);
1313 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1314 ReadUnalignedLE32(d));
1315 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1316 // The framework offset is 1 greater than the actual offset,
1317 // since 0 is used as an indicator for "no framework name".
1318 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1319 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1320 }
1321
1322 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1323 (void)End;
1324
1325 // This HeaderFileInfo was externally loaded.
1326 HFI.External = true;
1327 return HFI;
1328}
1329
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001330void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001331 II->setHadMacroDefinition(true);
1332 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00001333 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001334}
1335
1336void ASTReader::ReadDefinedMacros() {
1337 // Note that we are loading defined macros.
1338 Deserializing Macros(this);
1339
1340 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1341 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001342 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001343
1344 // If there was no preprocessor block, skip this file.
1345 if (!MacroCursor.getBitStreamReader())
1346 continue;
1347
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001348 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001349 Cursor.JumpToBit((*I)->MacroStartOffset);
1350
1351 RecordData Record;
1352 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001353 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1354
1355 switch (E.Kind) {
1356 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1357 case llvm::BitstreamEntry::Error:
1358 Error("malformed block record in AST file");
1359 return;
1360 case llvm::BitstreamEntry::EndBlock:
1361 goto NextCursor;
1362
1363 case llvm::BitstreamEntry::Record:
1364 const char *BlobStart;
1365 unsigned BlobLen;
1366 Record.clear();
1367 switch (Cursor.ReadRecord(E.ID, Record, BlobStart, BlobLen)) {
1368 default: // Default behavior: ignore.
1369 break;
1370
1371 case PP_MACRO_OBJECT_LIKE:
1372 case PP_MACRO_FUNCTION_LIKE:
1373 getLocalIdentifier(**I, Record[0]);
1374 break;
1375
1376 case PP_TOKEN:
1377 // Ignore tokens.
1378 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001380 break;
1381 }
1382 }
Chris Lattner88bde502013-01-19 21:39:22 +00001383 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001384 }
1385}
1386
1387namespace {
1388 /// \brief Visitor class used to look up identifirs in an AST file.
1389 class IdentifierLookupVisitor {
1390 StringRef Name;
1391 unsigned PriorGeneration;
1392 IdentifierInfo *Found;
1393 public:
1394 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)
1395 : Name(Name), PriorGeneration(PriorGeneration), Found() { }
1396
1397 static bool visit(ModuleFile &M, void *UserData) {
1398 IdentifierLookupVisitor *This
1399 = static_cast<IdentifierLookupVisitor *>(UserData);
1400
1401 // If we've already searched this module file, skip it now.
1402 if (M.Generation <= This->PriorGeneration)
1403 return true;
1404
1405 ASTIdentifierLookupTable *IdTable
1406 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1407 if (!IdTable)
1408 return false;
1409
1410 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1411 M, This->Found);
1412
1413 std::pair<const char*, unsigned> Key(This->Name.begin(),
1414 This->Name.size());
1415 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
1416 if (Pos == IdTable->end())
1417 return false;
1418
1419 // Dereferencing the iterator has the effect of building the
1420 // IdentifierInfo node and populating it with the various
1421 // declarations it needs.
1422 This->Found = *Pos;
1423 return true;
1424 }
1425
1426 // \brief Retrieve the identifier info found within the module
1427 // files.
1428 IdentifierInfo *getIdentifierInfo() const { return Found; }
1429 };
1430}
1431
1432void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1433 // Note that we are loading an identifier.
1434 Deserializing AnIdentifier(this);
1435
1436 unsigned PriorGeneration = 0;
1437 if (getContext().getLangOpts().Modules)
1438 PriorGeneration = IdentifierGeneration[&II];
1439
1440 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
1441 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
1442 markIdentifierUpToDate(&II);
1443}
1444
1445void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1446 if (!II)
1447 return;
1448
1449 II->setOutOfDate(false);
1450
1451 // Update the generation for this identifier.
1452 if (getContext().getLangOpts().Modules)
1453 IdentifierGeneration[II] = CurrentGeneration;
1454}
1455
1456llvm::PointerIntPair<const FileEntry *, 1, bool>
1457ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1458 // If this ID is bogus, just return an empty input file.
1459 if (ID == 0 || ID > F.InputFilesLoaded.size())
1460 return InputFile();
1461
1462 // If we've already loaded this input file, return it.
1463 if (F.InputFilesLoaded[ID-1].getPointer())
1464 return F.InputFilesLoaded[ID-1];
1465
1466 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001467 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001468 SavedStreamPosition SavedPosition(Cursor);
1469 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1470
1471 unsigned Code = Cursor.ReadCode();
1472 RecordData Record;
1473 const char *BlobStart = 0;
1474 unsigned BlobLen = 0;
1475 switch ((InputFileRecordTypes)Cursor.ReadRecord(Code, Record,
Chris Lattner88bde502013-01-19 21:39:22 +00001476 BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001477 case INPUT_FILE: {
1478 unsigned StoredID = Record[0];
1479 assert(ID == StoredID && "Bogus stored ID or offset");
1480 (void)StoredID;
1481 off_t StoredSize = (off_t)Record[1];
1482 time_t StoredTime = (time_t)Record[2];
1483 bool Overridden = (bool)Record[3];
1484
1485 // Get the file entry for this input file.
1486 StringRef OrigFilename(BlobStart, BlobLen);
1487 std::string Filename = OrigFilename;
1488 MaybeAddSystemRootToFilename(F, Filename);
1489 const FileEntry *File
1490 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1491 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1492
1493 // If we didn't find the file, resolve it relative to the
1494 // original directory from which this AST file was created.
1495 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1496 F.OriginalDir != CurrentDir) {
1497 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1498 F.OriginalDir,
1499 CurrentDir);
1500 if (!Resolved.empty())
1501 File = FileMgr.getFile(Resolved);
1502 }
1503
1504 // For an overridden file, create a virtual file with the stored
1505 // size/timestamp.
1506 if (Overridden && File == 0) {
1507 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1508 }
1509
1510 if (File == 0) {
1511 if (Complain) {
1512 std::string ErrorStr = "could not find file '";
1513 ErrorStr += Filename;
1514 ErrorStr += "' referenced by AST file";
1515 Error(ErrorStr.c_str());
1516 }
1517 return InputFile();
1518 }
1519
1520 // Note that we've loaded this input file.
1521 F.InputFilesLoaded[ID-1] = InputFile(File, Overridden);
1522
1523 // Check if there was a request to override the contents of the file
1524 // that was part of the precompiled header. Overridding such a file
1525 // can lead to problems when lexing using the source locations from the
1526 // PCH.
1527 SourceManager &SM = getSourceManager();
1528 if (!Overridden && SM.isFileOverridden(File)) {
1529 Error(diag::err_fe_pch_file_overridden, Filename);
1530 // After emitting the diagnostic, recover by disabling the override so
1531 // that the original file will be used.
1532 SM.disableFileContentsOverride(File);
1533 // The FileEntry is a virtual file entry with the size of the contents
1534 // that would override the original contents. Set it to the original's
1535 // size/time.
1536 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1537 StoredSize, StoredTime);
1538 }
1539
1540 // For an overridden file, there is nothing to validate.
1541 if (Overridden)
1542 return InputFile(File, Overridden);
1543
1544 if ((StoredSize != File->getSize()
1545#if !defined(LLVM_ON_WIN32)
1546 // In our regression testing, the Windows file system seems to
1547 // have inconsistent modification times that sometimes
1548 // erroneously trigger this error-handling path.
1549 || StoredTime != File->getModificationTime()
1550#endif
1551 )) {
1552 if (Complain)
1553 Error(diag::err_fe_pch_file_modified, Filename);
1554
1555 return InputFile();
1556 }
1557
1558 return InputFile(File, Overridden);
1559 }
1560 }
1561
1562 return InputFile();
1563}
1564
1565const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1566 ModuleFile &M = ModuleMgr.getPrimaryModule();
1567 std::string Filename = filenameStrRef;
1568 MaybeAddSystemRootToFilename(M, Filename);
1569 const FileEntry *File = FileMgr.getFile(Filename);
1570 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1571 M.OriginalDir != CurrentDir) {
1572 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1573 M.OriginalDir,
1574 CurrentDir);
1575 if (!resolved.empty())
1576 File = FileMgr.getFile(resolved);
1577 }
1578
1579 return File;
1580}
1581
1582/// \brief If we are loading a relocatable PCH file, and the filename is
1583/// not an absolute path, add the system root to the beginning of the file
1584/// name.
1585void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1586 std::string &Filename) {
1587 // If this is not a relocatable PCH file, there's nothing to do.
1588 if (!M.RelocatablePCH)
1589 return;
1590
1591 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1592 return;
1593
1594 if (isysroot.empty()) {
1595 // If no system root was given, default to '/'
1596 Filename.insert(Filename.begin(), '/');
1597 return;
1598 }
1599
1600 unsigned Length = isysroot.size();
1601 if (isysroot[Length - 1] != '/')
1602 Filename.insert(Filename.begin(), '/');
1603
1604 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1605}
1606
1607ASTReader::ASTReadResult
1608ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001609 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001610 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001611 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001612
1613 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1614 Error("malformed block record in AST file");
1615 return Failure;
1616 }
1617
1618 // Read all of the records and blocks in the control block.
1619 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001620 while (1) {
1621 llvm::BitstreamEntry Entry = Stream.advance();
1622
1623 switch (Entry.Kind) {
1624 case llvm::BitstreamEntry::Error:
1625 Error("malformed block record in AST file");
1626 return Failure;
1627 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001628 // Validate all of the input files.
1629 if (!DisableValidation) {
1630 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
1631 for (unsigned I = 0, N = Record[0]; I < N; ++I)
1632 if (!getInputFile(F, I+1, Complain).getPointer())
1633 return OutOfDate;
1634 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001635 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001636
1637 case llvm::BitstreamEntry::SubBlock:
1638 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 case INPUT_FILES_BLOCK_ID:
1640 F.InputFilesCursor = Stream;
1641 if (Stream.SkipBlock() || // Skip with the main cursor
1642 // Read the abbreviations
1643 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1644 Error("malformed block record in AST file");
1645 return Failure;
1646 }
1647 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001648
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001649 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001650 if (Stream.SkipBlock()) {
1651 Error("malformed block record in AST file");
1652 return Failure;
1653 }
1654 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001655 }
Chris Lattner88bde502013-01-19 21:39:22 +00001656
1657 case llvm::BitstreamEntry::Record:
1658 // The interesting case.
1659 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660 }
1661
1662 // Read and process a record.
1663 Record.clear();
1664 const char *BlobStart = 0;
1665 unsigned BlobLen = 0;
Chris Lattner88bde502013-01-19 21:39:22 +00001666 switch ((ControlRecordTypes)Stream.ReadRecord(Entry.ID, Record,
1667 BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001668 case METADATA: {
1669 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1670 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1671 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1672 : diag::warn_pch_version_too_new);
1673 return VersionMismatch;
1674 }
1675
1676 bool hasErrors = Record[5];
1677 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1678 Diag(diag::err_pch_with_compiler_errors);
1679 return HadErrors;
1680 }
1681
1682 F.RelocatablePCH = Record[4];
1683
1684 const std::string &CurBranch = getClangFullRepositoryVersion();
1685 StringRef ASTBranch(BlobStart, BlobLen);
1686 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1687 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1688 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1689 return VersionMismatch;
1690 }
1691 break;
1692 }
1693
1694 case IMPORTS: {
1695 // Load each of the imported PCH files.
1696 unsigned Idx = 0, N = Record.size();
1697 while (Idx < N) {
1698 // Read information about the AST file.
1699 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1700 // The import location will be the local one for now; we will adjust
1701 // all import locations of module imports after the global source
1702 // location info are setup.
1703 SourceLocation ImportLoc =
1704 SourceLocation::getFromRawEncoding(Record[Idx++]);
1705 unsigned Length = Record[Idx++];
1706 SmallString<128> ImportedFile(Record.begin() + Idx,
1707 Record.begin() + Idx + Length);
1708 Idx += Length;
1709
1710 // Load the AST file.
1711 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
1712 ClientLoadCapabilities)) {
1713 case Failure: return Failure;
1714 // If we have to ignore the dependency, we'll have to ignore this too.
1715 case OutOfDate: return OutOfDate;
1716 case VersionMismatch: return VersionMismatch;
1717 case ConfigurationMismatch: return ConfigurationMismatch;
1718 case HadErrors: return HadErrors;
1719 case Success: break;
1720 }
1721 }
1722 break;
1723 }
1724
1725 case LANGUAGE_OPTIONS: {
1726 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1727 if (Listener && &F == *ModuleMgr.begin() &&
1728 ParseLanguageOptions(Record, Complain, *Listener) &&
1729 !DisableValidation)
1730 return ConfigurationMismatch;
1731 break;
1732 }
1733
1734 case TARGET_OPTIONS: {
1735 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1736 if (Listener && &F == *ModuleMgr.begin() &&
1737 ParseTargetOptions(Record, Complain, *Listener) &&
1738 !DisableValidation)
1739 return ConfigurationMismatch;
1740 break;
1741 }
1742
1743 case DIAGNOSTIC_OPTIONS: {
1744 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1745 if (Listener && &F == *ModuleMgr.begin() &&
1746 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1747 !DisableValidation)
1748 return ConfigurationMismatch;
1749 break;
1750 }
1751
1752 case FILE_SYSTEM_OPTIONS: {
1753 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1754 if (Listener && &F == *ModuleMgr.begin() &&
1755 ParseFileSystemOptions(Record, Complain, *Listener) &&
1756 !DisableValidation)
1757 return ConfigurationMismatch;
1758 break;
1759 }
1760
1761 case HEADER_SEARCH_OPTIONS: {
1762 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1763 if (Listener && &F == *ModuleMgr.begin() &&
1764 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1765 !DisableValidation)
1766 return ConfigurationMismatch;
1767 break;
1768 }
1769
1770 case PREPROCESSOR_OPTIONS: {
1771 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1772 if (Listener && &F == *ModuleMgr.begin() &&
1773 ParsePreprocessorOptions(Record, Complain, *Listener,
1774 SuggestedPredefines) &&
1775 !DisableValidation)
1776 return ConfigurationMismatch;
1777 break;
1778 }
1779
1780 case ORIGINAL_FILE:
1781 F.OriginalSourceFileID = FileID::get(Record[0]);
1782 F.ActualOriginalSourceFileName.assign(BlobStart, BlobLen);
1783 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1784 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1785 break;
1786
1787 case ORIGINAL_FILE_ID:
1788 F.OriginalSourceFileID = FileID::get(Record[0]);
1789 break;
1790
1791 case ORIGINAL_PCH_DIR:
1792 F.OriginalDir.assign(BlobStart, BlobLen);
1793 break;
1794
1795 case INPUT_FILE_OFFSETS:
1796 F.InputFileOffsets = (const uint32_t *)BlobStart;
1797 F.InputFilesLoaded.resize(Record[0]);
1798 break;
1799 }
1800 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001801}
1802
1803bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001804 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001805
1806 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1807 Error("malformed block record in AST file");
1808 return true;
1809 }
1810
1811 // Read all of the records and blocks for the AST file.
1812 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001813 while (1) {
1814 llvm::BitstreamEntry Entry = Stream.advance();
1815
1816 switch (Entry.Kind) {
1817 case llvm::BitstreamEntry::Error:
1818 Error("error at end of module block in AST file");
1819 return true;
1820 case llvm::BitstreamEntry::EndBlock: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001821 DeclContext *DC = Context.getTranslationUnitDecl();
1822 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
1823 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00001824
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001825 return false;
1826 }
Chris Lattner88bde502013-01-19 21:39:22 +00001827 case llvm::BitstreamEntry::SubBlock:
1828 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001829 case DECLTYPES_BLOCK_ID:
1830 // We lazily load the decls block, but we want to set up the
1831 // DeclsCursor cursor to point into it. Clone our current bitcode
1832 // cursor to it, enter the block and read the abbrevs in that block.
1833 // With the main cursor, we just skip over it.
1834 F.DeclsCursor = Stream;
1835 if (Stream.SkipBlock() || // Skip with the main cursor.
1836 // Read the abbrevs.
1837 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1838 Error("malformed block record in AST file");
1839 return true;
1840 }
1841 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001842
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843 case DECL_UPDATES_BLOCK_ID:
1844 if (Stream.SkipBlock()) {
1845 Error("malformed block record in AST file");
1846 return true;
1847 }
1848 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001849
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001850 case PREPROCESSOR_BLOCK_ID:
1851 F.MacroCursor = Stream;
1852 if (!PP.getExternalSource())
1853 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00001854
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001855 if (Stream.SkipBlock() ||
1856 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1857 Error("malformed block record in AST file");
1858 return true;
1859 }
1860 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1861 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001862
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863 case PREPROCESSOR_DETAIL_BLOCK_ID:
1864 F.PreprocessorDetailCursor = Stream;
1865 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00001866 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001867 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001868 Error("malformed preprocessor detail record in AST file");
1869 return true;
1870 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00001872 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1873
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001874 if (!PP.getPreprocessingRecord())
1875 PP.createPreprocessingRecord();
1876 if (!PP.getPreprocessingRecord()->getExternalSource())
1877 PP.getPreprocessingRecord()->SetExternalSource(*this);
1878 break;
1879
1880 case SOURCE_MANAGER_BLOCK_ID:
1881 if (ReadSourceManagerBlock(F))
1882 return true;
1883 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001884
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001885 case SUBMODULE_BLOCK_ID:
1886 if (ReadSubmoduleBlock(F))
1887 return true;
1888 break;
Chris Lattner88bde502013-01-19 21:39:22 +00001889
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001890 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001891 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 if (Stream.SkipBlock() ||
1893 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
1894 Error("malformed comments block in AST file");
1895 return true;
1896 }
1897 CommentsCursors.push_back(std::make_pair(C, &F));
1898 break;
1899 }
Chris Lattner88bde502013-01-19 21:39:22 +00001900
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001901 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001902 if (Stream.SkipBlock()) {
1903 Error("malformed block record in AST file");
1904 return true;
1905 }
1906 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001907 }
1908 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001909
1910 case llvm::BitstreamEntry::Record:
1911 // The interesting case.
1912 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001913 }
1914
1915 // Read and process a record.
1916 Record.clear();
1917 const char *BlobStart = 0;
1918 unsigned BlobLen = 0;
Chris Lattner88bde502013-01-19 21:39:22 +00001919 switch ((ASTRecordTypes)Stream.ReadRecord(Entry.ID, Record,
1920 BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001921 default: // Default behavior: ignore.
1922 break;
1923
1924 case TYPE_OFFSET: {
1925 if (F.LocalNumTypes != 0) {
1926 Error("duplicate TYPE_OFFSET record in AST file");
1927 return true;
1928 }
1929 F.TypeOffsets = (const uint32_t *)BlobStart;
1930 F.LocalNumTypes = Record[0];
1931 unsigned LocalBaseTypeIndex = Record[1];
1932 F.BaseTypeIndex = getTotalNumTypes();
1933
1934 if (F.LocalNumTypes > 0) {
1935 // Introduce the global -> local mapping for types within this module.
1936 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1937
1938 // Introduce the local -> global mapping for types within this module.
1939 F.TypeRemap.insertOrReplace(
1940 std::make_pair(LocalBaseTypeIndex,
1941 F.BaseTypeIndex - LocalBaseTypeIndex));
1942
1943 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1944 }
1945 break;
1946 }
1947
1948 case DECL_OFFSET: {
1949 if (F.LocalNumDecls != 0) {
1950 Error("duplicate DECL_OFFSET record in AST file");
1951 return true;
1952 }
1953 F.DeclOffsets = (const DeclOffset *)BlobStart;
1954 F.LocalNumDecls = Record[0];
1955 unsigned LocalBaseDeclID = Record[1];
1956 F.BaseDeclID = getTotalNumDecls();
1957
1958 if (F.LocalNumDecls > 0) {
1959 // Introduce the global -> local mapping for declarations within this
1960 // module.
1961 GlobalDeclMap.insert(
1962 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
1963
1964 // Introduce the local -> global mapping for declarations within this
1965 // module.
1966 F.DeclRemap.insertOrReplace(
1967 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
1968
1969 // Introduce the global -> local mapping for declarations within this
1970 // module.
1971 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
1972
1973 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
1974 }
1975 break;
1976 }
1977
1978 case TU_UPDATE_LEXICAL: {
1979 DeclContext *TU = Context.getTranslationUnitDecl();
1980 DeclContextInfo &Info = F.DeclContextInfos[TU];
1981 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
1982 Info.NumLexicalDecls
1983 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
1984 TU->setHasExternalLexicalStorage(true);
1985 break;
1986 }
1987
1988 case UPDATE_VISIBLE: {
1989 unsigned Idx = 0;
1990 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
1991 ASTDeclContextNameLookupTable *Table =
1992 ASTDeclContextNameLookupTable::Create(
1993 (const unsigned char *)BlobStart + Record[Idx++],
1994 (const unsigned char *)BlobStart,
1995 ASTDeclContextNameLookupTrait(*this, F));
1996 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
1997 DeclContext *TU = Context.getTranslationUnitDecl();
1998 F.DeclContextInfos[TU].NameLookupTableData = Table;
1999 TU->setHasExternalVisibleStorage(true);
2000 } else
2001 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2002 break;
2003 }
2004
2005 case IDENTIFIER_TABLE:
2006 F.IdentifierTableData = BlobStart;
2007 if (Record[0]) {
2008 F.IdentifierLookupTable
2009 = ASTIdentifierLookupTable::Create(
2010 (const unsigned char *)F.IdentifierTableData + Record[0],
2011 (const unsigned char *)F.IdentifierTableData,
2012 ASTIdentifierLookupTrait(*this, F));
2013
2014 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2015 }
2016 break;
2017
2018 case IDENTIFIER_OFFSET: {
2019 if (F.LocalNumIdentifiers != 0) {
2020 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2021 return true;
2022 }
2023 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2024 F.LocalNumIdentifiers = Record[0];
2025 unsigned LocalBaseIdentifierID = Record[1];
2026 F.BaseIdentifierID = getTotalNumIdentifiers();
2027
2028 if (F.LocalNumIdentifiers > 0) {
2029 // Introduce the global -> local mapping for identifiers within this
2030 // module.
2031 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2032 &F));
2033
2034 // Introduce the local -> global mapping for identifiers within this
2035 // module.
2036 F.IdentifierRemap.insertOrReplace(
2037 std::make_pair(LocalBaseIdentifierID,
2038 F.BaseIdentifierID - LocalBaseIdentifierID));
2039
2040 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2041 + F.LocalNumIdentifiers);
2042 }
2043 break;
2044 }
2045
2046 case EXTERNAL_DEFINITIONS:
2047 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2048 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2049 break;
2050
2051 case SPECIAL_TYPES:
2052 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2053 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2054 break;
2055
2056 case STATISTICS:
2057 TotalNumStatements += Record[0];
2058 TotalNumMacros += Record[1];
2059 TotalLexicalDeclContexts += Record[2];
2060 TotalVisibleDeclContexts += Record[3];
2061 break;
2062
2063 case UNUSED_FILESCOPED_DECLS:
2064 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2065 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2066 break;
2067
2068 case DELEGATING_CTORS:
2069 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2070 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2071 break;
2072
2073 case WEAK_UNDECLARED_IDENTIFIERS:
2074 if (Record.size() % 4 != 0) {
2075 Error("invalid weak identifiers record");
2076 return true;
2077 }
2078
2079 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2080 // files. This isn't the way to do it :)
2081 WeakUndeclaredIdentifiers.clear();
2082
2083 // Translate the weak, undeclared identifiers into global IDs.
2084 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2085 WeakUndeclaredIdentifiers.push_back(
2086 getGlobalIdentifierID(F, Record[I++]));
2087 WeakUndeclaredIdentifiers.push_back(
2088 getGlobalIdentifierID(F, Record[I++]));
2089 WeakUndeclaredIdentifiers.push_back(
2090 ReadSourceLocation(F, Record, I).getRawEncoding());
2091 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2092 }
2093 break;
2094
Richard Smith5ea6ef42013-01-10 23:43:47 +00002095 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002096 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002097 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002098 break;
2099
2100 case SELECTOR_OFFSETS: {
2101 F.SelectorOffsets = (const uint32_t *)BlobStart;
2102 F.LocalNumSelectors = Record[0];
2103 unsigned LocalBaseSelectorID = Record[1];
2104 F.BaseSelectorID = getTotalNumSelectors();
2105
2106 if (F.LocalNumSelectors > 0) {
2107 // Introduce the global -> local mapping for selectors within this
2108 // module.
2109 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2110
2111 // Introduce the local -> global mapping for selectors within this
2112 // module.
2113 F.SelectorRemap.insertOrReplace(
2114 std::make_pair(LocalBaseSelectorID,
2115 F.BaseSelectorID - LocalBaseSelectorID));
2116
2117 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2118 }
2119 break;
2120 }
2121
2122 case METHOD_POOL:
2123 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2124 if (Record[0])
2125 F.SelectorLookupTable
2126 = ASTSelectorLookupTable::Create(
2127 F.SelectorLookupTableData + Record[0],
2128 F.SelectorLookupTableData,
2129 ASTSelectorLookupTrait(*this, F));
2130 TotalNumMethodPoolEntries += Record[1];
2131 break;
2132
2133 case REFERENCED_SELECTOR_POOL:
2134 if (!Record.empty()) {
2135 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2136 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2137 Record[Idx++]));
2138 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2139 getRawEncoding());
2140 }
2141 }
2142 break;
2143
2144 case PP_COUNTER_VALUE:
2145 if (!Record.empty() && Listener)
2146 Listener->ReadCounter(F, Record[0]);
2147 break;
2148
2149 case FILE_SORTED_DECLS:
2150 F.FileSortedDecls = (const DeclID *)BlobStart;
2151 F.NumFileSortedDecls = Record[0];
2152 break;
2153
2154 case SOURCE_LOCATION_OFFSETS: {
2155 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
2156 F.LocalNumSLocEntries = Record[0];
2157 unsigned SLocSpaceSize = Record[1];
2158 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2159 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2160 SLocSpaceSize);
2161 // Make our entry in the range map. BaseID is negative and growing, so
2162 // we invert it. Because we invert it, though, we need the other end of
2163 // the range.
2164 unsigned RangeStart =
2165 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2166 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2167 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2168
2169 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2170 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2171 GlobalSLocOffsetMap.insert(
2172 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2173 - SLocSpaceSize,&F));
2174
2175 // Initialize the remapping table.
2176 // Invalid stays invalid.
2177 F.SLocRemap.insert(std::make_pair(0U, 0));
2178 // This module. Base was 2 when being compiled.
2179 F.SLocRemap.insert(std::make_pair(2U,
2180 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2181
2182 TotalNumSLocEntries += F.LocalNumSLocEntries;
2183 break;
2184 }
2185
2186 case MODULE_OFFSET_MAP: {
2187 // Additional remapping information.
2188 const unsigned char *Data = (const unsigned char*)BlobStart;
2189 const unsigned char *DataEnd = Data + BlobLen;
2190
2191 // Continuous range maps we may be updating in our module.
2192 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2193 ContinuousRangeMap<uint32_t, int, 2>::Builder
2194 IdentifierRemap(F.IdentifierRemap);
2195 ContinuousRangeMap<uint32_t, int, 2>::Builder
2196 MacroRemap(F.MacroRemap);
2197 ContinuousRangeMap<uint32_t, int, 2>::Builder
2198 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2199 ContinuousRangeMap<uint32_t, int, 2>::Builder
2200 SubmoduleRemap(F.SubmoduleRemap);
2201 ContinuousRangeMap<uint32_t, int, 2>::Builder
2202 SelectorRemap(F.SelectorRemap);
2203 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2204 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2205
2206 while(Data < DataEnd) {
2207 uint16_t Len = io::ReadUnalignedLE16(Data);
2208 StringRef Name = StringRef((const char*)Data, Len);
2209 Data += Len;
2210 ModuleFile *OM = ModuleMgr.lookup(Name);
2211 if (!OM) {
2212 Error("SourceLocation remap refers to unknown module");
2213 return true;
2214 }
2215
2216 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2217 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2218 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2219 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2220 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2221 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2222 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2223 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2224
2225 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2226 SLocRemap.insert(std::make_pair(SLocOffset,
2227 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2228 IdentifierRemap.insert(
2229 std::make_pair(IdentifierIDOffset,
2230 OM->BaseIdentifierID - IdentifierIDOffset));
2231 MacroRemap.insert(std::make_pair(MacroIDOffset,
2232 OM->BaseMacroID - MacroIDOffset));
2233 PreprocessedEntityRemap.insert(
2234 std::make_pair(PreprocessedEntityIDOffset,
2235 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2236 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2237 OM->BaseSubmoduleID - SubmoduleIDOffset));
2238 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2239 OM->BaseSelectorID - SelectorIDOffset));
2240 DeclRemap.insert(std::make_pair(DeclIDOffset,
2241 OM->BaseDeclID - DeclIDOffset));
2242
2243 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2244 OM->BaseTypeIndex - TypeIndexOffset));
2245
2246 // Global -> local mappings.
2247 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2248 }
2249 break;
2250 }
2251
2252 case SOURCE_MANAGER_LINE_TABLE:
2253 if (ParseLineTable(F, Record))
2254 return true;
2255 break;
2256
2257 case SOURCE_LOCATION_PRELOADS: {
2258 // Need to transform from the local view (1-based IDs) to the global view,
2259 // which is based off F.SLocEntryBaseID.
2260 if (!F.PreloadSLocEntries.empty()) {
2261 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2262 return true;
2263 }
2264
2265 F.PreloadSLocEntries.swap(Record);
2266 break;
2267 }
2268
2269 case EXT_VECTOR_DECLS:
2270 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2271 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2272 break;
2273
2274 case VTABLE_USES:
2275 if (Record.size() % 3 != 0) {
2276 Error("Invalid VTABLE_USES record");
2277 return true;
2278 }
2279
2280 // Later tables overwrite earlier ones.
2281 // FIXME: Modules will have some trouble with this. This is clearly not
2282 // the right way to do this.
2283 VTableUses.clear();
2284
2285 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2286 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2287 VTableUses.push_back(
2288 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2289 VTableUses.push_back(Record[Idx++]);
2290 }
2291 break;
2292
2293 case DYNAMIC_CLASSES:
2294 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2295 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2296 break;
2297
2298 case PENDING_IMPLICIT_INSTANTIATIONS:
2299 if (PendingInstantiations.size() % 2 != 0) {
2300 Error("Invalid existing PendingInstantiations");
2301 return true;
2302 }
2303
2304 if (Record.size() % 2 != 0) {
2305 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2306 return true;
2307 }
2308
2309 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2310 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2311 PendingInstantiations.push_back(
2312 ReadSourceLocation(F, Record, I).getRawEncoding());
2313 }
2314 break;
2315
2316 case SEMA_DECL_REFS:
2317 // Later tables overwrite earlier ones.
2318 // FIXME: Modules will have some trouble with this.
2319 SemaDeclRefs.clear();
2320 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2321 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2322 break;
2323
2324 case PPD_ENTITIES_OFFSETS: {
2325 F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2326 assert(BlobLen % sizeof(PPEntityOffset) == 0);
2327 F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
2328
2329 unsigned LocalBasePreprocessedEntityID = Record[0];
2330
2331 unsigned StartingID;
2332 if (!PP.getPreprocessingRecord())
2333 PP.createPreprocessingRecord();
2334 if (!PP.getPreprocessingRecord()->getExternalSource())
2335 PP.getPreprocessingRecord()->SetExternalSource(*this);
2336 StartingID
2337 = PP.getPreprocessingRecord()
2338 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2339 F.BasePreprocessedEntityID = StartingID;
2340
2341 if (F.NumPreprocessedEntities > 0) {
2342 // Introduce the global -> local mapping for preprocessed entities in
2343 // this module.
2344 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2345
2346 // Introduce the local -> global mapping for preprocessed entities in
2347 // this module.
2348 F.PreprocessedEntityRemap.insertOrReplace(
2349 std::make_pair(LocalBasePreprocessedEntityID,
2350 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2351 }
2352
2353 break;
2354 }
2355
2356 case DECL_UPDATE_OFFSETS: {
2357 if (Record.size() % 2 != 0) {
2358 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2359 return true;
2360 }
2361 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2362 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2363 .push_back(std::make_pair(&F, Record[I+1]));
2364 break;
2365 }
2366
2367 case DECL_REPLACEMENTS: {
2368 if (Record.size() % 3 != 0) {
2369 Error("invalid DECL_REPLACEMENTS block in AST file");
2370 return true;
2371 }
2372 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2373 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2374 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2375 break;
2376 }
2377
2378 case OBJC_CATEGORIES_MAP: {
2379 if (F.LocalNumObjCCategoriesInMap != 0) {
2380 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2381 return true;
2382 }
2383
2384 F.LocalNumObjCCategoriesInMap = Record[0];
2385 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
2386 break;
2387 }
2388
2389 case OBJC_CATEGORIES:
2390 F.ObjCCategories.swap(Record);
2391 break;
2392
2393 case CXX_BASE_SPECIFIER_OFFSETS: {
2394 if (F.LocalNumCXXBaseSpecifiers != 0) {
2395 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2396 return true;
2397 }
2398
2399 F.LocalNumCXXBaseSpecifiers = Record[0];
2400 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2401 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2402 break;
2403 }
2404
2405 case DIAG_PRAGMA_MAPPINGS:
2406 if (F.PragmaDiagMappings.empty())
2407 F.PragmaDiagMappings.swap(Record);
2408 else
2409 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2410 Record.begin(), Record.end());
2411 break;
2412
2413 case CUDA_SPECIAL_DECL_REFS:
2414 // Later tables overwrite earlier ones.
2415 // FIXME: Modules will have trouble with this.
2416 CUDASpecialDeclRefs.clear();
2417 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2418 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2419 break;
2420
2421 case HEADER_SEARCH_TABLE: {
2422 F.HeaderFileInfoTableData = BlobStart;
2423 F.LocalNumHeaderFileInfos = Record[1];
2424 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2425 if (Record[0]) {
2426 F.HeaderFileInfoTable
2427 = HeaderFileInfoLookupTable::Create(
2428 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2429 (const unsigned char *)F.HeaderFileInfoTableData,
2430 HeaderFileInfoTrait(*this, F,
2431 &PP.getHeaderSearchInfo(),
2432 BlobStart + Record[2]));
2433
2434 PP.getHeaderSearchInfo().SetExternalSource(this);
2435 if (!PP.getHeaderSearchInfo().getExternalLookup())
2436 PP.getHeaderSearchInfo().SetExternalLookup(this);
2437 }
2438 break;
2439 }
2440
2441 case FP_PRAGMA_OPTIONS:
2442 // Later tables overwrite earlier ones.
2443 FPPragmaOptions.swap(Record);
2444 break;
2445
2446 case OPENCL_EXTENSIONS:
2447 // Later tables overwrite earlier ones.
2448 OpenCLExtensions.swap(Record);
2449 break;
2450
2451 case TENTATIVE_DEFINITIONS:
2452 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2453 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2454 break;
2455
2456 case KNOWN_NAMESPACES:
2457 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2458 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2459 break;
2460
2461 case IMPORTED_MODULES: {
2462 if (F.Kind != MK_Module) {
2463 // If we aren't loading a module (which has its own exports), make
2464 // all of the imported modules visible.
2465 // FIXME: Deal with macros-only imports.
2466 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2467 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2468 ImportedModules.push_back(GlobalID);
2469 }
2470 }
2471 break;
2472 }
2473
2474 case LOCAL_REDECLARATIONS: {
2475 F.RedeclarationChains.swap(Record);
2476 break;
2477 }
2478
2479 case LOCAL_REDECLARATIONS_MAP: {
2480 if (F.LocalNumRedeclarationsInMap != 0) {
2481 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2482 return true;
2483 }
2484
2485 F.LocalNumRedeclarationsInMap = Record[0];
2486 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
2487 break;
2488 }
2489
2490 case MERGED_DECLARATIONS: {
2491 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2492 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2493 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2494 for (unsigned N = Record[Idx++]; N > 0; --N)
2495 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2496 }
2497 break;
2498 }
2499
2500 case MACRO_OFFSET: {
2501 if (F.LocalNumMacros != 0) {
2502 Error("duplicate MACRO_OFFSET record in AST file");
2503 return true;
2504 }
2505 F.MacroOffsets = (const uint32_t *)BlobStart;
2506 F.LocalNumMacros = Record[0];
2507 unsigned LocalBaseMacroID = Record[1];
2508 F.BaseMacroID = getTotalNumMacros();
2509
2510 if (F.LocalNumMacros > 0) {
2511 // Introduce the global -> local mapping for macros within this module.
2512 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2513
2514 // Introduce the local -> global mapping for macros within this module.
2515 F.MacroRemap.insertOrReplace(
2516 std::make_pair(LocalBaseMacroID,
2517 F.BaseMacroID - LocalBaseMacroID));
2518
2519 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2520 }
2521 break;
2522 }
2523
2524 case MACRO_UPDATES: {
2525 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2526 MacroID ID = getGlobalMacroID(F, Record[I++]);
2527 if (I == N)
2528 break;
2529
2530 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2531 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2532 MacroUpdate Update;
2533 Update.UndefLoc = UndefLoc;
2534 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
2535 }
2536 break;
2537 }
2538 }
2539 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002540}
2541
2542void ASTReader::makeNamesVisible(const HiddenNames &Names) {
2543 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2544 switch (Names[I].getKind()) {
2545 case HiddenName::Declaration:
2546 Names[I].getDecl()->Hidden = false;
2547 break;
2548
2549 case HiddenName::MacroVisibility: {
2550 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2551 Macro.second->setHidden(!Macro.second->isPublic());
2552 if (Macro.second->isDefined()) {
2553 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2554 }
2555 break;
2556 }
2557
2558 case HiddenName::MacroUndef: {
2559 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2560 if (Macro.second->isDefined()) {
2561 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
2562 if (PPMutationListener *Listener = PP.getPPMutationListener())
2563 Listener->UndefinedMacro(Macro.second);
2564 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2565 }
2566 break;
2567 }
2568 }
2569 }
2570}
2571
2572void ASTReader::makeModuleVisible(Module *Mod,
2573 Module::NameVisibilityKind NameVisibility) {
2574 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002575 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002576 Stack.push_back(Mod);
2577 while (!Stack.empty()) {
2578 Mod = Stack.back();
2579 Stack.pop_back();
2580
2581 if (NameVisibility <= Mod->NameVisibility) {
2582 // This module already has this level of visibility (or greater), so
2583 // there is nothing more to do.
2584 continue;
2585 }
2586
2587 if (!Mod->isAvailable()) {
2588 // Modules that aren't available cannot be made visible.
2589 continue;
2590 }
2591
2592 // Update the module's name visibility.
2593 Mod->NameVisibility = NameVisibility;
2594
2595 // If we've already deserialized any names from this module,
2596 // mark them as visible.
2597 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2598 if (Hidden != HiddenNamesMap.end()) {
2599 makeNamesVisible(Hidden->second);
2600 HiddenNamesMap.erase(Hidden);
2601 }
2602
2603 // Push any non-explicit submodules onto the stack to be marked as
2604 // visible.
2605 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2606 SubEnd = Mod->submodule_end();
2607 Sub != SubEnd; ++Sub) {
2608 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2609 Stack.push_back(*Sub);
2610 }
2611
2612 // Push any exported modules onto the stack to be marked as visible.
2613 bool AnyWildcard = false;
2614 bool UnrestrictedWildcard = false;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002615 SmallVector<Module *, 4> WildcardRestrictions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002616 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2617 Module *Exported = Mod->Exports[I].getPointer();
2618 if (!Mod->Exports[I].getInt()) {
2619 // Export a named module directly; no wildcards involved.
2620 if (Visited.insert(Exported))
2621 Stack.push_back(Exported);
2622
2623 continue;
2624 }
2625
2626 // Wildcard export: export all of the imported modules that match
2627 // the given pattern.
2628 AnyWildcard = true;
2629 if (UnrestrictedWildcard)
2630 continue;
2631
2632 if (Module *Restriction = Mod->Exports[I].getPointer())
2633 WildcardRestrictions.push_back(Restriction);
2634 else {
2635 WildcardRestrictions.clear();
2636 UnrestrictedWildcard = true;
2637 }
2638 }
2639
2640 // If there were any wildcards, push any imported modules that were
2641 // re-exported by the wildcard restriction.
2642 if (!AnyWildcard)
2643 continue;
2644
2645 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2646 Module *Imported = Mod->Imports[I];
2647 if (!Visited.insert(Imported))
2648 continue;
2649
2650 bool Acceptable = UnrestrictedWildcard;
2651 if (!Acceptable) {
2652 // Check whether this module meets one of the restrictions.
2653 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
2654 Module *Restriction = WildcardRestrictions[R];
2655 if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
2656 Acceptable = true;
2657 break;
2658 }
2659 }
2660 }
2661
2662 if (!Acceptable)
2663 continue;
2664
2665 Stack.push_back(Imported);
2666 }
2667 }
2668}
2669
2670ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2671 ModuleKind Type,
2672 SourceLocation ImportLoc,
2673 unsigned ClientLoadCapabilities) {
2674 // Bump the generation number.
2675 unsigned PreviousGeneration = CurrentGeneration++;
2676
2677 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002678 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002679 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2680 /*ImportedBy=*/0, Loaded,
2681 ClientLoadCapabilities)) {
2682 case Failure:
2683 case OutOfDate:
2684 case VersionMismatch:
2685 case ConfigurationMismatch:
2686 case HadErrors:
2687 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end());
2688 return ReadResult;
2689
2690 case Success:
2691 break;
2692 }
2693
2694 // Here comes stuff that we only do once the entire chain is loaded.
2695
2696 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002697 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2698 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002699 M != MEnd; ++M) {
2700 ModuleFile &F = *M->Mod;
2701
2702 // Read the AST block.
2703 if (ReadASTBlock(F))
2704 return Failure;
2705
2706 // Once read, set the ModuleFile bit base offset and update the size in
2707 // bits of all files we've seen.
2708 F.GlobalBitOffset = TotalModulesSizeInBits;
2709 TotalModulesSizeInBits += F.SizeInBits;
2710 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2711
2712 // Preload SLocEntries.
2713 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2714 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2715 // Load it through the SourceManager and don't call ReadSLocEntry()
2716 // directly because the entry may have already been loaded in which case
2717 // calling ReadSLocEntry() directly would trigger an assertion in
2718 // SourceManager.
2719 SourceMgr.getLoadedSLocEntryByID(Index);
2720 }
2721 }
2722
2723 // Setup the import locations.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002724 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2725 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002726 M != MEnd; ++M) {
2727 ModuleFile &F = *M->Mod;
2728 if (!M->ImportedBy)
2729 F.ImportLoc = M->ImportLoc;
2730 else
2731 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2732 M->ImportLoc.getRawEncoding());
2733 }
2734
2735 // Mark all of the identifiers in the identifier table as being out of date,
2736 // so that various accessors know to check the loaded modules when the
2737 // identifier is used.
2738 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2739 IdEnd = PP.getIdentifierTable().end();
2740 Id != IdEnd; ++Id)
2741 Id->second->setOutOfDate(true);
2742
2743 // Resolve any unresolved module exports.
2744 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
2745 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
2746 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2747 Module *ResolvedMod = getSubmodule(GlobalID);
2748
2749 if (Unresolved.IsImport) {
2750 if (ResolvedMod)
2751 Unresolved.Mod->Imports.push_back(ResolvedMod);
2752 continue;
2753 }
2754
2755 if (ResolvedMod || Unresolved.IsWildcard)
2756 Unresolved.Mod->Exports.push_back(
2757 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
2758 }
2759 UnresolvedModuleImportExports.clear();
2760
2761 InitializeContext();
2762
2763 if (DeserializationListener)
2764 DeserializationListener->ReaderInitialized(this);
2765
2766 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
2767 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
2768 PrimaryModule.OriginalSourceFileID
2769 = FileID::get(PrimaryModule.SLocEntryBaseID
2770 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
2771
2772 // If this AST file is a precompiled preamble, then set the
2773 // preamble file ID of the source manager to the file source file
2774 // from which the preamble was built.
2775 if (Type == MK_Preamble) {
2776 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
2777 } else if (Type == MK_MainFile) {
2778 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
2779 }
2780 }
2781
2782 // For any Objective-C class definitions we have already loaded, make sure
2783 // that we load any additional categories.
2784 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
2785 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
2786 ObjCClassesLoaded[I],
2787 PreviousGeneration);
2788 }
2789
2790 return Success;
2791}
2792
2793ASTReader::ASTReadResult
2794ASTReader::ReadASTCore(StringRef FileName,
2795 ModuleKind Type,
2796 SourceLocation ImportLoc,
2797 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002798 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002799 unsigned ClientLoadCapabilities) {
2800 ModuleFile *M;
2801 bool NewModule;
2802 std::string ErrorStr;
2803 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportLoc,
2804 ImportedBy, CurrentGeneration,
2805 ErrorStr);
2806
2807 if (!M) {
2808 // We couldn't load the module.
2809 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2810 + ErrorStr;
2811 Error(Msg);
2812 return Failure;
2813 }
2814
2815 if (!NewModule) {
2816 // We've already loaded this module.
2817 return Success;
2818 }
2819
2820 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2821 // module?
2822 if (FileName != "-") {
2823 CurrentDir = llvm::sys::path::parent_path(FileName);
2824 if (CurrentDir.empty()) CurrentDir = ".";
2825 }
2826
2827 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002828 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002829 Stream.init(F.StreamFile);
2830 F.SizeInBits = F.Buffer->getBufferSize() * 8;
2831
2832 // Sniff for the signature.
2833 if (Stream.Read(8) != 'C' ||
2834 Stream.Read(8) != 'P' ||
2835 Stream.Read(8) != 'C' ||
2836 Stream.Read(8) != 'H') {
2837 Diag(diag::err_not_a_pch_file) << FileName;
2838 return Failure;
2839 }
2840
2841 // This is used for compatibility with older PCH formats.
2842 bool HaveReadControlBlock = false;
2843
Chris Lattner99a5af02013-01-20 00:00:22 +00002844 while (1) {
2845 llvm::BitstreamEntry Entry = Stream.advance();
2846
2847 switch (Entry.Kind) {
2848 case llvm::BitstreamEntry::Error:
2849 case llvm::BitstreamEntry::EndBlock:
2850 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002851 Error("invalid record at top-level of AST file");
2852 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00002853
2854 case llvm::BitstreamEntry::SubBlock:
2855 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002856 }
2857
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002858 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00002859 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002860 case llvm::bitc::BLOCKINFO_BLOCK_ID:
2861 if (Stream.ReadBlockInfoBlock()) {
2862 Error("malformed BlockInfoBlock in AST file");
2863 return Failure;
2864 }
2865 break;
2866 case CONTROL_BLOCK_ID:
2867 HaveReadControlBlock = true;
2868 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
2869 case Success:
2870 break;
2871
2872 case Failure: return Failure;
2873 case OutOfDate: return OutOfDate;
2874 case VersionMismatch: return VersionMismatch;
2875 case ConfigurationMismatch: return ConfigurationMismatch;
2876 case HadErrors: return HadErrors;
2877 }
2878 break;
2879 case AST_BLOCK_ID:
2880 if (!HaveReadControlBlock) {
2881 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2882 Diag(diag::warn_pch_version_too_old);
2883 return VersionMismatch;
2884 }
2885
2886 // Record that we've loaded this module.
2887 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
2888 return Success;
2889
2890 default:
2891 if (Stream.SkipBlock()) {
2892 Error("malformed block record in AST file");
2893 return Failure;
2894 }
2895 break;
2896 }
2897 }
2898
2899 return Success;
2900}
2901
2902void ASTReader::InitializeContext() {
2903 // If there's a listener, notify them that we "read" the translation unit.
2904 if (DeserializationListener)
2905 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
2906 Context.getTranslationUnitDecl());
2907
2908 // Make sure we load the declaration update records for the translation unit,
2909 // if there are any.
2910 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
2911 Context.getTranslationUnitDecl());
2912
2913 // FIXME: Find a better way to deal with collisions between these
2914 // built-in types. Right now, we just ignore the problem.
2915
2916 // Load the special types.
2917 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
2918 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2919 if (!Context.CFConstantStringTypeDecl)
2920 Context.setCFConstantStringType(GetType(String));
2921 }
2922
2923 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2924 QualType FileType = GetType(File);
2925 if (FileType.isNull()) {
2926 Error("FILE type is NULL");
2927 return;
2928 }
2929
2930 if (!Context.FILEDecl) {
2931 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2932 Context.setFILEDecl(Typedef->getDecl());
2933 else {
2934 const TagType *Tag = FileType->getAs<TagType>();
2935 if (!Tag) {
2936 Error("Invalid FILE type in AST file");
2937 return;
2938 }
2939 Context.setFILEDecl(Tag->getDecl());
2940 }
2941 }
2942 }
2943
2944 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
2945 QualType Jmp_bufType = GetType(Jmp_buf);
2946 if (Jmp_bufType.isNull()) {
2947 Error("jmp_buf type is NULL");
2948 return;
2949 }
2950
2951 if (!Context.jmp_bufDecl) {
2952 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2953 Context.setjmp_bufDecl(Typedef->getDecl());
2954 else {
2955 const TagType *Tag = Jmp_bufType->getAs<TagType>();
2956 if (!Tag) {
2957 Error("Invalid jmp_buf type in AST file");
2958 return;
2959 }
2960 Context.setjmp_bufDecl(Tag->getDecl());
2961 }
2962 }
2963 }
2964
2965 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
2966 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2967 if (Sigjmp_bufType.isNull()) {
2968 Error("sigjmp_buf type is NULL");
2969 return;
2970 }
2971
2972 if (!Context.sigjmp_bufDecl) {
2973 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2974 Context.setsigjmp_bufDecl(Typedef->getDecl());
2975 else {
2976 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2977 assert(Tag && "Invalid sigjmp_buf type in AST file");
2978 Context.setsigjmp_bufDecl(Tag->getDecl());
2979 }
2980 }
2981 }
2982
2983 if (unsigned ObjCIdRedef
2984 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
2985 if (Context.ObjCIdRedefinitionType.isNull())
2986 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2987 }
2988
2989 if (unsigned ObjCClassRedef
2990 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
2991 if (Context.ObjCClassRedefinitionType.isNull())
2992 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2993 }
2994
2995 if (unsigned ObjCSelRedef
2996 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
2997 if (Context.ObjCSelRedefinitionType.isNull())
2998 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2999 }
3000
3001 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3002 QualType Ucontext_tType = GetType(Ucontext_t);
3003 if (Ucontext_tType.isNull()) {
3004 Error("ucontext_t type is NULL");
3005 return;
3006 }
3007
3008 if (!Context.ucontext_tDecl) {
3009 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3010 Context.setucontext_tDecl(Typedef->getDecl());
3011 else {
3012 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3013 assert(Tag && "Invalid ucontext_t type in AST file");
3014 Context.setucontext_tDecl(Tag->getDecl());
3015 }
3016 }
3017 }
3018 }
3019
3020 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3021
3022 // If there were any CUDA special declarations, deserialize them.
3023 if (!CUDASpecialDeclRefs.empty()) {
3024 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3025 Context.setcudaConfigureCallDecl(
3026 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3027 }
3028
3029 // Re-export any modules that were imported by a non-module AST file.
3030 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3031 if (Module *Imported = getSubmodule(ImportedModules[I]))
3032 makeModuleVisible(Imported, Module::AllVisible);
3033 }
3034 ImportedModules.clear();
3035}
3036
3037void ASTReader::finalizeForWriting() {
3038 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3039 HiddenEnd = HiddenNamesMap.end();
3040 Hidden != HiddenEnd; ++Hidden) {
3041 makeNamesVisible(Hidden->second);
3042 }
3043 HiddenNamesMap.clear();
3044}
3045
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003046/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3047/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3048/// false on success and true on failure.
3049static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3050 while (1) {
3051 llvm::BitstreamEntry Entry = Cursor.advance();
3052 switch (Entry.Kind) {
3053 case llvm::BitstreamEntry::Error:
3054 case llvm::BitstreamEntry::EndBlock:
3055 return true;
3056
3057 case llvm::BitstreamEntry::Record:
3058 // Ignore top-level records.
3059 Cursor.skipRecord(Entry.ID);
3060 break;
3061
3062 case llvm::BitstreamEntry::SubBlock:
3063 if (Entry.ID == CONTROL_BLOCK_ID) {
3064 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3065 return true;
3066 // Found it!
3067 return false;
3068 }
3069
3070 if (Cursor.SkipBlock())
3071 return true;
3072 }
3073 }
3074}
3075
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003076/// \brief Retrieve the name of the original source file name
3077/// directly from the AST file, without actually loading the AST
3078/// file.
3079std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3080 FileManager &FileMgr,
3081 DiagnosticsEngine &Diags) {
3082 // Open the AST file.
3083 std::string ErrStr;
3084 OwningPtr<llvm::MemoryBuffer> Buffer;
3085 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3086 if (!Buffer) {
3087 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3088 return std::string();
3089 }
3090
3091 // Initialize the stream
3092 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003093 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003094 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3095 (const unsigned char *)Buffer->getBufferEnd());
3096 Stream.init(StreamFile);
3097
3098 // Sniff for the signature.
3099 if (Stream.Read(8) != 'C' ||
3100 Stream.Read(8) != 'P' ||
3101 Stream.Read(8) != 'C' ||
3102 Stream.Read(8) != 'H') {
3103 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3104 return std::string();
3105 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003106
Chris Lattner88bde502013-01-19 21:39:22 +00003107 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003108 if (SkipCursorToControlBlock(Stream)) {
3109 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3110 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003111 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003112
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003113 // Scan for ORIGINAL_FILE inside the control block.
3114 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003115 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003116 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003117 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3118 return std::string();
3119
3120 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3121 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3122 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003123 }
Chris Lattner88bde502013-01-19 21:39:22 +00003124
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003125 Record.clear();
3126 const char *BlobStart = 0;
3127 unsigned BlobLen = 0;
Chris Lattner88bde502013-01-19 21:39:22 +00003128 if (Stream.ReadRecord(Entry.ID, Record, BlobStart, BlobLen)
3129 == ORIGINAL_FILE)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003130 return std::string(BlobStart, BlobLen);
3131 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003132}
3133
3134namespace {
3135 class SimplePCHValidator : public ASTReaderListener {
3136 const LangOptions &ExistingLangOpts;
3137 const TargetOptions &ExistingTargetOpts;
3138 const PreprocessorOptions &ExistingPPOpts;
3139 FileManager &FileMgr;
3140
3141 public:
3142 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3143 const TargetOptions &ExistingTargetOpts,
3144 const PreprocessorOptions &ExistingPPOpts,
3145 FileManager &FileMgr)
3146 : ExistingLangOpts(ExistingLangOpts),
3147 ExistingTargetOpts(ExistingTargetOpts),
3148 ExistingPPOpts(ExistingPPOpts),
3149 FileMgr(FileMgr)
3150 {
3151 }
3152
3153 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3154 bool Complain) {
3155 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3156 }
3157 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3158 bool Complain) {
3159 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3160 }
3161 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3162 bool Complain,
3163 std::string &SuggestedPredefines) {
3164 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3165 SuggestedPredefines);
3166 }
3167 };
3168}
3169
3170bool ASTReader::readASTFileControlBlock(StringRef Filename,
3171 FileManager &FileMgr,
3172 ASTReaderListener &Listener) {
3173 // Open the AST file.
3174 std::string ErrStr;
3175 OwningPtr<llvm::MemoryBuffer> Buffer;
3176 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3177 if (!Buffer) {
3178 return true;
3179 }
3180
3181 // Initialize the stream
3182 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003183 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003184 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3185 (const unsigned char *)Buffer->getBufferEnd());
3186 Stream.init(StreamFile);
3187
3188 // Sniff for the signature.
3189 if (Stream.Read(8) != 'C' ||
3190 Stream.Read(8) != 'P' ||
3191 Stream.Read(8) != 'C' ||
3192 Stream.Read(8) != 'H') {
3193 return true;
3194 }
3195
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003196 // Scan for the CONTROL_BLOCK_ID block.
3197 if (SkipCursorToControlBlock(Stream))
3198 return true;
3199
3200 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003201 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003202 while (1) {
3203 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3204 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3205 return false;
3206
3207 if (Entry.Kind != llvm::BitstreamEntry::Record)
3208 return true;
3209
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003210 Record.clear();
3211 const char *BlobStart = 0;
3212 unsigned BlobLen = 0;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003213 unsigned RecCode = Stream.ReadRecord(Entry.ID, Record, BlobStart, BlobLen);
3214 switch ((ControlRecordTypes)RecCode) {
3215 case METADATA: {
3216 if (Record[0] != VERSION_MAJOR)
3217 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003218
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003219 const std::string &CurBranch = getClangFullRepositoryVersion();
3220 StringRef ASTBranch(BlobStart, BlobLen);
3221 if (StringRef(CurBranch) != ASTBranch)
3222 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003223
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003224 break;
3225 }
3226 case LANGUAGE_OPTIONS:
3227 if (ParseLanguageOptions(Record, false, Listener))
3228 return true;
3229 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003230
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003231 case TARGET_OPTIONS:
3232 if (ParseTargetOptions(Record, false, Listener))
3233 return true;
3234 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003235
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003236 case DIAGNOSTIC_OPTIONS:
3237 if (ParseDiagnosticOptions(Record, false, Listener))
3238 return true;
3239 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003240
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003241 case FILE_SYSTEM_OPTIONS:
3242 if (ParseFileSystemOptions(Record, false, Listener))
3243 return true;
3244 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003245
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003246 case HEADER_SEARCH_OPTIONS:
3247 if (ParseHeaderSearchOptions(Record, false, Listener))
3248 return true;
3249 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003250
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003251 case PREPROCESSOR_OPTIONS: {
3252 std::string IgnoredSuggestedPredefines;
3253 if (ParsePreprocessorOptions(Record, false, Listener,
3254 IgnoredSuggestedPredefines))
3255 return true;
3256 break;
3257 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003258
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003259 default:
3260 // No other validation to perform.
3261 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003262 }
3263 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003264}
3265
3266
3267bool ASTReader::isAcceptableASTFile(StringRef Filename,
3268 FileManager &FileMgr,
3269 const LangOptions &LangOpts,
3270 const TargetOptions &TargetOpts,
3271 const PreprocessorOptions &PPOpts) {
3272 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3273 return !readASTFileControlBlock(Filename, FileMgr, validator);
3274}
3275
3276bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3277 // Enter the submodule block.
3278 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3279 Error("malformed submodule block record in AST file");
3280 return true;
3281 }
3282
3283 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3284 bool First = true;
3285 Module *CurrentModule = 0;
3286 RecordData Record;
3287 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003288 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3289
3290 switch (Entry.Kind) {
3291 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3292 case llvm::BitstreamEntry::Error:
3293 Error("malformed block record in AST file");
3294 return true;
3295 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003296 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003297 case llvm::BitstreamEntry::Record:
3298 // The interesting case.
3299 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003300 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003301
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003302 // Read a record.
3303 const char *BlobStart;
3304 unsigned BlobLen;
3305 Record.clear();
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003306 switch (F.Stream.ReadRecord(Entry.ID, Record, BlobStart, BlobLen)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003307 default: // Default behavior: ignore.
3308 break;
3309
3310 case SUBMODULE_DEFINITION: {
3311 if (First) {
3312 Error("missing submodule metadata record at beginning of block");
3313 return true;
3314 }
3315
3316 if (Record.size() < 7) {
3317 Error("malformed module definition");
3318 return true;
3319 }
3320
3321 StringRef Name(BlobStart, BlobLen);
3322 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3323 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3324 bool IsFramework = Record[2];
3325 bool IsExplicit = Record[3];
3326 bool IsSystem = Record[4];
3327 bool InferSubmodules = Record[5];
3328 bool InferExplicitSubmodules = Record[6];
3329 bool InferExportWildcard = Record[7];
3330
3331 Module *ParentModule = 0;
3332 if (Parent)
3333 ParentModule = getSubmodule(Parent);
3334
3335 // Retrieve this (sub)module from the module map, creating it if
3336 // necessary.
3337 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3338 IsFramework,
3339 IsExplicit).first;
3340 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3341 if (GlobalIndex >= SubmodulesLoaded.size() ||
3342 SubmodulesLoaded[GlobalIndex]) {
3343 Error("too many submodules");
3344 return true;
3345 }
3346
3347 CurrentModule->setASTFile(F.File);
3348 CurrentModule->IsFromModuleFile = true;
3349 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3350 CurrentModule->InferSubmodules = InferSubmodules;
3351 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3352 CurrentModule->InferExportWildcard = InferExportWildcard;
3353 if (DeserializationListener)
3354 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3355
3356 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003357
3358 // Clear out link libraries; the module file has them.
3359 CurrentModule->LinkLibraries.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003360 break;
3361 }
3362
3363 case SUBMODULE_UMBRELLA_HEADER: {
3364 if (First) {
3365 Error("missing submodule metadata record at beginning of block");
3366 return true;
3367 }
3368
3369 if (!CurrentModule)
3370 break;
3371
3372 StringRef FileName(BlobStart, BlobLen);
3373 if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
3374 if (!CurrentModule->getUmbrellaHeader())
3375 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3376 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3377 Error("mismatched umbrella headers in submodule");
3378 return true;
3379 }
3380 }
3381 break;
3382 }
3383
3384 case SUBMODULE_HEADER: {
3385 if (First) {
3386 Error("missing submodule metadata record at beginning of block");
3387 return true;
3388 }
3389
3390 if (!CurrentModule)
3391 break;
3392
3393 // FIXME: Be more lazy about this!
3394 StringRef FileName(BlobStart, BlobLen);
3395 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3396 if (std::find(CurrentModule->Headers.begin(),
3397 CurrentModule->Headers.end(),
3398 File) == CurrentModule->Headers.end())
3399 ModMap.addHeader(CurrentModule, File, false);
3400 }
3401 break;
3402 }
3403
3404 case SUBMODULE_EXCLUDED_HEADER: {
3405 if (First) {
3406 Error("missing submodule metadata record at beginning of block");
3407 return true;
3408 }
3409
3410 if (!CurrentModule)
3411 break;
3412
3413 // FIXME: Be more lazy about this!
3414 StringRef FileName(BlobStart, BlobLen);
3415 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3416 if (std::find(CurrentModule->Headers.begin(),
3417 CurrentModule->Headers.end(),
3418 File) == CurrentModule->Headers.end())
3419 ModMap.addHeader(CurrentModule, File, true);
3420 }
3421 break;
3422 }
3423
3424 case SUBMODULE_TOPHEADER: {
3425 if (First) {
3426 Error("missing submodule metadata record at beginning of block");
3427 return true;
3428 }
3429
3430 if (!CurrentModule)
3431 break;
3432
3433 // FIXME: Be more lazy about this!
3434 StringRef FileName(BlobStart, BlobLen);
3435 if (const FileEntry *File = PP.getFileManager().getFile(FileName))
3436 CurrentModule->TopHeaders.insert(File);
3437 break;
3438 }
3439
3440 case SUBMODULE_UMBRELLA_DIR: {
3441 if (First) {
3442 Error("missing submodule metadata record at beginning of block");
3443 return true;
3444 }
3445
3446 if (!CurrentModule)
3447 break;
3448
3449 StringRef DirName(BlobStart, BlobLen);
3450 if (const DirectoryEntry *Umbrella
3451 = PP.getFileManager().getDirectory(DirName)) {
3452 if (!CurrentModule->getUmbrellaDir())
3453 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3454 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3455 Error("mismatched umbrella directories in submodule");
3456 return true;
3457 }
3458 }
3459 break;
3460 }
3461
3462 case SUBMODULE_METADATA: {
3463 if (!First) {
3464 Error("submodule metadata record not at beginning of block");
3465 return true;
3466 }
3467 First = false;
3468
3469 F.BaseSubmoduleID = getTotalNumSubmodules();
3470 F.LocalNumSubmodules = Record[0];
3471 unsigned LocalBaseSubmoduleID = Record[1];
3472 if (F.LocalNumSubmodules > 0) {
3473 // Introduce the global -> local mapping for submodules within this
3474 // module.
3475 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3476
3477 // Introduce the local -> global mapping for submodules within this
3478 // module.
3479 F.SubmoduleRemap.insertOrReplace(
3480 std::make_pair(LocalBaseSubmoduleID,
3481 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3482
3483 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3484 }
3485 break;
3486 }
3487
3488 case SUBMODULE_IMPORTS: {
3489 if (First) {
3490 Error("missing submodule metadata record at beginning of block");
3491 return true;
3492 }
3493
3494 if (!CurrentModule)
3495 break;
3496
3497 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3498 UnresolvedModuleImportExport Unresolved;
3499 Unresolved.File = &F;
3500 Unresolved.Mod = CurrentModule;
3501 Unresolved.ID = Record[Idx];
3502 Unresolved.IsImport = true;
3503 Unresolved.IsWildcard = false;
3504 UnresolvedModuleImportExports.push_back(Unresolved);
3505 }
3506 break;
3507 }
3508
3509 case SUBMODULE_EXPORTS: {
3510 if (First) {
3511 Error("missing submodule metadata record at beginning of block");
3512 return true;
3513 }
3514
3515 if (!CurrentModule)
3516 break;
3517
3518 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
3519 UnresolvedModuleImportExport Unresolved;
3520 Unresolved.File = &F;
3521 Unresolved.Mod = CurrentModule;
3522 Unresolved.ID = Record[Idx];
3523 Unresolved.IsImport = false;
3524 Unresolved.IsWildcard = Record[Idx + 1];
3525 UnresolvedModuleImportExports.push_back(Unresolved);
3526 }
3527
3528 // Once we've loaded the set of exports, there's no reason to keep
3529 // the parsed, unresolved exports around.
3530 CurrentModule->UnresolvedExports.clear();
3531 break;
3532 }
3533 case SUBMODULE_REQUIRES: {
3534 if (First) {
3535 Error("missing submodule metadata record at beginning of block");
3536 return true;
3537 }
3538
3539 if (!CurrentModule)
3540 break;
3541
3542 CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),
3543 Context.getLangOpts(),
3544 Context.getTargetInfo());
3545 break;
3546 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003547
3548 case SUBMODULE_LINK_LIBRARY:
3549 if (First) {
3550 Error("missing submodule metadata record at beginning of block");
3551 return true;
3552 }
3553
3554 if (!CurrentModule)
3555 break;
3556
3557 CurrentModule->LinkLibraries.push_back(
3558 Module::LinkLibrary(StringRef(BlobStart, BlobLen),
3559 Record[0]));
3560 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003561 }
3562 }
3563}
3564
3565/// \brief Parse the record that corresponds to a LangOptions data
3566/// structure.
3567///
3568/// This routine parses the language options from the AST file and then gives
3569/// them to the AST listener if one is set.
3570///
3571/// \returns true if the listener deems the file unacceptable, false otherwise.
3572bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3573 bool Complain,
3574 ASTReaderListener &Listener) {
3575 LangOptions LangOpts;
3576 unsigned Idx = 0;
3577#define LANGOPT(Name, Bits, Default, Description) \
3578 LangOpts.Name = Record[Idx++];
3579#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3580 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3581#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003582#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3583#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003584
3585 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3586 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3587 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3588
3589 unsigned Length = Record[Idx++];
3590 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3591 Record.begin() + Idx + Length);
3592 return Listener.ReadLanguageOptions(LangOpts, Complain);
3593}
3594
3595bool ASTReader::ParseTargetOptions(const RecordData &Record,
3596 bool Complain,
3597 ASTReaderListener &Listener) {
3598 unsigned Idx = 0;
3599 TargetOptions TargetOpts;
3600 TargetOpts.Triple = ReadString(Record, Idx);
3601 TargetOpts.CPU = ReadString(Record, Idx);
3602 TargetOpts.ABI = ReadString(Record, Idx);
3603 TargetOpts.CXXABI = ReadString(Record, Idx);
3604 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3605 for (unsigned N = Record[Idx++]; N; --N) {
3606 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3607 }
3608 for (unsigned N = Record[Idx++]; N; --N) {
3609 TargetOpts.Features.push_back(ReadString(Record, Idx));
3610 }
3611
3612 return Listener.ReadTargetOptions(TargetOpts, Complain);
3613}
3614
3615bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3616 ASTReaderListener &Listener) {
3617 DiagnosticOptions DiagOpts;
3618 unsigned Idx = 0;
3619#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3620#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3621 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3622#include "clang/Basic/DiagnosticOptions.def"
3623
3624 for (unsigned N = Record[Idx++]; N; --N) {
3625 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3626 }
3627
3628 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3629}
3630
3631bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3632 ASTReaderListener &Listener) {
3633 FileSystemOptions FSOpts;
3634 unsigned Idx = 0;
3635 FSOpts.WorkingDir = ReadString(Record, Idx);
3636 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3637}
3638
3639bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3640 bool Complain,
3641 ASTReaderListener &Listener) {
3642 HeaderSearchOptions HSOpts;
3643 unsigned Idx = 0;
3644 HSOpts.Sysroot = ReadString(Record, Idx);
3645
3646 // Include entries.
3647 for (unsigned N = Record[Idx++]; N; --N) {
3648 std::string Path = ReadString(Record, Idx);
3649 frontend::IncludeDirGroup Group
3650 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
3651 bool IsUserSupplied = Record[Idx++];
3652 bool IsFramework = Record[Idx++];
3653 bool IgnoreSysRoot = Record[Idx++];
3654 bool IsInternal = Record[Idx++];
3655 bool ImplicitExternC = Record[Idx++];
3656 HSOpts.UserEntries.push_back(
3657 HeaderSearchOptions::Entry(Path, Group, IsUserSupplied, IsFramework,
3658 IgnoreSysRoot, IsInternal, ImplicitExternC));
3659 }
3660
3661 // System header prefixes.
3662 for (unsigned N = Record[Idx++]; N; --N) {
3663 std::string Prefix = ReadString(Record, Idx);
3664 bool IsSystemHeader = Record[Idx++];
3665 HSOpts.SystemHeaderPrefixes.push_back(
3666 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3667 }
3668
3669 HSOpts.ResourceDir = ReadString(Record, Idx);
3670 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3671 HSOpts.DisableModuleHash = Record[Idx++];
3672 HSOpts.UseBuiltinIncludes = Record[Idx++];
3673 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3674 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3675 HSOpts.UseLibcxx = Record[Idx++];
3676
3677 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3678}
3679
3680bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
3681 bool Complain,
3682 ASTReaderListener &Listener,
3683 std::string &SuggestedPredefines) {
3684 PreprocessorOptions PPOpts;
3685 unsigned Idx = 0;
3686
3687 // Macro definitions/undefs
3688 for (unsigned N = Record[Idx++]; N; --N) {
3689 std::string Macro = ReadString(Record, Idx);
3690 bool IsUndef = Record[Idx++];
3691 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
3692 }
3693
3694 // Includes
3695 for (unsigned N = Record[Idx++]; N; --N) {
3696 PPOpts.Includes.push_back(ReadString(Record, Idx));
3697 }
3698
3699 // Macro Includes
3700 for (unsigned N = Record[Idx++]; N; --N) {
3701 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
3702 }
3703
3704 PPOpts.UsePredefines = Record[Idx++];
3705 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
3706 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
3707 PPOpts.ObjCXXARCStandardLibrary =
3708 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
3709 SuggestedPredefines.clear();
3710 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
3711 SuggestedPredefines);
3712}
3713
3714std::pair<ModuleFile *, unsigned>
3715ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
3716 GlobalPreprocessedEntityMapType::iterator
3717 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
3718 assert(I != GlobalPreprocessedEntityMap.end() &&
3719 "Corrupted global preprocessed entity map");
3720 ModuleFile *M = I->second;
3721 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
3722 return std::make_pair(M, LocalIndex);
3723}
3724
3725std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
3726ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
3727 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
3728 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
3729 Mod.NumPreprocessedEntities);
3730
3731 return std::make_pair(PreprocessingRecord::iterator(),
3732 PreprocessingRecord::iterator());
3733}
3734
3735std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
3736ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
3737 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
3738 ModuleDeclIterator(this, &Mod,
3739 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
3740}
3741
3742PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
3743 PreprocessedEntityID PPID = Index+1;
3744 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3745 ModuleFile &M = *PPInfo.first;
3746 unsigned LocalIndex = PPInfo.second;
3747 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3748
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003749 if (!PP.getPreprocessingRecord()) {
3750 Error("no preprocessing record");
3751 return 0;
3752 }
3753
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003754 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
3755 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
3756
3757 llvm::BitstreamEntry Entry =
3758 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
3759 if (Entry.Kind != llvm::BitstreamEntry::Record)
3760 return 0;
3761
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003762 // Read the record.
3763 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
3764 ReadSourceLocation(M, PPOffs.End));
3765 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
3766 const char *BlobStart = 0;
3767 unsigned BlobLen = 0;
3768 RecordData Record;
3769 PreprocessorDetailRecordTypes RecType =
3770 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003771 Entry.ID, Record, BlobStart, BlobLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003772 switch (RecType) {
3773 case PPD_MACRO_EXPANSION: {
3774 bool isBuiltin = Record[0];
3775 IdentifierInfo *Name = 0;
3776 MacroDefinition *Def = 0;
3777 if (isBuiltin)
3778 Name = getLocalIdentifier(M, Record[1]);
3779 else {
3780 PreprocessedEntityID
3781 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
3782 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
3783 }
3784
3785 MacroExpansion *ME;
3786 if (isBuiltin)
3787 ME = new (PPRec) MacroExpansion(Name, Range);
3788 else
3789 ME = new (PPRec) MacroExpansion(Def, Range);
3790
3791 return ME;
3792 }
3793
3794 case PPD_MACRO_DEFINITION: {
3795 // Decode the identifier info and then check again; if the macro is
3796 // still defined and associated with the identifier,
3797 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
3798 MacroDefinition *MD
3799 = new (PPRec) MacroDefinition(II, Range);
3800
3801 if (DeserializationListener)
3802 DeserializationListener->MacroDefinitionRead(PPID, MD);
3803
3804 return MD;
3805 }
3806
3807 case PPD_INCLUSION_DIRECTIVE: {
3808 const char *FullFileNameStart = BlobStart + Record[0];
3809 StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
3810 const FileEntry *File = 0;
3811 if (!FullFileName.empty())
3812 File = PP.getFileManager().getFile(FullFileName);
3813
3814 // FIXME: Stable encoding
3815 InclusionDirective::InclusionKind Kind
3816 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
3817 InclusionDirective *ID
3818 = new (PPRec) InclusionDirective(PPRec, Kind,
3819 StringRef(BlobStart, Record[0]),
3820 Record[1], Record[3],
3821 File,
3822 Range);
3823 return ID;
3824 }
3825 }
3826
3827 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
3828}
3829
3830/// \brief \arg SLocMapI points at a chunk of a module that contains no
3831/// preprocessed entities or the entities it contains are not the ones we are
3832/// looking for. Find the next module that contains entities and return the ID
3833/// of the first entry.
3834PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
3835 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
3836 ++SLocMapI;
3837 for (GlobalSLocOffsetMapType::const_iterator
3838 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
3839 ModuleFile &M = *SLocMapI->second;
3840 if (M.NumPreprocessedEntities)
3841 return M.BasePreprocessedEntityID;
3842 }
3843
3844 return getTotalNumPreprocessedEntities();
3845}
3846
3847namespace {
3848
3849template <unsigned PPEntityOffset::*PPLoc>
3850struct PPEntityComp {
3851 const ASTReader &Reader;
3852 ModuleFile &M;
3853
3854 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
3855
3856 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
3857 SourceLocation LHS = getLoc(L);
3858 SourceLocation RHS = getLoc(R);
3859 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3860 }
3861
3862 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
3863 SourceLocation LHS = getLoc(L);
3864 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3865 }
3866
3867 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
3868 SourceLocation RHS = getLoc(R);
3869 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
3870 }
3871
3872 SourceLocation getLoc(const PPEntityOffset &PPE) const {
3873 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
3874 }
3875};
3876
3877}
3878
3879/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
3880PreprocessedEntityID
3881ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
3882 if (SourceMgr.isLocalSourceLocation(BLoc))
3883 return getTotalNumPreprocessedEntities();
3884
3885 GlobalSLocOffsetMapType::const_iterator
3886 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3887 BLoc.getOffset());
3888 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3889 "Corrupted global sloc offset map");
3890
3891 if (SLocMapI->second->NumPreprocessedEntities == 0)
3892 return findNextPreprocessedEntity(SLocMapI);
3893
3894 ModuleFile &M = *SLocMapI->second;
3895 typedef const PPEntityOffset *pp_iterator;
3896 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3897 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3898
3899 size_t Count = M.NumPreprocessedEntities;
3900 size_t Half;
3901 pp_iterator First = pp_begin;
3902 pp_iterator PPI;
3903
3904 // Do a binary search manually instead of using std::lower_bound because
3905 // The end locations of entities may be unordered (when a macro expansion
3906 // is inside another macro argument), but for this case it is not important
3907 // whether we get the first macro expansion or its containing macro.
3908 while (Count > 0) {
3909 Half = Count/2;
3910 PPI = First;
3911 std::advance(PPI, Half);
3912 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
3913 BLoc)){
3914 First = PPI;
3915 ++First;
3916 Count = Count - Half - 1;
3917 } else
3918 Count = Half;
3919 }
3920
3921 if (PPI == pp_end)
3922 return findNextPreprocessedEntity(SLocMapI);
3923
3924 return M.BasePreprocessedEntityID + (PPI - pp_begin);
3925}
3926
3927/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
3928PreprocessedEntityID
3929ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
3930 if (SourceMgr.isLocalSourceLocation(ELoc))
3931 return getTotalNumPreprocessedEntities();
3932
3933 GlobalSLocOffsetMapType::const_iterator
3934 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3935 ELoc.getOffset());
3936 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3937 "Corrupted global sloc offset map");
3938
3939 if (SLocMapI->second->NumPreprocessedEntities == 0)
3940 return findNextPreprocessedEntity(SLocMapI);
3941
3942 ModuleFile &M = *SLocMapI->second;
3943 typedef const PPEntityOffset *pp_iterator;
3944 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3945 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3946 pp_iterator PPI =
3947 std::upper_bound(pp_begin, pp_end, ELoc,
3948 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
3949
3950 if (PPI == pp_end)
3951 return findNextPreprocessedEntity(SLocMapI);
3952
3953 return M.BasePreprocessedEntityID + (PPI - pp_begin);
3954}
3955
3956/// \brief Returns a pair of [Begin, End) indices of preallocated
3957/// preprocessed entities that \arg Range encompasses.
3958std::pair<unsigned, unsigned>
3959 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
3960 if (Range.isInvalid())
3961 return std::make_pair(0,0);
3962 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
3963
3964 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
3965 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
3966 return std::make_pair(BeginID, EndID);
3967}
3968
3969/// \brief Optionally returns true or false if the preallocated preprocessed
3970/// entity with index \arg Index came from file \arg FID.
3971llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
3972 FileID FID) {
3973 if (FID.isInvalid())
3974 return false;
3975
3976 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3977 ModuleFile &M = *PPInfo.first;
3978 unsigned LocalIndex = PPInfo.second;
3979 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3980
3981 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
3982 if (Loc.isInvalid())
3983 return false;
3984
3985 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
3986 return true;
3987 else
3988 return false;
3989}
3990
3991namespace {
3992 /// \brief Visitor used to search for information about a header file.
3993 class HeaderFileInfoVisitor {
3994 ASTReader &Reader;
3995 const FileEntry *FE;
3996
3997 llvm::Optional<HeaderFileInfo> HFI;
3998
3999 public:
4000 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4001 : Reader(Reader), FE(FE) { }
4002
4003 static bool visit(ModuleFile &M, void *UserData) {
4004 HeaderFileInfoVisitor *This
4005 = static_cast<HeaderFileInfoVisitor *>(UserData);
4006
4007 HeaderFileInfoTrait Trait(This->Reader, M,
4008 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4009 M.HeaderFileFrameworkStrings,
4010 This->FE->getName());
4011
4012 HeaderFileInfoLookupTable *Table
4013 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4014 if (!Table)
4015 return false;
4016
4017 // Look in the on-disk hash table for an entry for this file name.
4018 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4019 &Trait);
4020 if (Pos == Table->end())
4021 return false;
4022
4023 This->HFI = *Pos;
4024 return true;
4025 }
4026
4027 llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4028 };
4029}
4030
4031HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4032 HeaderFileInfoVisitor Visitor(*this, FE);
4033 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4034 if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
4035 if (Listener)
4036 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4037 return *HFI;
4038 }
4039
4040 return HeaderFileInfo();
4041}
4042
4043void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4044 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004045 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004046 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4047 ModuleFile &F = *(*I);
4048 unsigned Idx = 0;
4049 DiagStates.clear();
4050 assert(!Diag.DiagStates.empty());
4051 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4052 while (Idx < F.PragmaDiagMappings.size()) {
4053 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4054 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4055 if (DiagStateID != 0) {
4056 Diag.DiagStatePoints.push_back(
4057 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4058 FullSourceLoc(Loc, SourceMgr)));
4059 continue;
4060 }
4061
4062 assert(DiagStateID == 0);
4063 // A new DiagState was created here.
4064 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4065 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4066 DiagStates.push_back(NewState);
4067 Diag.DiagStatePoints.push_back(
4068 DiagnosticsEngine::DiagStatePoint(NewState,
4069 FullSourceLoc(Loc, SourceMgr)));
4070 while (1) {
4071 assert(Idx < F.PragmaDiagMappings.size() &&
4072 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4073 if (Idx >= F.PragmaDiagMappings.size()) {
4074 break; // Something is messed up but at least avoid infinite loop in
4075 // release build.
4076 }
4077 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4078 if (DiagID == (unsigned)-1) {
4079 break; // no more diag/map pairs for this location.
4080 }
4081 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4082 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4083 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4084 }
4085 }
4086 }
4087}
4088
4089/// \brief Get the correct cursor and offset for loading a type.
4090ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4091 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4092 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4093 ModuleFile *M = I->second;
4094 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4095}
4096
4097/// \brief Read and return the type with the given index..
4098///
4099/// The index is the type ID, shifted and minus the number of predefs. This
4100/// routine actually reads the record corresponding to the type at the given
4101/// location. It is a helper routine for GetType, which deals with reading type
4102/// IDs.
4103QualType ASTReader::readTypeRecord(unsigned Index) {
4104 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004105 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004106
4107 // Keep track of where we are in the stream, then jump back there
4108 // after reading this type.
4109 SavedStreamPosition SavedPosition(DeclsCursor);
4110
4111 ReadingKindTracker ReadingKind(Read_Type, *this);
4112
4113 // Note that we are loading a type record.
4114 Deserializing AType(this);
4115
4116 unsigned Idx = 0;
4117 DeclsCursor.JumpToBit(Loc.Offset);
4118 RecordData Record;
4119 unsigned Code = DeclsCursor.ReadCode();
4120 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
4121 case TYPE_EXT_QUAL: {
4122 if (Record.size() != 2) {
4123 Error("Incorrect encoding of extended qualifier type");
4124 return QualType();
4125 }
4126 QualType Base = readType(*Loc.F, Record, Idx);
4127 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4128 return Context.getQualifiedType(Base, Quals);
4129 }
4130
4131 case TYPE_COMPLEX: {
4132 if (Record.size() != 1) {
4133 Error("Incorrect encoding of complex type");
4134 return QualType();
4135 }
4136 QualType ElemType = readType(*Loc.F, Record, Idx);
4137 return Context.getComplexType(ElemType);
4138 }
4139
4140 case TYPE_POINTER: {
4141 if (Record.size() != 1) {
4142 Error("Incorrect encoding of pointer type");
4143 return QualType();
4144 }
4145 QualType PointeeType = readType(*Loc.F, Record, Idx);
4146 return Context.getPointerType(PointeeType);
4147 }
4148
4149 case TYPE_BLOCK_POINTER: {
4150 if (Record.size() != 1) {
4151 Error("Incorrect encoding of block pointer type");
4152 return QualType();
4153 }
4154 QualType PointeeType = readType(*Loc.F, Record, Idx);
4155 return Context.getBlockPointerType(PointeeType);
4156 }
4157
4158 case TYPE_LVALUE_REFERENCE: {
4159 if (Record.size() != 2) {
4160 Error("Incorrect encoding of lvalue reference type");
4161 return QualType();
4162 }
4163 QualType PointeeType = readType(*Loc.F, Record, Idx);
4164 return Context.getLValueReferenceType(PointeeType, Record[1]);
4165 }
4166
4167 case TYPE_RVALUE_REFERENCE: {
4168 if (Record.size() != 1) {
4169 Error("Incorrect encoding of rvalue reference type");
4170 return QualType();
4171 }
4172 QualType PointeeType = readType(*Loc.F, Record, Idx);
4173 return Context.getRValueReferenceType(PointeeType);
4174 }
4175
4176 case TYPE_MEMBER_POINTER: {
4177 if (Record.size() != 2) {
4178 Error("Incorrect encoding of member pointer type");
4179 return QualType();
4180 }
4181 QualType PointeeType = readType(*Loc.F, Record, Idx);
4182 QualType ClassType = readType(*Loc.F, Record, Idx);
4183 if (PointeeType.isNull() || ClassType.isNull())
4184 return QualType();
4185
4186 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4187 }
4188
4189 case TYPE_CONSTANT_ARRAY: {
4190 QualType ElementType = readType(*Loc.F, Record, Idx);
4191 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4192 unsigned IndexTypeQuals = Record[2];
4193 unsigned Idx = 3;
4194 llvm::APInt Size = ReadAPInt(Record, Idx);
4195 return Context.getConstantArrayType(ElementType, Size,
4196 ASM, IndexTypeQuals);
4197 }
4198
4199 case TYPE_INCOMPLETE_ARRAY: {
4200 QualType ElementType = readType(*Loc.F, Record, Idx);
4201 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4202 unsigned IndexTypeQuals = Record[2];
4203 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4204 }
4205
4206 case TYPE_VARIABLE_ARRAY: {
4207 QualType ElementType = readType(*Loc.F, Record, Idx);
4208 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4209 unsigned IndexTypeQuals = Record[2];
4210 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4211 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4212 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4213 ASM, IndexTypeQuals,
4214 SourceRange(LBLoc, RBLoc));
4215 }
4216
4217 case TYPE_VECTOR: {
4218 if (Record.size() != 3) {
4219 Error("incorrect encoding of vector type in AST file");
4220 return QualType();
4221 }
4222
4223 QualType ElementType = readType(*Loc.F, Record, Idx);
4224 unsigned NumElements = Record[1];
4225 unsigned VecKind = Record[2];
4226 return Context.getVectorType(ElementType, NumElements,
4227 (VectorType::VectorKind)VecKind);
4228 }
4229
4230 case TYPE_EXT_VECTOR: {
4231 if (Record.size() != 3) {
4232 Error("incorrect encoding of extended vector type in AST file");
4233 return QualType();
4234 }
4235
4236 QualType ElementType = readType(*Loc.F, Record, Idx);
4237 unsigned NumElements = Record[1];
4238 return Context.getExtVectorType(ElementType, NumElements);
4239 }
4240
4241 case TYPE_FUNCTION_NO_PROTO: {
4242 if (Record.size() != 6) {
4243 Error("incorrect encoding of no-proto function type");
4244 return QualType();
4245 }
4246 QualType ResultType = readType(*Loc.F, Record, Idx);
4247 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4248 (CallingConv)Record[4], Record[5]);
4249 return Context.getFunctionNoProtoType(ResultType, Info);
4250 }
4251
4252 case TYPE_FUNCTION_PROTO: {
4253 QualType ResultType = readType(*Loc.F, Record, Idx);
4254
4255 FunctionProtoType::ExtProtoInfo EPI;
4256 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4257 /*hasregparm*/ Record[2],
4258 /*regparm*/ Record[3],
4259 static_cast<CallingConv>(Record[4]),
4260 /*produces*/ Record[5]);
4261
4262 unsigned Idx = 6;
4263 unsigned NumParams = Record[Idx++];
4264 SmallVector<QualType, 16> ParamTypes;
4265 for (unsigned I = 0; I != NumParams; ++I)
4266 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4267
4268 EPI.Variadic = Record[Idx++];
4269 EPI.HasTrailingReturn = Record[Idx++];
4270 EPI.TypeQuals = Record[Idx++];
4271 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4272 ExceptionSpecificationType EST =
4273 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4274 EPI.ExceptionSpecType = EST;
4275 SmallVector<QualType, 2> Exceptions;
4276 if (EST == EST_Dynamic) {
4277 EPI.NumExceptions = Record[Idx++];
4278 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4279 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4280 EPI.Exceptions = Exceptions.data();
4281 } else if (EST == EST_ComputedNoexcept) {
4282 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4283 } else if (EST == EST_Uninstantiated) {
4284 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4285 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4286 } else if (EST == EST_Unevaluated) {
4287 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4288 }
4289 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
4290 EPI);
4291 }
4292
4293 case TYPE_UNRESOLVED_USING: {
4294 unsigned Idx = 0;
4295 return Context.getTypeDeclType(
4296 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4297 }
4298
4299 case TYPE_TYPEDEF: {
4300 if (Record.size() != 2) {
4301 Error("incorrect encoding of typedef type");
4302 return QualType();
4303 }
4304 unsigned Idx = 0;
4305 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4306 QualType Canonical = readType(*Loc.F, Record, Idx);
4307 if (!Canonical.isNull())
4308 Canonical = Context.getCanonicalType(Canonical);
4309 return Context.getTypedefType(Decl, Canonical);
4310 }
4311
4312 case TYPE_TYPEOF_EXPR:
4313 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4314
4315 case TYPE_TYPEOF: {
4316 if (Record.size() != 1) {
4317 Error("incorrect encoding of typeof(type) in AST file");
4318 return QualType();
4319 }
4320 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4321 return Context.getTypeOfType(UnderlyingType);
4322 }
4323
4324 case TYPE_DECLTYPE: {
4325 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4326 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4327 }
4328
4329 case TYPE_UNARY_TRANSFORM: {
4330 QualType BaseType = readType(*Loc.F, Record, Idx);
4331 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4332 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4333 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4334 }
4335
4336 case TYPE_AUTO:
4337 return Context.getAutoType(readType(*Loc.F, Record, Idx));
4338
4339 case TYPE_RECORD: {
4340 if (Record.size() != 2) {
4341 Error("incorrect encoding of record type");
4342 return QualType();
4343 }
4344 unsigned Idx = 0;
4345 bool IsDependent = Record[Idx++];
4346 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4347 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4348 QualType T = Context.getRecordType(RD);
4349 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4350 return T;
4351 }
4352
4353 case TYPE_ENUM: {
4354 if (Record.size() != 2) {
4355 Error("incorrect encoding of enum type");
4356 return QualType();
4357 }
4358 unsigned Idx = 0;
4359 bool IsDependent = Record[Idx++];
4360 QualType T
4361 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4362 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4363 return T;
4364 }
4365
4366 case TYPE_ATTRIBUTED: {
4367 if (Record.size() != 3) {
4368 Error("incorrect encoding of attributed type");
4369 return QualType();
4370 }
4371 QualType modifiedType = readType(*Loc.F, Record, Idx);
4372 QualType equivalentType = readType(*Loc.F, Record, Idx);
4373 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4374 return Context.getAttributedType(kind, modifiedType, equivalentType);
4375 }
4376
4377 case TYPE_PAREN: {
4378 if (Record.size() != 1) {
4379 Error("incorrect encoding of paren type");
4380 return QualType();
4381 }
4382 QualType InnerType = readType(*Loc.F, Record, Idx);
4383 return Context.getParenType(InnerType);
4384 }
4385
4386 case TYPE_PACK_EXPANSION: {
4387 if (Record.size() != 2) {
4388 Error("incorrect encoding of pack expansion type");
4389 return QualType();
4390 }
4391 QualType Pattern = readType(*Loc.F, Record, Idx);
4392 if (Pattern.isNull())
4393 return QualType();
4394 llvm::Optional<unsigned> NumExpansions;
4395 if (Record[1])
4396 NumExpansions = Record[1] - 1;
4397 return Context.getPackExpansionType(Pattern, NumExpansions);
4398 }
4399
4400 case TYPE_ELABORATED: {
4401 unsigned Idx = 0;
4402 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4403 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4404 QualType NamedType = readType(*Loc.F, Record, Idx);
4405 return Context.getElaboratedType(Keyword, NNS, NamedType);
4406 }
4407
4408 case TYPE_OBJC_INTERFACE: {
4409 unsigned Idx = 0;
4410 ObjCInterfaceDecl *ItfD
4411 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4412 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4413 }
4414
4415 case TYPE_OBJC_OBJECT: {
4416 unsigned Idx = 0;
4417 QualType Base = readType(*Loc.F, Record, Idx);
4418 unsigned NumProtos = Record[Idx++];
4419 SmallVector<ObjCProtocolDecl*, 4> Protos;
4420 for (unsigned I = 0; I != NumProtos; ++I)
4421 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4422 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4423 }
4424
4425 case TYPE_OBJC_OBJECT_POINTER: {
4426 unsigned Idx = 0;
4427 QualType Pointee = readType(*Loc.F, Record, Idx);
4428 return Context.getObjCObjectPointerType(Pointee);
4429 }
4430
4431 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4432 unsigned Idx = 0;
4433 QualType Parm = readType(*Loc.F, Record, Idx);
4434 QualType Replacement = readType(*Loc.F, Record, Idx);
4435 return
4436 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4437 Replacement);
4438 }
4439
4440 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4441 unsigned Idx = 0;
4442 QualType Parm = readType(*Loc.F, Record, Idx);
4443 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4444 return Context.getSubstTemplateTypeParmPackType(
4445 cast<TemplateTypeParmType>(Parm),
4446 ArgPack);
4447 }
4448
4449 case TYPE_INJECTED_CLASS_NAME: {
4450 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4451 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4452 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4453 // for AST reading, too much interdependencies.
4454 return
4455 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4456 }
4457
4458 case TYPE_TEMPLATE_TYPE_PARM: {
4459 unsigned Idx = 0;
4460 unsigned Depth = Record[Idx++];
4461 unsigned Index = Record[Idx++];
4462 bool Pack = Record[Idx++];
4463 TemplateTypeParmDecl *D
4464 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4465 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4466 }
4467
4468 case TYPE_DEPENDENT_NAME: {
4469 unsigned Idx = 0;
4470 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4471 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4472 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4473 QualType Canon = readType(*Loc.F, Record, Idx);
4474 if (!Canon.isNull())
4475 Canon = Context.getCanonicalType(Canon);
4476 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4477 }
4478
4479 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4480 unsigned Idx = 0;
4481 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4482 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4483 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4484 unsigned NumArgs = Record[Idx++];
4485 SmallVector<TemplateArgument, 8> Args;
4486 Args.reserve(NumArgs);
4487 while (NumArgs--)
4488 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4489 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4490 Args.size(), Args.data());
4491 }
4492
4493 case TYPE_DEPENDENT_SIZED_ARRAY: {
4494 unsigned Idx = 0;
4495
4496 // ArrayType
4497 QualType ElementType = readType(*Loc.F, Record, Idx);
4498 ArrayType::ArraySizeModifier ASM
4499 = (ArrayType::ArraySizeModifier)Record[Idx++];
4500 unsigned IndexTypeQuals = Record[Idx++];
4501
4502 // DependentSizedArrayType
4503 Expr *NumElts = ReadExpr(*Loc.F);
4504 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4505
4506 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4507 IndexTypeQuals, Brackets);
4508 }
4509
4510 case TYPE_TEMPLATE_SPECIALIZATION: {
4511 unsigned Idx = 0;
4512 bool IsDependent = Record[Idx++];
4513 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4514 SmallVector<TemplateArgument, 8> Args;
4515 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4516 QualType Underlying = readType(*Loc.F, Record, Idx);
4517 QualType T;
4518 if (Underlying.isNull())
4519 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4520 Args.size());
4521 else
4522 T = Context.getTemplateSpecializationType(Name, Args.data(),
4523 Args.size(), Underlying);
4524 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4525 return T;
4526 }
4527
4528 case TYPE_ATOMIC: {
4529 if (Record.size() != 1) {
4530 Error("Incorrect encoding of atomic type");
4531 return QualType();
4532 }
4533 QualType ValueType = readType(*Loc.F, Record, Idx);
4534 return Context.getAtomicType(ValueType);
4535 }
4536 }
4537 llvm_unreachable("Invalid TypeCode!");
4538}
4539
4540class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4541 ASTReader &Reader;
4542 ModuleFile &F;
4543 const ASTReader::RecordData &Record;
4544 unsigned &Idx;
4545
4546 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4547 unsigned &I) {
4548 return Reader.ReadSourceLocation(F, R, I);
4549 }
4550
4551 template<typename T>
4552 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4553 return Reader.ReadDeclAs<T>(F, Record, Idx);
4554 }
4555
4556public:
4557 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4558 const ASTReader::RecordData &Record, unsigned &Idx)
4559 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4560 { }
4561
4562 // We want compile-time assurance that we've enumerated all of
4563 // these, so unfortunately we have to declare them first, then
4564 // define them out-of-line.
4565#define ABSTRACT_TYPELOC(CLASS, PARENT)
4566#define TYPELOC(CLASS, PARENT) \
4567 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4568#include "clang/AST/TypeLocNodes.def"
4569
4570 void VisitFunctionTypeLoc(FunctionTypeLoc);
4571 void VisitArrayTypeLoc(ArrayTypeLoc);
4572};
4573
4574void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4575 // nothing to do
4576}
4577void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4578 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4579 if (TL.needsExtraLocalData()) {
4580 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4581 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4582 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4583 TL.setModeAttr(Record[Idx++]);
4584 }
4585}
4586void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4587 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4588}
4589void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4590 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4591}
4592void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4593 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4594}
4595void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4596 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4597}
4598void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4599 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4600}
4601void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4602 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4603 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4604}
4605void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4606 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4607 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4608 if (Record[Idx++])
4609 TL.setSizeExpr(Reader.ReadExpr(F));
4610 else
4611 TL.setSizeExpr(0);
4612}
4613void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4614 VisitArrayTypeLoc(TL);
4615}
4616void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4617 VisitArrayTypeLoc(TL);
4618}
4619void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4620 VisitArrayTypeLoc(TL);
4621}
4622void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4623 DependentSizedArrayTypeLoc TL) {
4624 VisitArrayTypeLoc(TL);
4625}
4626void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4627 DependentSizedExtVectorTypeLoc TL) {
4628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4629}
4630void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4631 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4632}
4633void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4634 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4635}
4636void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4637 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4638 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4639 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4640 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4641 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4642 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4643 }
4644}
4645void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4646 VisitFunctionTypeLoc(TL);
4647}
4648void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4649 VisitFunctionTypeLoc(TL);
4650}
4651void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4653}
4654void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4655 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4656}
4657void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4658 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4659 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4660 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4661}
4662void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4663 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4664 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4665 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4666 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4667}
4668void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4669 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4670}
4671void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4672 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4673 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4674 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4675 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4676}
4677void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4679}
4680void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4682}
4683void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
4684 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4685}
4686void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4687 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
4688 if (TL.hasAttrOperand()) {
4689 SourceRange range;
4690 range.setBegin(ReadSourceLocation(Record, Idx));
4691 range.setEnd(ReadSourceLocation(Record, Idx));
4692 TL.setAttrOperandParensRange(range);
4693 }
4694 if (TL.hasAttrExprOperand()) {
4695 if (Record[Idx++])
4696 TL.setAttrExprOperand(Reader.ReadExpr(F));
4697 else
4698 TL.setAttrExprOperand(0);
4699 } else if (TL.hasAttrEnumOperand())
4700 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
4701}
4702void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
4703 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4704}
4705void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
4706 SubstTemplateTypeParmTypeLoc TL) {
4707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4708}
4709void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
4710 SubstTemplateTypeParmPackTypeLoc TL) {
4711 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4712}
4713void TypeLocReader::VisitTemplateSpecializationTypeLoc(
4714 TemplateSpecializationTypeLoc TL) {
4715 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4716 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4717 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4718 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4719 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4720 TL.setArgLocInfo(i,
4721 Reader.GetTemplateArgumentLocInfo(F,
4722 TL.getTypePtr()->getArg(i).getKind(),
4723 Record, Idx));
4724}
4725void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
4726 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4727 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4728}
4729void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4730 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4731 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4732}
4733void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
4734 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4735}
4736void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4737 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4738 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4739 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4740}
4741void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
4742 DependentTemplateSpecializationTypeLoc TL) {
4743 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
4744 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
4745 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
4746 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
4747 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4748 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4749 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
4750 TL.setArgLocInfo(I,
4751 Reader.GetTemplateArgumentLocInfo(F,
4752 TL.getTypePtr()->getArg(I).getKind(),
4753 Record, Idx));
4754}
4755void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
4756 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
4757}
4758void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4759 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4760}
4761void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4762 TL.setHasBaseTypeAsWritten(Record[Idx++]);
4763 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
4764 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
4765 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
4766 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
4767}
4768void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4769 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4770}
4771void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4772 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4773 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4774 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4775}
4776
4777TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
4778 const RecordData &Record,
4779 unsigned &Idx) {
4780 QualType InfoTy = readType(F, Record, Idx);
4781 if (InfoTy.isNull())
4782 return 0;
4783
4784 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
4785 TypeLocReader TLR(*this, F, Record, Idx);
4786 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
4787 TLR.Visit(TL);
4788 return TInfo;
4789}
4790
4791QualType ASTReader::GetType(TypeID ID) {
4792 unsigned FastQuals = ID & Qualifiers::FastMask;
4793 unsigned Index = ID >> Qualifiers::FastWidth;
4794
4795 if (Index < NUM_PREDEF_TYPE_IDS) {
4796 QualType T;
4797 switch ((PredefinedTypeIDs)Index) {
4798 case PREDEF_TYPE_NULL_ID: return QualType();
4799 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
4800 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
4801
4802 case PREDEF_TYPE_CHAR_U_ID:
4803 case PREDEF_TYPE_CHAR_S_ID:
4804 // FIXME: Check that the signedness of CharTy is correct!
4805 T = Context.CharTy;
4806 break;
4807
4808 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
4809 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
4810 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
4811 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
4812 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
4813 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
4814 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
4815 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
4816 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
4817 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
4818 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
4819 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
4820 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
4821 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
4822 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
4823 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
4824 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
4825 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
4826 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
4827 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
4828 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
4829 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
4830 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
4831 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
4832 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
4833 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
4834 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
4835 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00004836 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
4837 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
4838 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
4839 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
4840 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
4841 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004842 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
4843
4844 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
4845 T = Context.getAutoRRefDeductType();
4846 break;
4847
4848 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
4849 T = Context.ARCUnbridgedCastTy;
4850 break;
4851
4852 case PREDEF_TYPE_VA_LIST_TAG:
4853 T = Context.getVaListTagType();
4854 break;
4855
4856 case PREDEF_TYPE_BUILTIN_FN:
4857 T = Context.BuiltinFnTy;
4858 break;
4859 }
4860
4861 assert(!T.isNull() && "Unknown predefined type");
4862 return T.withFastQualifiers(FastQuals);
4863 }
4864
4865 Index -= NUM_PREDEF_TYPE_IDS;
4866 assert(Index < TypesLoaded.size() && "Type index out-of-range");
4867 if (TypesLoaded[Index].isNull()) {
4868 TypesLoaded[Index] = readTypeRecord(Index);
4869 if (TypesLoaded[Index].isNull())
4870 return QualType();
4871
4872 TypesLoaded[Index]->setFromAST();
4873 if (DeserializationListener)
4874 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
4875 TypesLoaded[Index]);
4876 }
4877
4878 return TypesLoaded[Index].withFastQualifiers(FastQuals);
4879}
4880
4881QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
4882 return GetType(getGlobalTypeID(F, LocalID));
4883}
4884
4885serialization::TypeID
4886ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
4887 unsigned FastQuals = LocalID & Qualifiers::FastMask;
4888 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
4889
4890 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
4891 return LocalID;
4892
4893 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4894 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
4895 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
4896
4897 unsigned GlobalIndex = LocalIndex + I->second;
4898 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
4899}
4900
4901TemplateArgumentLocInfo
4902ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
4903 TemplateArgument::ArgKind Kind,
4904 const RecordData &Record,
4905 unsigned &Index) {
4906 switch (Kind) {
4907 case TemplateArgument::Expression:
4908 return ReadExpr(F);
4909 case TemplateArgument::Type:
4910 return GetTypeSourceInfo(F, Record, Index);
4911 case TemplateArgument::Template: {
4912 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4913 Index);
4914 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
4915 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
4916 SourceLocation());
4917 }
4918 case TemplateArgument::TemplateExpansion: {
4919 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4920 Index);
4921 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
4922 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
4923 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
4924 EllipsisLoc);
4925 }
4926 case TemplateArgument::Null:
4927 case TemplateArgument::Integral:
4928 case TemplateArgument::Declaration:
4929 case TemplateArgument::NullPtr:
4930 case TemplateArgument::Pack:
4931 // FIXME: Is this right?
4932 return TemplateArgumentLocInfo();
4933 }
4934 llvm_unreachable("unexpected template argument loc");
4935}
4936
4937TemplateArgumentLoc
4938ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
4939 const RecordData &Record, unsigned &Index) {
4940 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
4941
4942 if (Arg.getKind() == TemplateArgument::Expression) {
4943 if (Record[Index++]) // bool InfoHasSameExpr.
4944 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
4945 }
4946 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
4947 Record, Index));
4948}
4949
4950Decl *ASTReader::GetExternalDecl(uint32_t ID) {
4951 return GetDecl(ID);
4952}
4953
4954uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
4955 unsigned &Idx){
4956 if (Idx >= Record.size())
4957 return 0;
4958
4959 unsigned LocalID = Record[Idx++];
4960 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
4961}
4962
4963CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
4964 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004965 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004966 SavedStreamPosition SavedPosition(Cursor);
4967 Cursor.JumpToBit(Loc.Offset);
4968 ReadingKindTracker ReadingKind(Read_Decl, *this);
4969 RecordData Record;
4970 unsigned Code = Cursor.ReadCode();
4971 unsigned RecCode = Cursor.ReadRecord(Code, Record);
4972 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
4973 Error("Malformed AST file: missing C++ base specifiers");
4974 return 0;
4975 }
4976
4977 unsigned Idx = 0;
4978 unsigned NumBases = Record[Idx++];
4979 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
4980 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
4981 for (unsigned I = 0; I != NumBases; ++I)
4982 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
4983 return Bases;
4984}
4985
4986serialization::DeclID
4987ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
4988 if (LocalID < NUM_PREDEF_DECL_IDS)
4989 return LocalID;
4990
4991 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4992 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
4993 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
4994
4995 return LocalID + I->second;
4996}
4997
4998bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
4999 ModuleFile &M) const {
5000 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5001 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5002 return &M == I->second;
5003}
5004
5005ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
5006 if (!D->isFromASTFile())
5007 return 0;
5008 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5009 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5010 return I->second;
5011}
5012
5013SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5014 if (ID < NUM_PREDEF_DECL_IDS)
5015 return SourceLocation();
5016
5017 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5018
5019 if (Index > DeclsLoaded.size()) {
5020 Error("declaration ID out-of-range for AST file");
5021 return SourceLocation();
5022 }
5023
5024 if (Decl *D = DeclsLoaded[Index])
5025 return D->getLocation();
5026
5027 unsigned RawLocation = 0;
5028 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5029 return ReadSourceLocation(*Rec.F, RawLocation);
5030}
5031
5032Decl *ASTReader::GetDecl(DeclID ID) {
5033 if (ID < NUM_PREDEF_DECL_IDS) {
5034 switch ((PredefinedDeclIDs)ID) {
5035 case PREDEF_DECL_NULL_ID:
5036 return 0;
5037
5038 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5039 return Context.getTranslationUnitDecl();
5040
5041 case PREDEF_DECL_OBJC_ID_ID:
5042 return Context.getObjCIdDecl();
5043
5044 case PREDEF_DECL_OBJC_SEL_ID:
5045 return Context.getObjCSelDecl();
5046
5047 case PREDEF_DECL_OBJC_CLASS_ID:
5048 return Context.getObjCClassDecl();
5049
5050 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5051 return Context.getObjCProtocolDecl();
5052
5053 case PREDEF_DECL_INT_128_ID:
5054 return Context.getInt128Decl();
5055
5056 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5057 return Context.getUInt128Decl();
5058
5059 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5060 return Context.getObjCInstanceTypeDecl();
5061
5062 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5063 return Context.getBuiltinVaListDecl();
5064 }
5065 }
5066
5067 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5068
5069 if (Index >= DeclsLoaded.size()) {
5070 assert(0 && "declaration ID out-of-range for AST file");
5071 Error("declaration ID out-of-range for AST file");
5072 return 0;
5073 }
5074
5075 if (!DeclsLoaded[Index]) {
5076 ReadDeclRecord(ID);
5077 if (DeserializationListener)
5078 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5079 }
5080
5081 return DeclsLoaded[Index];
5082}
5083
5084DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5085 DeclID GlobalID) {
5086 if (GlobalID < NUM_PREDEF_DECL_IDS)
5087 return GlobalID;
5088
5089 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5090 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5091 ModuleFile *Owner = I->second;
5092
5093 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5094 = M.GlobalToLocalDeclIDs.find(Owner);
5095 if (Pos == M.GlobalToLocalDeclIDs.end())
5096 return 0;
5097
5098 return GlobalID - Owner->BaseDeclID + Pos->second;
5099}
5100
5101serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5102 const RecordData &Record,
5103 unsigned &Idx) {
5104 if (Idx >= Record.size()) {
5105 Error("Corrupted AST file");
5106 return 0;
5107 }
5108
5109 return getGlobalDeclID(F, Record[Idx++]);
5110}
5111
5112/// \brief Resolve the offset of a statement into a statement.
5113///
5114/// This operation will read a new statement from the external
5115/// source each time it is called, and is meant to be used via a
5116/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5117Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5118 // Switch case IDs are per Decl.
5119 ClearSwitchCaseIDs();
5120
5121 // Offset here is a global offset across the entire chain.
5122 RecordLocation Loc = getLocalBitOffset(Offset);
5123 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5124 return ReadStmtFromStream(*Loc.F);
5125}
5126
5127namespace {
5128 class FindExternalLexicalDeclsVisitor {
5129 ASTReader &Reader;
5130 const DeclContext *DC;
5131 bool (*isKindWeWant)(Decl::Kind);
5132
5133 SmallVectorImpl<Decl*> &Decls;
5134 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5135
5136 public:
5137 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5138 bool (*isKindWeWant)(Decl::Kind),
5139 SmallVectorImpl<Decl*> &Decls)
5140 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5141 {
5142 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5143 PredefsVisited[I] = false;
5144 }
5145
5146 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5147 if (Preorder)
5148 return false;
5149
5150 FindExternalLexicalDeclsVisitor *This
5151 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5152
5153 ModuleFile::DeclContextInfosMap::iterator Info
5154 = M.DeclContextInfos.find(This->DC);
5155 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5156 return false;
5157
5158 // Load all of the declaration IDs
5159 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5160 *IDE = ID + Info->second.NumLexicalDecls;
5161 ID != IDE; ++ID) {
5162 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5163 continue;
5164
5165 // Don't add predefined declarations to the lexical context more
5166 // than once.
5167 if (ID->second < NUM_PREDEF_DECL_IDS) {
5168 if (This->PredefsVisited[ID->second])
5169 continue;
5170
5171 This->PredefsVisited[ID->second] = true;
5172 }
5173
5174 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5175 if (!This->DC->isDeclInLexicalTraversal(D))
5176 This->Decls.push_back(D);
5177 }
5178 }
5179
5180 return false;
5181 }
5182 };
5183}
5184
5185ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5186 bool (*isKindWeWant)(Decl::Kind),
5187 SmallVectorImpl<Decl*> &Decls) {
5188 // There might be lexical decls in multiple modules, for the TU at
5189 // least. Walk all of the modules in the order they were loaded.
5190 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5191 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5192 ++NumLexicalDeclContextsRead;
5193 return ELR_Success;
5194}
5195
5196namespace {
5197
5198class DeclIDComp {
5199 ASTReader &Reader;
5200 ModuleFile &Mod;
5201
5202public:
5203 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5204
5205 bool operator()(LocalDeclID L, LocalDeclID R) const {
5206 SourceLocation LHS = getLocation(L);
5207 SourceLocation RHS = getLocation(R);
5208 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5209 }
5210
5211 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5212 SourceLocation RHS = getLocation(R);
5213 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5214 }
5215
5216 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5217 SourceLocation LHS = getLocation(L);
5218 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5219 }
5220
5221 SourceLocation getLocation(LocalDeclID ID) const {
5222 return Reader.getSourceManager().getFileLoc(
5223 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5224 }
5225};
5226
5227}
5228
5229void ASTReader::FindFileRegionDecls(FileID File,
5230 unsigned Offset, unsigned Length,
5231 SmallVectorImpl<Decl *> &Decls) {
5232 SourceManager &SM = getSourceManager();
5233
5234 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5235 if (I == FileDeclIDs.end())
5236 return;
5237
5238 FileDeclsInfo &DInfo = I->second;
5239 if (DInfo.Decls.empty())
5240 return;
5241
5242 SourceLocation
5243 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5244 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5245
5246 DeclIDComp DIDComp(*this, *DInfo.Mod);
5247 ArrayRef<serialization::LocalDeclID>::iterator
5248 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5249 BeginLoc, DIDComp);
5250 if (BeginIt != DInfo.Decls.begin())
5251 --BeginIt;
5252
5253 // If we are pointing at a top-level decl inside an objc container, we need
5254 // to backtrack until we find it otherwise we will fail to report that the
5255 // region overlaps with an objc container.
5256 while (BeginIt != DInfo.Decls.begin() &&
5257 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5258 ->isTopLevelDeclInObjCContainer())
5259 --BeginIt;
5260
5261 ArrayRef<serialization::LocalDeclID>::iterator
5262 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5263 EndLoc, DIDComp);
5264 if (EndIt != DInfo.Decls.end())
5265 ++EndIt;
5266
5267 for (ArrayRef<serialization::LocalDeclID>::iterator
5268 DIt = BeginIt; DIt != EndIt; ++DIt)
5269 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5270}
5271
5272namespace {
5273 /// \brief ModuleFile visitor used to perform name lookup into a
5274 /// declaration context.
5275 class DeclContextNameLookupVisitor {
5276 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005277 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005278 DeclarationName Name;
5279 SmallVectorImpl<NamedDecl *> &Decls;
5280
5281 public:
5282 DeclContextNameLookupVisitor(ASTReader &Reader,
5283 SmallVectorImpl<const DeclContext *> &Contexts,
5284 DeclarationName Name,
5285 SmallVectorImpl<NamedDecl *> &Decls)
5286 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5287
5288 static bool visit(ModuleFile &M, void *UserData) {
5289 DeclContextNameLookupVisitor *This
5290 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5291
5292 // Check whether we have any visible declaration information for
5293 // this context in this module.
5294 ModuleFile::DeclContextInfosMap::iterator Info;
5295 bool FoundInfo = false;
5296 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5297 Info = M.DeclContextInfos.find(This->Contexts[I]);
5298 if (Info != M.DeclContextInfos.end() &&
5299 Info->second.NameLookupTableData) {
5300 FoundInfo = true;
5301 break;
5302 }
5303 }
5304
5305 if (!FoundInfo)
5306 return false;
5307
5308 // Look for this name within this module.
5309 ASTDeclContextNameLookupTable *LookupTable =
5310 Info->second.NameLookupTableData;
5311 ASTDeclContextNameLookupTable::iterator Pos
5312 = LookupTable->find(This->Name);
5313 if (Pos == LookupTable->end())
5314 return false;
5315
5316 bool FoundAnything = false;
5317 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5318 for (; Data.first != Data.second; ++Data.first) {
5319 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5320 if (!ND)
5321 continue;
5322
5323 if (ND->getDeclName() != This->Name) {
5324 // A name might be null because the decl's redeclarable part is
5325 // currently read before reading its name. The lookup is triggered by
5326 // building that decl (likely indirectly), and so it is later in the
5327 // sense of "already existing" and can be ignored here.
5328 continue;
5329 }
5330
5331 // Record this declaration.
5332 FoundAnything = true;
5333 This->Decls.push_back(ND);
5334 }
5335
5336 return FoundAnything;
5337 }
5338 };
5339}
5340
5341DeclContext::lookup_result
5342ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5343 DeclarationName Name) {
5344 assert(DC->hasExternalVisibleStorage() &&
5345 "DeclContext has no visible decls in storage");
5346 if (!Name)
5347 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
5348 DeclContext::lookup_iterator(0));
5349
5350 SmallVector<NamedDecl *, 64> Decls;
5351
5352 // Compute the declaration contexts we need to look into. Multiple such
5353 // declaration contexts occur when two declaration contexts from disjoint
5354 // modules get merged, e.g., when two namespaces with the same name are
5355 // independently defined in separate modules.
5356 SmallVector<const DeclContext *, 2> Contexts;
5357 Contexts.push_back(DC);
5358
5359 if (DC->isNamespace()) {
5360 MergedDeclsMap::iterator Merged
5361 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5362 if (Merged != MergedDecls.end()) {
5363 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5364 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5365 }
5366 }
5367
5368 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
5369 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5370 ++NumVisibleDeclContextsRead;
5371 SetExternalVisibleDeclsForName(DC, Name, Decls);
5372 return const_cast<DeclContext*>(DC)->lookup(Name);
5373}
5374
5375namespace {
5376 /// \brief ModuleFile visitor used to retrieve all visible names in a
5377 /// declaration context.
5378 class DeclContextAllNamesVisitor {
5379 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005380 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005381 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005382 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005383
5384 public:
5385 DeclContextAllNamesVisitor(ASTReader &Reader,
5386 SmallVectorImpl<const DeclContext *> &Contexts,
5387 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005388 SmallVector<NamedDecl *, 8> > &Decls,
5389 bool VisitAll)
5390 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005391
5392 static bool visit(ModuleFile &M, void *UserData) {
5393 DeclContextAllNamesVisitor *This
5394 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5395
5396 // Check whether we have any visible declaration information for
5397 // this context in this module.
5398 ModuleFile::DeclContextInfosMap::iterator Info;
5399 bool FoundInfo = false;
5400 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5401 Info = M.DeclContextInfos.find(This->Contexts[I]);
5402 if (Info != M.DeclContextInfos.end() &&
5403 Info->second.NameLookupTableData) {
5404 FoundInfo = true;
5405 break;
5406 }
5407 }
5408
5409 if (!FoundInfo)
5410 return false;
5411
5412 ASTDeclContextNameLookupTable *LookupTable =
5413 Info->second.NameLookupTableData;
5414 bool FoundAnything = false;
5415 for (ASTDeclContextNameLookupTable::data_iterator
5416 I = LookupTable->data_begin(), E = LookupTable->data_end();
5417 I != E; ++I) {
5418 ASTDeclContextNameLookupTrait::data_type Data = *I;
5419 for (; Data.first != Data.second; ++Data.first) {
5420 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5421 *Data.first);
5422 if (!ND)
5423 continue;
5424
5425 // Record this declaration.
5426 FoundAnything = true;
5427 This->Decls[ND->getDeclName()].push_back(ND);
5428 }
5429 }
5430
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005431 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005432 }
5433 };
5434}
5435
5436void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5437 if (!DC->hasExternalVisibleStorage())
5438 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005439 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005440
5441 // Compute the declaration contexts we need to look into. Multiple such
5442 // declaration contexts occur when two declaration contexts from disjoint
5443 // modules get merged, e.g., when two namespaces with the same name are
5444 // independently defined in separate modules.
5445 SmallVector<const DeclContext *, 2> Contexts;
5446 Contexts.push_back(DC);
5447
5448 if (DC->isNamespace()) {
5449 MergedDeclsMap::iterator Merged
5450 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5451 if (Merged != MergedDecls.end()) {
5452 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5453 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5454 }
5455 }
5456
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005457 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5458 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005459 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5460 ++NumVisibleDeclContextsRead;
5461
5462 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005463 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005464 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5465 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5466 }
5467 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5468}
5469
5470/// \brief Under non-PCH compilation the consumer receives the objc methods
5471/// before receiving the implementation, and codegen depends on this.
5472/// We simulate this by deserializing and passing to consumer the methods of the
5473/// implementation before passing the deserialized implementation decl.
5474static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5475 ASTConsumer *Consumer) {
5476 assert(ImplD && Consumer);
5477
5478 for (ObjCImplDecl::method_iterator
5479 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5480 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5481
5482 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5483}
5484
5485void ASTReader::PassInterestingDeclsToConsumer() {
5486 assert(Consumer);
5487 while (!InterestingDecls.empty()) {
5488 Decl *D = InterestingDecls.front();
5489 InterestingDecls.pop_front();
5490
5491 PassInterestingDeclToConsumer(D);
5492 }
5493}
5494
5495void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5496 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5497 PassObjCImplDeclToConsumer(ImplD, Consumer);
5498 else
5499 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5500}
5501
5502void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5503 this->Consumer = Consumer;
5504
5505 if (!Consumer)
5506 return;
5507
5508 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5509 // Force deserialization of this decl, which will cause it to be queued for
5510 // passing to the consumer.
5511 GetDecl(ExternalDefinitions[I]);
5512 }
5513 ExternalDefinitions.clear();
5514
5515 PassInterestingDeclsToConsumer();
5516}
5517
5518void ASTReader::PrintStats() {
5519 std::fprintf(stderr, "*** AST File Statistics:\n");
5520
5521 unsigned NumTypesLoaded
5522 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5523 QualType());
5524 unsigned NumDeclsLoaded
5525 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5526 (Decl *)0);
5527 unsigned NumIdentifiersLoaded
5528 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5529 IdentifiersLoaded.end(),
5530 (IdentifierInfo *)0);
5531 unsigned NumMacrosLoaded
5532 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5533 MacrosLoaded.end(),
5534 (MacroInfo *)0);
5535 unsigned NumSelectorsLoaded
5536 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5537 SelectorsLoaded.end(),
5538 Selector());
5539
5540 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5541 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5542 NumSLocEntriesRead, TotalNumSLocEntries,
5543 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5544 if (!TypesLoaded.empty())
5545 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5546 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5547 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5548 if (!DeclsLoaded.empty())
5549 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5550 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5551 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5552 if (!IdentifiersLoaded.empty())
5553 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5554 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5555 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5556 if (!MacrosLoaded.empty())
5557 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5558 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5559 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5560 if (!SelectorsLoaded.empty())
5561 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5562 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5563 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5564 if (TotalNumStatements)
5565 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5566 NumStatementsRead, TotalNumStatements,
5567 ((float)NumStatementsRead/TotalNumStatements * 100));
5568 if (TotalNumMacros)
5569 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5570 NumMacrosRead, TotalNumMacros,
5571 ((float)NumMacrosRead/TotalNumMacros * 100));
5572 if (TotalLexicalDeclContexts)
5573 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5574 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5575 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5576 * 100));
5577 if (TotalVisibleDeclContexts)
5578 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5579 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5580 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5581 * 100));
5582 if (TotalNumMethodPoolEntries) {
5583 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5584 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5585 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5586 * 100));
5587 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
5588 }
5589 std::fprintf(stderr, "\n");
5590 dump();
5591 std::fprintf(stderr, "\n");
5592}
5593
5594template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5595static void
5596dumpModuleIDMap(StringRef Name,
5597 const ContinuousRangeMap<Key, ModuleFile *,
5598 InitialCapacity> &Map) {
5599 if (Map.begin() == Map.end())
5600 return;
5601
5602 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5603 llvm::errs() << Name << ":\n";
5604 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5605 I != IEnd; ++I) {
5606 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5607 << "\n";
5608 }
5609}
5610
5611void ASTReader::dump() {
5612 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5613 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5614 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5615 dumpModuleIDMap("Global type map", GlobalTypeMap);
5616 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5617 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5618 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5619 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5620 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5621 dumpModuleIDMap("Global preprocessed entity map",
5622 GlobalPreprocessedEntityMap);
5623
5624 llvm::errs() << "\n*** PCH/Modules Loaded:";
5625 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5626 MEnd = ModuleMgr.end();
5627 M != MEnd; ++M)
5628 (*M)->dump();
5629}
5630
5631/// Return the amount of memory used by memory buffers, breaking down
5632/// by heap-backed versus mmap'ed memory.
5633void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
5634 for (ModuleConstIterator I = ModuleMgr.begin(),
5635 E = ModuleMgr.end(); I != E; ++I) {
5636 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
5637 size_t bytes = buf->getBufferSize();
5638 switch (buf->getBufferKind()) {
5639 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
5640 sizes.malloc_bytes += bytes;
5641 break;
5642 case llvm::MemoryBuffer::MemoryBuffer_MMap:
5643 sizes.mmap_bytes += bytes;
5644 break;
5645 }
5646 }
5647 }
5648}
5649
5650void ASTReader::InitializeSema(Sema &S) {
5651 SemaObj = &S;
5652 S.addExternalSource(this);
5653
5654 // Makes sure any declarations that were deserialized "too early"
5655 // still get added to the identifier's declaration chains.
5656 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
5657 SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
5658 PreloadedDecls[I]->getDeclName());
5659 }
5660 PreloadedDecls.clear();
5661
5662 // Load the offsets of the declarations that Sema references.
5663 // They will be lazily deserialized when needed.
5664 if (!SemaDeclRefs.empty()) {
5665 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
5666 if (!SemaObj->StdNamespace)
5667 SemaObj->StdNamespace = SemaDeclRefs[0];
5668 if (!SemaObj->StdBadAlloc)
5669 SemaObj->StdBadAlloc = SemaDeclRefs[1];
5670 }
5671
5672 if (!FPPragmaOptions.empty()) {
5673 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
5674 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
5675 }
5676
5677 if (!OpenCLExtensions.empty()) {
5678 unsigned I = 0;
5679#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
5680#include "clang/Basic/OpenCLExtensions.def"
5681
5682 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
5683 }
5684}
5685
5686IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
5687 // Note that we are loading an identifier.
5688 Deserializing AnIdentifier(this);
5689
5690 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
5691 /*PriorGeneration=*/0);
5692 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
5693 IdentifierInfo *II = Visitor.getIdentifierInfo();
5694 markIdentifierUpToDate(II);
5695 return II;
5696}
5697
5698namespace clang {
5699 /// \brief An identifier-lookup iterator that enumerates all of the
5700 /// identifiers stored within a set of AST files.
5701 class ASTIdentifierIterator : public IdentifierIterator {
5702 /// \brief The AST reader whose identifiers are being enumerated.
5703 const ASTReader &Reader;
5704
5705 /// \brief The current index into the chain of AST files stored in
5706 /// the AST reader.
5707 unsigned Index;
5708
5709 /// \brief The current position within the identifier lookup table
5710 /// of the current AST file.
5711 ASTIdentifierLookupTable::key_iterator Current;
5712
5713 /// \brief The end position within the identifier lookup table of
5714 /// the current AST file.
5715 ASTIdentifierLookupTable::key_iterator End;
5716
5717 public:
5718 explicit ASTIdentifierIterator(const ASTReader &Reader);
5719
5720 virtual StringRef Next();
5721 };
5722}
5723
5724ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
5725 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
5726 ASTIdentifierLookupTable *IdTable
5727 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
5728 Current = IdTable->key_begin();
5729 End = IdTable->key_end();
5730}
5731
5732StringRef ASTIdentifierIterator::Next() {
5733 while (Current == End) {
5734 // If we have exhausted all of our AST files, we're done.
5735 if (Index == 0)
5736 return StringRef();
5737
5738 --Index;
5739 ASTIdentifierLookupTable *IdTable
5740 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
5741 IdentifierLookupTable;
5742 Current = IdTable->key_begin();
5743 End = IdTable->key_end();
5744 }
5745
5746 // We have any identifiers remaining in the current AST file; return
5747 // the next one.
5748 std::pair<const char*, unsigned> Key = *Current;
5749 ++Current;
5750 return StringRef(Key.first, Key.second);
5751}
5752
5753IdentifierIterator *ASTReader::getIdentifiers() const {
5754 return new ASTIdentifierIterator(*this);
5755}
5756
5757namespace clang { namespace serialization {
5758 class ReadMethodPoolVisitor {
5759 ASTReader &Reader;
5760 Selector Sel;
5761 unsigned PriorGeneration;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005762 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
5763 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005764
5765 public:
5766 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
5767 unsigned PriorGeneration)
5768 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
5769
5770 static bool visit(ModuleFile &M, void *UserData) {
5771 ReadMethodPoolVisitor *This
5772 = static_cast<ReadMethodPoolVisitor *>(UserData);
5773
5774 if (!M.SelectorLookupTable)
5775 return false;
5776
5777 // If we've already searched this module file, skip it now.
5778 if (M.Generation <= This->PriorGeneration)
5779 return true;
5780
5781 ASTSelectorLookupTable *PoolTable
5782 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
5783 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
5784 if (Pos == PoolTable->end())
5785 return false;
5786
5787 ++This->Reader.NumSelectorsRead;
5788 // FIXME: Not quite happy with the statistics here. We probably should
5789 // disable this tracking when called via LoadSelector.
5790 // Also, should entries without methods count as misses?
5791 ++This->Reader.NumMethodPoolEntriesRead;
5792 ASTSelectorLookupTrait::data_type Data = *Pos;
5793 if (This->Reader.DeserializationListener)
5794 This->Reader.DeserializationListener->SelectorRead(Data.ID,
5795 This->Sel);
5796
5797 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
5798 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
5799 return true;
5800 }
5801
5802 /// \brief Retrieve the instance methods found by this visitor.
5803 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
5804 return InstanceMethods;
5805 }
5806
5807 /// \brief Retrieve the instance methods found by this visitor.
5808 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
5809 return FactoryMethods;
5810 }
5811 };
5812} } // end namespace clang::serialization
5813
5814/// \brief Add the given set of methods to the method list.
5815static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
5816 ObjCMethodList &List) {
5817 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
5818 S.addMethodToGlobalList(&List, Methods[I]);
5819 }
5820}
5821
5822void ASTReader::ReadMethodPool(Selector Sel) {
5823 // Get the selector generation and update it to the current generation.
5824 unsigned &Generation = SelectorGeneration[Sel];
5825 unsigned PriorGeneration = Generation;
5826 Generation = CurrentGeneration;
5827
5828 // Search for methods defined with this selector.
5829 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
5830 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
5831
5832 if (Visitor.getInstanceMethods().empty() &&
5833 Visitor.getFactoryMethods().empty()) {
5834 ++NumMethodPoolMisses;
5835 return;
5836 }
5837
5838 if (!getSema())
5839 return;
5840
5841 Sema &S = *getSema();
5842 Sema::GlobalMethodPool::iterator Pos
5843 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
5844
5845 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
5846 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
5847}
5848
5849void ASTReader::ReadKnownNamespaces(
5850 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
5851 Namespaces.clear();
5852
5853 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
5854 if (NamespaceDecl *Namespace
5855 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
5856 Namespaces.push_back(Namespace);
5857 }
5858}
5859
5860void ASTReader::ReadTentativeDefinitions(
5861 SmallVectorImpl<VarDecl *> &TentativeDefs) {
5862 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
5863 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
5864 if (Var)
5865 TentativeDefs.push_back(Var);
5866 }
5867 TentativeDefinitions.clear();
5868}
5869
5870void ASTReader::ReadUnusedFileScopedDecls(
5871 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
5872 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
5873 DeclaratorDecl *D
5874 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
5875 if (D)
5876 Decls.push_back(D);
5877 }
5878 UnusedFileScopedDecls.clear();
5879}
5880
5881void ASTReader::ReadDelegatingConstructors(
5882 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
5883 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
5884 CXXConstructorDecl *D
5885 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
5886 if (D)
5887 Decls.push_back(D);
5888 }
5889 DelegatingCtorDecls.clear();
5890}
5891
5892void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
5893 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
5894 TypedefNameDecl *D
5895 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
5896 if (D)
5897 Decls.push_back(D);
5898 }
5899 ExtVectorDecls.clear();
5900}
5901
5902void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
5903 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
5904 CXXRecordDecl *D
5905 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
5906 if (D)
5907 Decls.push_back(D);
5908 }
5909 DynamicClasses.clear();
5910}
5911
5912void
Richard Smith5ea6ef42013-01-10 23:43:47 +00005913ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
5914 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
5915 NamedDecl *D
5916 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005917 if (D)
5918 Decls.push_back(D);
5919 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00005920 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005921}
5922
5923void ASTReader::ReadReferencedSelectors(
5924 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
5925 if (ReferencedSelectorsData.empty())
5926 return;
5927
5928 // If there are @selector references added them to its pool. This is for
5929 // implementation of -Wselector.
5930 unsigned int DataSize = ReferencedSelectorsData.size()-1;
5931 unsigned I = 0;
5932 while (I < DataSize) {
5933 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
5934 SourceLocation SelLoc
5935 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
5936 Sels.push_back(std::make_pair(Sel, SelLoc));
5937 }
5938 ReferencedSelectorsData.clear();
5939}
5940
5941void ASTReader::ReadWeakUndeclaredIdentifiers(
5942 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
5943 if (WeakUndeclaredIdentifiers.empty())
5944 return;
5945
5946 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
5947 IdentifierInfo *WeakId
5948 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
5949 IdentifierInfo *AliasId
5950 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
5951 SourceLocation Loc
5952 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
5953 bool Used = WeakUndeclaredIdentifiers[I++];
5954 WeakInfo WI(AliasId, Loc);
5955 WI.setUsed(Used);
5956 WeakIDs.push_back(std::make_pair(WeakId, WI));
5957 }
5958 WeakUndeclaredIdentifiers.clear();
5959}
5960
5961void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
5962 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
5963 ExternalVTableUse VT;
5964 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
5965 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
5966 VT.DefinitionRequired = VTableUses[Idx++];
5967 VTables.push_back(VT);
5968 }
5969
5970 VTableUses.clear();
5971}
5972
5973void ASTReader::ReadPendingInstantiations(
5974 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
5975 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
5976 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
5977 SourceLocation Loc
5978 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
5979
5980 Pending.push_back(std::make_pair(D, Loc));
5981 }
5982 PendingInstantiations.clear();
5983}
5984
5985void ASTReader::LoadSelector(Selector Sel) {
5986 // It would be complicated to avoid reading the methods anyway. So don't.
5987 ReadMethodPool(Sel);
5988}
5989
5990void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
5991 assert(ID && "Non-zero identifier ID required");
5992 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
5993 IdentifiersLoaded[ID - 1] = II;
5994 if (DeserializationListener)
5995 DeserializationListener->IdentifierRead(ID, II);
5996}
5997
5998/// \brief Set the globally-visible declarations associated with the given
5999/// identifier.
6000///
6001/// If the AST reader is currently in a state where the given declaration IDs
6002/// cannot safely be resolved, they are queued until it is safe to resolve
6003/// them.
6004///
6005/// \param II an IdentifierInfo that refers to one or more globally-visible
6006/// declarations.
6007///
6008/// \param DeclIDs the set of declaration IDs with the name @p II that are
6009/// visible at global scope.
6010///
6011/// \param Nonrecursive should be true to indicate that the caller knows that
6012/// this call is non-recursive, and therefore the globally-visible declarations
6013/// will not be placed onto the pending queue.
6014void
6015ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6016 const SmallVectorImpl<uint32_t> &DeclIDs,
6017 bool Nonrecursive) {
6018 if (NumCurrentElementsDeserializing && !Nonrecursive) {
6019 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
6020 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
6021 PII.II = II;
6022 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
6023 return;
6024 }
6025
6026 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6027 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6028 if (SemaObj) {
6029 // Introduce this declaration into the translation-unit scope
6030 // and add it to the declaration chain for this identifier, so
6031 // that (unqualified) name lookup will find it.
6032 SemaObj->pushExternalDeclIntoScope(D, II);
6033 } else {
6034 // Queue this declaration so that it will be added to the
6035 // translation unit scope and identifier's declaration chain
6036 // once a Sema object is known.
6037 PreloadedDecls.push_back(D);
6038 }
6039 }
6040}
6041
6042IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
6043 if (ID == 0)
6044 return 0;
6045
6046 if (IdentifiersLoaded.empty()) {
6047 Error("no identifier table in AST file");
6048 return 0;
6049 }
6050
6051 ID -= 1;
6052 if (!IdentifiersLoaded[ID]) {
6053 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6054 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6055 ModuleFile *M = I->second;
6056 unsigned Index = ID - M->BaseIdentifierID;
6057 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6058
6059 // All of the strings in the AST file are preceded by a 16-bit length.
6060 // Extract that 16-bit length to avoid having to execute strlen().
6061 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6062 // unsigned integers. This is important to avoid integer overflow when
6063 // we cast them to 'unsigned'.
6064 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6065 unsigned StrLen = (((unsigned) StrLenPtr[0])
6066 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
6067 IdentifiersLoaded[ID]
6068 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
6069 if (DeserializationListener)
6070 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6071 }
6072
6073 return IdentifiersLoaded[ID];
6074}
6075
6076IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6077 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6078}
6079
6080IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6081 if (LocalID < NUM_PREDEF_IDENT_IDS)
6082 return LocalID;
6083
6084 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6085 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6086 assert(I != M.IdentifierRemap.end()
6087 && "Invalid index into identifier index remap");
6088
6089 return LocalID + I->second;
6090}
6091
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00006092MacroInfo *ASTReader::getMacro(MacroID ID, MacroInfo *Hint) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006093 if (ID == 0)
6094 return 0;
6095
6096 if (MacrosLoaded.empty()) {
6097 Error("no macro table in AST file");
6098 return 0;
6099 }
6100
6101 ID -= NUM_PREDEF_MACRO_IDS;
6102 if (!MacrosLoaded[ID]) {
6103 GlobalMacroMapType::iterator I
6104 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6105 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6106 ModuleFile *M = I->second;
6107 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00006108 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006109 }
6110
6111 return MacrosLoaded[ID];
6112}
6113
6114MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6115 if (LocalID < NUM_PREDEF_MACRO_IDS)
6116 return LocalID;
6117
6118 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6119 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6120 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6121
6122 return LocalID + I->second;
6123}
6124
6125serialization::SubmoduleID
6126ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6127 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6128 return LocalID;
6129
6130 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6131 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6132 assert(I != M.SubmoduleRemap.end()
6133 && "Invalid index into submodule index remap");
6134
6135 return LocalID + I->second;
6136}
6137
6138Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6139 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6140 assert(GlobalID == 0 && "Unhandled global submodule ID");
6141 return 0;
6142 }
6143
6144 if (GlobalID > SubmodulesLoaded.size()) {
6145 Error("submodule ID out of range in AST file");
6146 return 0;
6147 }
6148
6149 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6150}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006151
6152Module *ASTReader::getModule(unsigned ID) {
6153 return getSubmodule(ID);
6154}
6155
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006156Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6157 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6158}
6159
6160Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6161 if (ID == 0)
6162 return Selector();
6163
6164 if (ID > SelectorsLoaded.size()) {
6165 Error("selector ID out of range in AST file");
6166 return Selector();
6167 }
6168
6169 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6170 // Load this selector from the selector table.
6171 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6172 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6173 ModuleFile &M = *I->second;
6174 ASTSelectorLookupTrait Trait(*this, M);
6175 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6176 SelectorsLoaded[ID - 1] =
6177 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6178 if (DeserializationListener)
6179 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6180 }
6181
6182 return SelectorsLoaded[ID - 1];
6183}
6184
6185Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6186 return DecodeSelector(ID);
6187}
6188
6189uint32_t ASTReader::GetNumExternalSelectors() {
6190 // ID 0 (the null selector) is considered an external selector.
6191 return getTotalNumSelectors() + 1;
6192}
6193
6194serialization::SelectorID
6195ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6196 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6197 return LocalID;
6198
6199 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6200 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6201 assert(I != M.SelectorRemap.end()
6202 && "Invalid index into selector index remap");
6203
6204 return LocalID + I->second;
6205}
6206
6207DeclarationName
6208ASTReader::ReadDeclarationName(ModuleFile &F,
6209 const RecordData &Record, unsigned &Idx) {
6210 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6211 switch (Kind) {
6212 case DeclarationName::Identifier:
6213 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
6214
6215 case DeclarationName::ObjCZeroArgSelector:
6216 case DeclarationName::ObjCOneArgSelector:
6217 case DeclarationName::ObjCMultiArgSelector:
6218 return DeclarationName(ReadSelector(F, Record, Idx));
6219
6220 case DeclarationName::CXXConstructorName:
6221 return Context.DeclarationNames.getCXXConstructorName(
6222 Context.getCanonicalType(readType(F, Record, Idx)));
6223
6224 case DeclarationName::CXXDestructorName:
6225 return Context.DeclarationNames.getCXXDestructorName(
6226 Context.getCanonicalType(readType(F, Record, Idx)));
6227
6228 case DeclarationName::CXXConversionFunctionName:
6229 return Context.DeclarationNames.getCXXConversionFunctionName(
6230 Context.getCanonicalType(readType(F, Record, Idx)));
6231
6232 case DeclarationName::CXXOperatorName:
6233 return Context.DeclarationNames.getCXXOperatorName(
6234 (OverloadedOperatorKind)Record[Idx++]);
6235
6236 case DeclarationName::CXXLiteralOperatorName:
6237 return Context.DeclarationNames.getCXXLiteralOperatorName(
6238 GetIdentifierInfo(F, Record, Idx));
6239
6240 case DeclarationName::CXXUsingDirective:
6241 return DeclarationName::getUsingDirectiveName();
6242 }
6243
6244 llvm_unreachable("Invalid NameKind!");
6245}
6246
6247void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6248 DeclarationNameLoc &DNLoc,
6249 DeclarationName Name,
6250 const RecordData &Record, unsigned &Idx) {
6251 switch (Name.getNameKind()) {
6252 case DeclarationName::CXXConstructorName:
6253 case DeclarationName::CXXDestructorName:
6254 case DeclarationName::CXXConversionFunctionName:
6255 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6256 break;
6257
6258 case DeclarationName::CXXOperatorName:
6259 DNLoc.CXXOperatorName.BeginOpNameLoc
6260 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6261 DNLoc.CXXOperatorName.EndOpNameLoc
6262 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6263 break;
6264
6265 case DeclarationName::CXXLiteralOperatorName:
6266 DNLoc.CXXLiteralOperatorName.OpNameLoc
6267 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6268 break;
6269
6270 case DeclarationName::Identifier:
6271 case DeclarationName::ObjCZeroArgSelector:
6272 case DeclarationName::ObjCOneArgSelector:
6273 case DeclarationName::ObjCMultiArgSelector:
6274 case DeclarationName::CXXUsingDirective:
6275 break;
6276 }
6277}
6278
6279void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6280 DeclarationNameInfo &NameInfo,
6281 const RecordData &Record, unsigned &Idx) {
6282 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6283 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6284 DeclarationNameLoc DNLoc;
6285 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6286 NameInfo.setInfo(DNLoc);
6287}
6288
6289void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6290 const RecordData &Record, unsigned &Idx) {
6291 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6292 unsigned NumTPLists = Record[Idx++];
6293 Info.NumTemplParamLists = NumTPLists;
6294 if (NumTPLists) {
6295 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6296 for (unsigned i=0; i != NumTPLists; ++i)
6297 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6298 }
6299}
6300
6301TemplateName
6302ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6303 unsigned &Idx) {
6304 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6305 switch (Kind) {
6306 case TemplateName::Template:
6307 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6308
6309 case TemplateName::OverloadedTemplate: {
6310 unsigned size = Record[Idx++];
6311 UnresolvedSet<8> Decls;
6312 while (size--)
6313 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6314
6315 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6316 }
6317
6318 case TemplateName::QualifiedTemplate: {
6319 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6320 bool hasTemplKeyword = Record[Idx++];
6321 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6322 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6323 }
6324
6325 case TemplateName::DependentTemplate: {
6326 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6327 if (Record[Idx++]) // isIdentifier
6328 return Context.getDependentTemplateName(NNS,
6329 GetIdentifierInfo(F, Record,
6330 Idx));
6331 return Context.getDependentTemplateName(NNS,
6332 (OverloadedOperatorKind)Record[Idx++]);
6333 }
6334
6335 case TemplateName::SubstTemplateTemplateParm: {
6336 TemplateTemplateParmDecl *param
6337 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6338 if (!param) return TemplateName();
6339 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6340 return Context.getSubstTemplateTemplateParm(param, replacement);
6341 }
6342
6343 case TemplateName::SubstTemplateTemplateParmPack: {
6344 TemplateTemplateParmDecl *Param
6345 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6346 if (!Param)
6347 return TemplateName();
6348
6349 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6350 if (ArgPack.getKind() != TemplateArgument::Pack)
6351 return TemplateName();
6352
6353 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6354 }
6355 }
6356
6357 llvm_unreachable("Unhandled template name kind!");
6358}
6359
6360TemplateArgument
6361ASTReader::ReadTemplateArgument(ModuleFile &F,
6362 const RecordData &Record, unsigned &Idx) {
6363 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6364 switch (Kind) {
6365 case TemplateArgument::Null:
6366 return TemplateArgument();
6367 case TemplateArgument::Type:
6368 return TemplateArgument(readType(F, Record, Idx));
6369 case TemplateArgument::Declaration: {
6370 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6371 bool ForReferenceParam = Record[Idx++];
6372 return TemplateArgument(D, ForReferenceParam);
6373 }
6374 case TemplateArgument::NullPtr:
6375 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6376 case TemplateArgument::Integral: {
6377 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6378 QualType T = readType(F, Record, Idx);
6379 return TemplateArgument(Context, Value, T);
6380 }
6381 case TemplateArgument::Template:
6382 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6383 case TemplateArgument::TemplateExpansion: {
6384 TemplateName Name = ReadTemplateName(F, Record, Idx);
6385 llvm::Optional<unsigned> NumTemplateExpansions;
6386 if (unsigned NumExpansions = Record[Idx++])
6387 NumTemplateExpansions = NumExpansions - 1;
6388 return TemplateArgument(Name, NumTemplateExpansions);
6389 }
6390 case TemplateArgument::Expression:
6391 return TemplateArgument(ReadExpr(F));
6392 case TemplateArgument::Pack: {
6393 unsigned NumArgs = Record[Idx++];
6394 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6395 for (unsigned I = 0; I != NumArgs; ++I)
6396 Args[I] = ReadTemplateArgument(F, Record, Idx);
6397 return TemplateArgument(Args, NumArgs);
6398 }
6399 }
6400
6401 llvm_unreachable("Unhandled template argument kind!");
6402}
6403
6404TemplateParameterList *
6405ASTReader::ReadTemplateParameterList(ModuleFile &F,
6406 const RecordData &Record, unsigned &Idx) {
6407 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6408 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6409 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6410
6411 unsigned NumParams = Record[Idx++];
6412 SmallVector<NamedDecl *, 16> Params;
6413 Params.reserve(NumParams);
6414 while (NumParams--)
6415 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6416
6417 TemplateParameterList* TemplateParams =
6418 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6419 Params.data(), Params.size(), RAngleLoc);
6420 return TemplateParams;
6421}
6422
6423void
6424ASTReader::
6425ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6426 ModuleFile &F, const RecordData &Record,
6427 unsigned &Idx) {
6428 unsigned NumTemplateArgs = Record[Idx++];
6429 TemplArgs.reserve(NumTemplateArgs);
6430 while (NumTemplateArgs--)
6431 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6432}
6433
6434/// \brief Read a UnresolvedSet structure.
6435void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6436 const RecordData &Record, unsigned &Idx) {
6437 unsigned NumDecls = Record[Idx++];
6438 Set.reserve(Context, NumDecls);
6439 while (NumDecls--) {
6440 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6441 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6442 Set.addDecl(Context, D, AS);
6443 }
6444}
6445
6446CXXBaseSpecifier
6447ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6448 const RecordData &Record, unsigned &Idx) {
6449 bool isVirtual = static_cast<bool>(Record[Idx++]);
6450 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6451 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6452 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6453 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6454 SourceRange Range = ReadSourceRange(F, Record, Idx);
6455 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6456 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6457 EllipsisLoc);
6458 Result.setInheritConstructors(inheritConstructors);
6459 return Result;
6460}
6461
6462std::pair<CXXCtorInitializer **, unsigned>
6463ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6464 unsigned &Idx) {
6465 CXXCtorInitializer **CtorInitializers = 0;
6466 unsigned NumInitializers = Record[Idx++];
6467 if (NumInitializers) {
6468 CtorInitializers
6469 = new (Context) CXXCtorInitializer*[NumInitializers];
6470 for (unsigned i=0; i != NumInitializers; ++i) {
6471 TypeSourceInfo *TInfo = 0;
6472 bool IsBaseVirtual = false;
6473 FieldDecl *Member = 0;
6474 IndirectFieldDecl *IndirectMember = 0;
6475
6476 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6477 switch (Type) {
6478 case CTOR_INITIALIZER_BASE:
6479 TInfo = GetTypeSourceInfo(F, Record, Idx);
6480 IsBaseVirtual = Record[Idx++];
6481 break;
6482
6483 case CTOR_INITIALIZER_DELEGATING:
6484 TInfo = GetTypeSourceInfo(F, Record, Idx);
6485 break;
6486
6487 case CTOR_INITIALIZER_MEMBER:
6488 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6489 break;
6490
6491 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6492 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6493 break;
6494 }
6495
6496 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6497 Expr *Init = ReadExpr(F);
6498 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6499 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6500 bool IsWritten = Record[Idx++];
6501 unsigned SourceOrderOrNumArrayIndices;
6502 SmallVector<VarDecl *, 8> Indices;
6503 if (IsWritten) {
6504 SourceOrderOrNumArrayIndices = Record[Idx++];
6505 } else {
6506 SourceOrderOrNumArrayIndices = Record[Idx++];
6507 Indices.reserve(SourceOrderOrNumArrayIndices);
6508 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6509 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6510 }
6511
6512 CXXCtorInitializer *BOMInit;
6513 if (Type == CTOR_INITIALIZER_BASE) {
6514 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6515 LParenLoc, Init, RParenLoc,
6516 MemberOrEllipsisLoc);
6517 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6518 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6519 Init, RParenLoc);
6520 } else if (IsWritten) {
6521 if (Member)
6522 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6523 LParenLoc, Init, RParenLoc);
6524 else
6525 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6526 MemberOrEllipsisLoc, LParenLoc,
6527 Init, RParenLoc);
6528 } else {
6529 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6530 LParenLoc, Init, RParenLoc,
6531 Indices.data(), Indices.size());
6532 }
6533
6534 if (IsWritten)
6535 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6536 CtorInitializers[i] = BOMInit;
6537 }
6538 }
6539
6540 return std::make_pair(CtorInitializers, NumInitializers);
6541}
6542
6543NestedNameSpecifier *
6544ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6545 const RecordData &Record, unsigned &Idx) {
6546 unsigned N = Record[Idx++];
6547 NestedNameSpecifier *NNS = 0, *Prev = 0;
6548 for (unsigned I = 0; I != N; ++I) {
6549 NestedNameSpecifier::SpecifierKind Kind
6550 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6551 switch (Kind) {
6552 case NestedNameSpecifier::Identifier: {
6553 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6554 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6555 break;
6556 }
6557
6558 case NestedNameSpecifier::Namespace: {
6559 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6560 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6561 break;
6562 }
6563
6564 case NestedNameSpecifier::NamespaceAlias: {
6565 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6566 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6567 break;
6568 }
6569
6570 case NestedNameSpecifier::TypeSpec:
6571 case NestedNameSpecifier::TypeSpecWithTemplate: {
6572 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6573 if (!T)
6574 return 0;
6575
6576 bool Template = Record[Idx++];
6577 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6578 break;
6579 }
6580
6581 case NestedNameSpecifier::Global: {
6582 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6583 // No associated value, and there can't be a prefix.
6584 break;
6585 }
6586 }
6587 Prev = NNS;
6588 }
6589 return NNS;
6590}
6591
6592NestedNameSpecifierLoc
6593ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6594 unsigned &Idx) {
6595 unsigned N = Record[Idx++];
6596 NestedNameSpecifierLocBuilder Builder;
6597 for (unsigned I = 0; I != N; ++I) {
6598 NestedNameSpecifier::SpecifierKind Kind
6599 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6600 switch (Kind) {
6601 case NestedNameSpecifier::Identifier: {
6602 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6603 SourceRange Range = ReadSourceRange(F, Record, Idx);
6604 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
6605 break;
6606 }
6607
6608 case NestedNameSpecifier::Namespace: {
6609 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6610 SourceRange Range = ReadSourceRange(F, Record, Idx);
6611 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
6612 break;
6613 }
6614
6615 case NestedNameSpecifier::NamespaceAlias: {
6616 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6617 SourceRange Range = ReadSourceRange(F, Record, Idx);
6618 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
6619 break;
6620 }
6621
6622 case NestedNameSpecifier::TypeSpec:
6623 case NestedNameSpecifier::TypeSpecWithTemplate: {
6624 bool Template = Record[Idx++];
6625 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
6626 if (!T)
6627 return NestedNameSpecifierLoc();
6628 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6629
6630 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
6631 Builder.Extend(Context,
6632 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
6633 T->getTypeLoc(), ColonColonLoc);
6634 break;
6635 }
6636
6637 case NestedNameSpecifier::Global: {
6638 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
6639 Builder.MakeGlobal(Context, ColonColonLoc);
6640 break;
6641 }
6642 }
6643 }
6644
6645 return Builder.getWithLocInContext(Context);
6646}
6647
6648SourceRange
6649ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
6650 unsigned &Idx) {
6651 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
6652 SourceLocation end = ReadSourceLocation(F, Record, Idx);
6653 return SourceRange(beg, end);
6654}
6655
6656/// \brief Read an integral value
6657llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
6658 unsigned BitWidth = Record[Idx++];
6659 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
6660 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
6661 Idx += NumWords;
6662 return Result;
6663}
6664
6665/// \brief Read a signed integral value
6666llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
6667 bool isUnsigned = Record[Idx++];
6668 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
6669}
6670
6671/// \brief Read a floating-point value
6672llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
6673 return llvm::APFloat(ReadAPInt(Record, Idx));
6674}
6675
6676// \brief Read a string
6677std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
6678 unsigned Len = Record[Idx++];
6679 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
6680 Idx += Len;
6681 return Result;
6682}
6683
6684VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
6685 unsigned &Idx) {
6686 unsigned Major = Record[Idx++];
6687 unsigned Minor = Record[Idx++];
6688 unsigned Subminor = Record[Idx++];
6689 if (Minor == 0)
6690 return VersionTuple(Major);
6691 if (Subminor == 0)
6692 return VersionTuple(Major, Minor - 1);
6693 return VersionTuple(Major, Minor - 1, Subminor - 1);
6694}
6695
6696CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
6697 const RecordData &Record,
6698 unsigned &Idx) {
6699 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
6700 return CXXTemporary::Create(Context, Decl);
6701}
6702
6703DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
6704 return Diag(SourceLocation(), DiagID);
6705}
6706
6707DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
6708 return Diags.Report(Loc, DiagID);
6709}
6710
6711/// \brief Retrieve the identifier table associated with the
6712/// preprocessor.
6713IdentifierTable &ASTReader::getIdentifierTable() {
6714 return PP.getIdentifierTable();
6715}
6716
6717/// \brief Record that the given ID maps to the given switch-case
6718/// statement.
6719void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
6720 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
6721 "Already have a SwitchCase with this ID");
6722 (*CurrSwitchCaseStmts)[ID] = SC;
6723}
6724
6725/// \brief Retrieve the switch-case statement with the given ID.
6726SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
6727 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
6728 return (*CurrSwitchCaseStmts)[ID];
6729}
6730
6731void ASTReader::ClearSwitchCaseIDs() {
6732 CurrSwitchCaseStmts->clear();
6733}
6734
6735void ASTReader::ReadComments() {
6736 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006737 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006738 serialization::ModuleFile *> >::iterator
6739 I = CommentsCursors.begin(),
6740 E = CommentsCursors.end();
6741 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006742 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006743 serialization::ModuleFile &F = *I->second;
6744 SavedStreamPosition SavedPosition(Cursor);
6745
6746 RecordData Record;
6747 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006748 llvm::BitstreamEntry Entry =
6749 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
6750
6751 switch (Entry.Kind) {
6752 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
6753 case llvm::BitstreamEntry::Error:
6754 Error("malformed block record in AST file");
6755 return;
6756 case llvm::BitstreamEntry::EndBlock:
6757 goto NextCursor;
6758 case llvm::BitstreamEntry::Record:
6759 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006760 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006761 }
6762
6763 // Read a record.
6764 Record.clear();
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006765 switch ((CommentRecordTypes)Cursor.ReadRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006766 case COMMENTS_RAW_COMMENT: {
6767 unsigned Idx = 0;
6768 SourceRange SR = ReadSourceRange(F, Record, Idx);
6769 RawComment::CommentKind Kind =
6770 (RawComment::CommentKind) Record[Idx++];
6771 bool IsTrailingComment = Record[Idx++];
6772 bool IsAlmostTrailingComment = Record[Idx++];
6773 Comments.push_back(new (Context) RawComment(SR, Kind,
6774 IsTrailingComment,
6775 IsAlmostTrailingComment));
6776 break;
6777 }
6778 }
6779 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00006780 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006781 }
6782 Context.Comments.addCommentsToFront(Comments);
6783}
6784
6785void ASTReader::finishPendingActions() {
6786 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
6787 !PendingMacroIDs.empty()) {
6788 // If any identifiers with corresponding top-level declarations have
6789 // been loaded, load those declarations now.
6790 while (!PendingIdentifierInfos.empty()) {
6791 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
6792 PendingIdentifierInfos.front().DeclIDs, true);
6793 PendingIdentifierInfos.pop_front();
6794 }
6795
6796 // Load pending declaration chains.
6797 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
6798 loadPendingDeclChain(PendingDeclChains[I]);
6799 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
6800 }
6801 PendingDeclChains.clear();
6802
6803 // Load any pending macro definitions.
6804 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00006805 // FIXME: std::move here
6806 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
6807 MacroInfo *Hint = 0;
6808 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
6809 ++IDIdx) {
6810 Hint = getMacro(GlobalIDs[IDIdx], Hint);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006811 }
6812 }
6813 PendingMacroIDs.clear();
6814 }
6815
6816 // If we deserialized any C++ or Objective-C class definitions, any
6817 // Objective-C protocol definitions, or any redeclarable templates, make sure
6818 // that all redeclarations point to the definitions. Note that this can only
6819 // happen now, after the redeclaration chains have been fully wired.
6820 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
6821 DEnd = PendingDefinitions.end();
6822 D != DEnd; ++D) {
6823 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
6824 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
6825 // Make sure that the TagType points at the definition.
6826 const_cast<TagType*>(TagT)->decl = TD;
6827 }
6828
6829 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
6830 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
6831 REnd = RD->redecls_end();
6832 R != REnd; ++R)
6833 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
6834
6835 }
6836
6837 continue;
6838 }
6839
6840 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
6841 // Make sure that the ObjCInterfaceType points at the definition.
6842 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
6843 ->Decl = ID;
6844
6845 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
6846 REnd = ID->redecls_end();
6847 R != REnd; ++R)
6848 R->Data = ID->Data;
6849
6850 continue;
6851 }
6852
6853 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
6854 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
6855 REnd = PD->redecls_end();
6856 R != REnd; ++R)
6857 R->Data = PD->Data;
6858
6859 continue;
6860 }
6861
6862 RedeclarableTemplateDecl *RTD
6863 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
6864 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
6865 REnd = RTD->redecls_end();
6866 R != REnd; ++R)
6867 R->Common = RTD->Common;
6868 }
6869 PendingDefinitions.clear();
6870
6871 // Load the bodies of any functions or methods we've encountered. We do
6872 // this now (delayed) so that we can be sure that the declaration chains
6873 // have been fully wired up.
6874 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
6875 PBEnd = PendingBodies.end();
6876 PB != PBEnd; ++PB) {
6877 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
6878 // FIXME: Check for =delete/=default?
6879 // FIXME: Complain about ODR violations here?
6880 if (!getContext().getLangOpts().Modules || !FD->hasBody())
6881 FD->setLazyBody(PB->second);
6882 continue;
6883 }
6884
6885 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
6886 if (!getContext().getLangOpts().Modules || !MD->hasBody())
6887 MD->setLazyBody(PB->second);
6888 }
6889 PendingBodies.clear();
6890}
6891
6892void ASTReader::FinishedDeserializing() {
6893 assert(NumCurrentElementsDeserializing &&
6894 "FinishedDeserializing not paired with StartedDeserializing");
6895 if (NumCurrentElementsDeserializing == 1) {
6896 // We decrease NumCurrentElementsDeserializing only after pending actions
6897 // are finished, to avoid recursively re-calling finishPendingActions().
6898 finishPendingActions();
6899 }
6900 --NumCurrentElementsDeserializing;
6901
6902 if (NumCurrentElementsDeserializing == 0 &&
6903 Consumer && !PassingDeclsToConsumer) {
6904 // Guard variable to avoid recursively redoing the process of passing
6905 // decls to consumer.
6906 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6907 true);
6908
6909 while (!InterestingDecls.empty()) {
6910 // We are not in recursive loading, so it's safe to pass the "interesting"
6911 // decls to the consumer.
6912 Decl *D = InterestingDecls.front();
6913 InterestingDecls.pop_front();
6914 PassInterestingDeclToConsumer(D);
6915 }
6916 }
6917}
6918
6919ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
6920 StringRef isysroot, bool DisableValidation,
6921 bool AllowASTWithCompilerErrors)
6922 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
6923 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
6924 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
6925 Consumer(0), ModuleMgr(PP.getFileManager()),
6926 isysroot(isysroot), DisableValidation(DisableValidation),
6927 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
6928 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
6929 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
6930 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
6931 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
6932 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
6933 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
6934 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
6935 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
6936 PassingDeclsToConsumer(false),
6937 NumCXXBaseSpecifiersLoaded(0)
6938{
6939 SourceMgr.setExternalSLocEntrySource(this);
6940}
6941
6942ASTReader::~ASTReader() {
6943 for (DeclContextVisibleUpdatesPending::iterator
6944 I = PendingVisibleUpdates.begin(),
6945 E = PendingVisibleUpdates.end();
6946 I != E; ++I) {
6947 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
6948 F = I->second.end();
6949 J != F; ++J)
6950 delete J->first;
6951 }
6952}