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