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