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