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