blob: a766bd2af4b222e7201e0e148807d01bb0f98cce [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"
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Bitcode/BitstreamReader.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Path.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/system_error.h"
53#include <algorithm>
Chris Lattnere4e4a882013-01-20 00:57:52 +000054#include <cstdio>
Guy Benyei7f92f2d2012-12-18 14:30:41 +000055#include <iterator>
56
57using namespace clang;
58using namespace clang::serialization;
59using namespace clang::serialization::reader;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +000060using llvm::BitstreamCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000061
62//===----------------------------------------------------------------------===//
63// PCH validator implementation
64//===----------------------------------------------------------------------===//
65
66ASTReaderListener::~ASTReaderListener() {}
67
68/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
79 if (Diags) \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
82 return true; \
83 }
84
85#define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
87 if (Diags) \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
89 << Description; \
90 return true; \
91 }
92
93#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
95 if (Diags) \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
97 << Description; \
98 return true; \
99 }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
104
105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106 if (Diags)
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
109 return true;
110 }
111
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000112 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
113 LangOpts.CommentOpts.BlockCommandNames) {
114 if (Diags)
115 Diags->Report(diag::err_pch_langopt_value_mismatch)
116 << "block command names";
117 return true;
118 }
119
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000120 return false;
121}
122
123/// \brief Compare the given set of target options against an existing set of
124/// target options.
125///
126/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
127///
128/// \returns true if the target options mis-match, false otherwise.
129static bool checkTargetOptions(const TargetOptions &TargetOpts,
130 const TargetOptions &ExistingTargetOpts,
131 DiagnosticsEngine *Diags) {
132#define CHECK_TARGET_OPT(Field, Name) \
133 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
134 if (Diags) \
135 Diags->Report(diag::err_pch_targetopt_mismatch) \
136 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
137 return true; \
138 }
139
140 CHECK_TARGET_OPT(Triple, "target");
141 CHECK_TARGET_OPT(CPU, "target CPU");
142 CHECK_TARGET_OPT(ABI, "target ABI");
143 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
144 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
145#undef CHECK_TARGET_OPT
146
147 // Compare feature sets.
148 SmallVector<StringRef, 4> ExistingFeatures(
149 ExistingTargetOpts.FeaturesAsWritten.begin(),
150 ExistingTargetOpts.FeaturesAsWritten.end());
151 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
152 TargetOpts.FeaturesAsWritten.end());
153 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
154 std::sort(ReadFeatures.begin(), ReadFeatures.end());
155
156 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
157 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
158 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
159 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
160 ++ExistingIdx;
161 ++ReadIdx;
162 continue;
163 }
164
165 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
166 if (Diags)
167 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
168 << false << ReadFeatures[ReadIdx];
169 return true;
170 }
171
172 if (Diags)
173 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
174 << true << ExistingFeatures[ExistingIdx];
175 return true;
176 }
177
178 if (ExistingIdx < ExistingN) {
179 if (Diags)
180 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
181 << true << ExistingFeatures[ExistingIdx];
182 return true;
183 }
184
185 if (ReadIdx < ReadN) {
186 if (Diags)
187 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
188 << false << ReadFeatures[ReadIdx];
189 return true;
190 }
191
192 return false;
193}
194
195bool
196PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
197 bool Complain) {
198 const LangOptions &ExistingLangOpts = PP.getLangOpts();
199 return checkLanguageOptions(LangOpts, ExistingLangOpts,
200 Complain? &Reader.Diags : 0);
201}
202
203bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
204 bool Complain) {
205 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
206 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
207 Complain? &Reader.Diags : 0);
208}
209
210namespace {
211 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
212 MacroDefinitionsMap;
213}
214
215/// \brief Collect the macro definitions provided by the given preprocessor
216/// options.
217static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
218 MacroDefinitionsMap &Macros,
219 SmallVectorImpl<StringRef> *MacroNames = 0){
220 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
221 StringRef Macro = PPOpts.Macros[I].first;
222 bool IsUndef = PPOpts.Macros[I].second;
223
224 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
225 StringRef MacroName = MacroPair.first;
226 StringRef MacroBody = MacroPair.second;
227
228 // For an #undef'd macro, we only care about the name.
229 if (IsUndef) {
230 if (MacroNames && !Macros.count(MacroName))
231 MacroNames->push_back(MacroName);
232
233 Macros[MacroName] = std::make_pair("", true);
234 continue;
235 }
236
237 // For a #define'd macro, figure out the actual definition.
238 if (MacroName.size() == Macro.size())
239 MacroBody = "1";
240 else {
241 // Note: GCC drops anything following an end-of-line character.
242 StringRef::size_type End = MacroBody.find_first_of("\n\r");
243 MacroBody = MacroBody.substr(0, End);
244 }
245
246 if (MacroNames && !Macros.count(MacroName))
247 MacroNames->push_back(MacroName);
248 Macros[MacroName] = std::make_pair(MacroBody, false);
249 }
250}
251
252/// \brief Check the preprocessor options deserialized from the control block
253/// against the preprocessor options in an existing preprocessor.
254///
255/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
256static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
257 const PreprocessorOptions &ExistingPPOpts,
258 DiagnosticsEngine *Diags,
259 FileManager &FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000260 std::string &SuggestedPredefines,
261 const LangOptions &LangOpts) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000262 // Check macro definitions.
263 MacroDefinitionsMap ASTFileMacros;
264 collectMacroDefinitions(PPOpts, ASTFileMacros);
265 MacroDefinitionsMap ExistingMacros;
266 SmallVector<StringRef, 4> ExistingMacroNames;
267 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
268
269 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
270 // Dig out the macro definition in the existing preprocessor options.
271 StringRef MacroName = ExistingMacroNames[I];
272 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
273
274 // Check whether we know anything about this macro name or not.
275 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
276 = ASTFileMacros.find(MacroName);
277 if (Known == ASTFileMacros.end()) {
278 // FIXME: Check whether this identifier was referenced anywhere in the
279 // AST file. If so, we should reject the AST file. Unfortunately, this
280 // information isn't in the control block. What shall we do about it?
281
282 if (Existing.second) {
283 SuggestedPredefines += "#undef ";
284 SuggestedPredefines += MacroName.str();
285 SuggestedPredefines += '\n';
286 } else {
287 SuggestedPredefines += "#define ";
288 SuggestedPredefines += MacroName.str();
289 SuggestedPredefines += ' ';
290 SuggestedPredefines += Existing.first.str();
291 SuggestedPredefines += '\n';
292 }
293 continue;
294 }
295
296 // If the macro was defined in one but undef'd in the other, we have a
297 // conflict.
298 if (Existing.second != Known->second.second) {
299 if (Diags) {
300 Diags->Report(diag::err_pch_macro_def_undef)
301 << MacroName << Known->second.second;
302 }
303 return true;
304 }
305
306 // If the macro was #undef'd in both, or if the macro bodies are identical,
307 // it's fine.
308 if (Existing.second || Existing.first == Known->second.first)
309 continue;
310
311 // The macro bodies differ; complain.
312 if (Diags) {
313 Diags->Report(diag::err_pch_macro_def_conflict)
314 << MacroName << Known->second.first << Existing.first;
315 }
316 return true;
317 }
318
319 // Check whether we're using predefines.
320 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
321 if (Diags) {
322 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
323 }
324 return true;
325 }
326
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000327 // Detailed record is important since it is used for the module cache hash.
328 if (LangOpts.Modules &&
329 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
330 if (Diags) {
331 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
332 }
333 return true;
334 }
335
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000336 // Compute the #include and #include_macros lines we need.
337 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
338 StringRef File = ExistingPPOpts.Includes[I];
339 if (File == ExistingPPOpts.ImplicitPCHInclude)
340 continue;
341
342 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
343 != PPOpts.Includes.end())
344 continue;
345
346 SuggestedPredefines += "#include \"";
347 SuggestedPredefines +=
348 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
349 SuggestedPredefines += "\"\n";
350 }
351
352 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
353 StringRef File = ExistingPPOpts.MacroIncludes[I];
354 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
355 File)
356 != PPOpts.MacroIncludes.end())
357 continue;
358
359 SuggestedPredefines += "#__include_macros \"";
360 SuggestedPredefines +=
361 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
362 SuggestedPredefines += "\"\n##\n";
363 }
364
365 return false;
366}
367
368bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
369 bool Complain,
370 std::string &SuggestedPredefines) {
371 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
372
373 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
374 Complain? &Reader.Diags : 0,
375 PP.getFileManager(),
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +0000376 SuggestedPredefines,
377 PP.getLangOpts());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000378}
379
380void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
381 unsigned ID) {
382 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
383 ++NumHeaderInfos;
384}
385
386void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
387 PP.setCounterValue(Value);
388}
389
390//===----------------------------------------------------------------------===//
391// AST reader implementation
392//===----------------------------------------------------------------------===//
393
394void
395ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
396 DeserializationListener = Listener;
397}
398
399
400
401unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
402 return serialization::ComputeHash(Sel);
403}
404
405
406std::pair<unsigned, unsigned>
407ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
408 using namespace clang::io;
409 unsigned KeyLen = ReadUnalignedLE16(d);
410 unsigned DataLen = ReadUnalignedLE16(d);
411 return std::make_pair(KeyLen, DataLen);
412}
413
414ASTSelectorLookupTrait::internal_key_type
415ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
416 using namespace clang::io;
417 SelectorTable &SelTable = Reader.getContext().Selectors;
418 unsigned N = ReadUnalignedLE16(d);
419 IdentifierInfo *FirstII
Douglas Gregor8222b892013-01-21 16:52:34 +0000420 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000421 if (N == 0)
422 return SelTable.getNullarySelector(FirstII);
423 else if (N == 1)
424 return SelTable.getUnarySelector(FirstII);
425
426 SmallVector<IdentifierInfo *, 16> Args;
427 Args.push_back(FirstII);
428 for (unsigned I = 1; I != N; ++I)
Douglas Gregor8222b892013-01-21 16:52:34 +0000429 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000430
431 return SelTable.getSelector(N, Args.data());
432}
433
434ASTSelectorLookupTrait::data_type
435ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
436 unsigned DataLen) {
437 using namespace clang::io;
438
439 data_type Result;
440
441 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +0000442 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
443 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
444 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
445 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
446 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
447 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000448
449 // Load instance methods
450 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
451 if (ObjCMethodDecl *Method
452 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
453 Result.Instance.push_back(Method);
454 }
455
456 // Load factory methods
457 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
458 if (ObjCMethodDecl *Method
459 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
460 Result.Factory.push_back(Method);
461 }
462
463 return Result;
464}
465
Douglas Gregor479633c2013-01-23 18:53:14 +0000466unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
467 return llvm::HashString(a);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000468}
469
470std::pair<unsigned, unsigned>
Douglas Gregor479633c2013-01-23 18:53:14 +0000471ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000472 using namespace clang::io;
473 unsigned DataLen = ReadUnalignedLE16(d);
474 unsigned KeyLen = ReadUnalignedLE16(d);
475 return std::make_pair(KeyLen, DataLen);
476}
477
Douglas Gregor479633c2013-01-23 18:53:14 +0000478ASTIdentifierLookupTraitBase::internal_key_type
479ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000480 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregor479633c2013-01-23 18:53:14 +0000481 return StringRef((const char*) d, n-1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000482}
483
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000484/// \brief Whether the given identifier is "interesting".
485static bool isInterestingIdentifier(IdentifierInfo &II) {
486 return II.isPoisoned() ||
487 II.isExtensionToken() ||
488 II.getObjCOrBuiltinID() ||
489 II.hasRevertedTokenIDToIdentifier() ||
490 II.hadMacroDefinition() ||
491 II.getFETokenInfo<void>();
492}
493
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000494IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
495 const unsigned char* d,
496 unsigned DataLen) {
497 using namespace clang::io;
498 unsigned RawID = ReadUnalignedLE32(d);
499 bool IsInteresting = RawID & 0x01;
500
501 // Wipe out the "is interesting" bit.
502 RawID = RawID >> 1;
503
504 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
505 if (!IsInteresting) {
506 // For uninteresting identifiers, just build the IdentifierInfo
507 // and associate it with the persistent ID.
508 IdentifierInfo *II = KnownII;
509 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000510 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000511 KnownII = II;
512 }
513 Reader.SetIdentifierInfo(ID, II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000514 if (!II->isFromAST()) {
515 bool WasInteresting = isInterestingIdentifier(*II);
516 II->setIsFromAST();
517 if (WasInteresting)
518 II->setChangedSinceDeserialization();
519 }
520 Reader.markIdentifierUpToDate(II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000521 return II;
522 }
523
524 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
525 unsigned Bits = ReadUnalignedLE16(d);
526 bool CPlusPlusOperatorKeyword = Bits & 0x01;
527 Bits >>= 1;
528 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
529 Bits >>= 1;
530 bool Poisoned = Bits & 0x01;
531 Bits >>= 1;
532 bool ExtensionToken = Bits & 0x01;
533 Bits >>= 1;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000534 bool hasSubmoduleMacros = Bits & 0x01;
535 Bits >>= 1;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000536 bool hadMacroDefinition = Bits & 0x01;
537 Bits >>= 1;
538
539 assert(Bits == 0 && "Extra bits in the identifier?");
540 DataLen -= 8;
541
542 // Build the IdentifierInfo itself and link the identifier ID with
543 // the new IdentifierInfo.
544 IdentifierInfo *II = KnownII;
545 if (!II) {
Douglas Gregor479633c2013-01-23 18:53:14 +0000546 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000547 KnownII = II;
548 }
549 Reader.markIdentifierUpToDate(II);
Douglas Gregorf4e955b2013-02-11 18:16:18 +0000550 if (!II->isFromAST()) {
551 bool WasInteresting = isInterestingIdentifier(*II);
552 II->setIsFromAST();
553 if (WasInteresting)
554 II->setChangedSinceDeserialization();
555 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000556
557 // Set or check the various bits in the IdentifierInfo structure.
558 // Token IDs are read-only.
Argyrios Kyrtzidis1ebefc72013-02-27 01:13:51 +0000559 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000560 II->RevertTokenIDToIdentifier();
561 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
562 assert(II->isExtensionToken() == ExtensionToken &&
563 "Incorrect extension token flag");
564 (void)ExtensionToken;
565 if (Poisoned)
566 II->setIsPoisoned(true);
567 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
568 "Incorrect C++ operator keyword flag");
569 (void)CPlusPlusOperatorKeyword;
570
571 // If this identifier is a macro, deserialize the macro
572 // definition.
573 if (hadMacroDefinition) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000574 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
575 DataLen -= 4;
576 SmallVector<uint32_t, 8> LocalMacroIDs;
577 if (hasSubmoduleMacros) {
578 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
579 DataLen -= 4;
580 LocalMacroIDs.push_back(LocalMacroID);
581 }
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +0000582 DataLen -= 4;
583 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +0000584
585 if (F.Kind == MK_Module) {
586 for (SmallVectorImpl<uint32_t>::iterator
587 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; ++I) {
588 MacroID MacID = Reader.getGlobalMacroID(F, *I);
589 Reader.addPendingMacroFromModule(II, &F, MacID, F.DirectImportLoc);
590 }
591 } else {
592 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
593 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000594 }
595
596 Reader.SetIdentifierInfo(ID, II);
597
598 // Read all of the declarations visible at global scope with this
599 // name.
600 if (DataLen > 0) {
601 SmallVector<uint32_t, 4> DeclIDs;
602 for (; DataLen > 0; DataLen -= 4)
603 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
604 Reader.SetGloballyVisibleDecls(II, DeclIDs);
605 }
606
607 return II;
608}
609
610unsigned
611ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
612 llvm::FoldingSetNodeID ID;
613 ID.AddInteger(Key.Kind);
614
615 switch (Key.Kind) {
616 case DeclarationName::Identifier:
617 case DeclarationName::CXXLiteralOperatorName:
618 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
619 break;
620 case DeclarationName::ObjCZeroArgSelector:
621 case DeclarationName::ObjCOneArgSelector:
622 case DeclarationName::ObjCMultiArgSelector:
623 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
624 break;
625 case DeclarationName::CXXOperatorName:
626 ID.AddInteger((OverloadedOperatorKind)Key.Data);
627 break;
628 case DeclarationName::CXXConstructorName:
629 case DeclarationName::CXXDestructorName:
630 case DeclarationName::CXXConversionFunctionName:
631 case DeclarationName::CXXUsingDirective:
632 break;
633 }
634
635 return ID.ComputeHash();
636}
637
638ASTDeclContextNameLookupTrait::internal_key_type
639ASTDeclContextNameLookupTrait::GetInternalKey(
640 const external_key_type& Name) const {
641 DeclNameKey Key;
642 Key.Kind = Name.getNameKind();
643 switch (Name.getNameKind()) {
644 case DeclarationName::Identifier:
645 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
646 break;
647 case DeclarationName::ObjCZeroArgSelector:
648 case DeclarationName::ObjCOneArgSelector:
649 case DeclarationName::ObjCMultiArgSelector:
650 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
651 break;
652 case DeclarationName::CXXOperatorName:
653 Key.Data = Name.getCXXOverloadedOperator();
654 break;
655 case DeclarationName::CXXLiteralOperatorName:
656 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
657 break;
658 case DeclarationName::CXXConstructorName:
659 case DeclarationName::CXXDestructorName:
660 case DeclarationName::CXXConversionFunctionName:
661 case DeclarationName::CXXUsingDirective:
662 Key.Data = 0;
663 break;
664 }
665
666 return Key;
667}
668
669std::pair<unsigned, unsigned>
670ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
671 using namespace clang::io;
672 unsigned KeyLen = ReadUnalignedLE16(d);
673 unsigned DataLen = ReadUnalignedLE16(d);
674 return std::make_pair(KeyLen, DataLen);
675}
676
677ASTDeclContextNameLookupTrait::internal_key_type
678ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
679 using namespace clang::io;
680
681 DeclNameKey Key;
682 Key.Kind = (DeclarationName::NameKind)*d++;
683 switch (Key.Kind) {
684 case DeclarationName::Identifier:
685 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
686 break;
687 case DeclarationName::ObjCZeroArgSelector:
688 case DeclarationName::ObjCOneArgSelector:
689 case DeclarationName::ObjCMultiArgSelector:
690 Key.Data =
691 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
692 .getAsOpaquePtr();
693 break;
694 case DeclarationName::CXXOperatorName:
695 Key.Data = *d++; // OverloadedOperatorKind
696 break;
697 case DeclarationName::CXXLiteralOperatorName:
698 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
699 break;
700 case DeclarationName::CXXConstructorName:
701 case DeclarationName::CXXDestructorName:
702 case DeclarationName::CXXConversionFunctionName:
703 case DeclarationName::CXXUsingDirective:
704 Key.Data = 0;
705 break;
706 }
707
708 return Key;
709}
710
711ASTDeclContextNameLookupTrait::data_type
712ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
713 const unsigned char* d,
714 unsigned DataLen) {
715 using namespace clang::io;
716 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidise8b61cf2013-01-11 22:29:49 +0000717 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
718 const_cast<unsigned char *>(d));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719 return std::make_pair(Start, Start + NumDecls);
720}
721
722bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000723 BitstreamCursor &Cursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000724 const std::pair<uint64_t, uint64_t> &Offsets,
725 DeclContextInfo &Info) {
726 SavedStreamPosition SavedPosition(Cursor);
727 // First the lexical decls.
728 if (Offsets.first != 0) {
729 Cursor.JumpToBit(Offsets.first);
730
731 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000732 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000733 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000734 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000735 if (RecCode != DECL_CONTEXT_LEXICAL) {
736 Error("Expected lexical block");
737 return true;
738 }
739
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000740 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
741 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000742 }
743
744 // Now the lookup table.
745 if (Offsets.second != 0) {
746 Cursor.JumpToBit(Offsets.second);
747
748 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000749 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000750 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000751 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000752 if (RecCode != DECL_CONTEXT_VISIBLE) {
753 Error("Expected visible lookup table block");
754 return true;
755 }
756 Info.NameLookupTableData
757 = ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000758 (const unsigned char *)Blob.data() + Record[0],
759 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000760 ASTDeclContextNameLookupTrait(*this, M));
761 }
762
763 return false;
764}
765
766void ASTReader::Error(StringRef Msg) {
767 Error(diag::err_fe_pch_malformed, Msg);
768}
769
770void ASTReader::Error(unsigned DiagID,
771 StringRef Arg1, StringRef Arg2) {
772 if (Diags.isDiagnosticInFlight())
773 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
774 else
775 Diag(DiagID) << Arg1 << Arg2;
776}
777
778//===----------------------------------------------------------------------===//
779// Source Manager Deserialization
780//===----------------------------------------------------------------------===//
781
782/// \brief Read the line table in the source manager block.
783/// \returns true if there was an error.
784bool ASTReader::ParseLineTable(ModuleFile &F,
785 SmallVectorImpl<uint64_t> &Record) {
786 unsigned Idx = 0;
787 LineTableInfo &LineTable = SourceMgr.getLineTable();
788
789 // Parse the file names
790 std::map<int, int> FileIDs;
791 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
792 // Extract the file name
793 unsigned FilenameLen = Record[Idx++];
794 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
795 Idx += FilenameLen;
796 MaybeAddSystemRootToFilename(F, Filename);
797 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
798 }
799
800 // Parse the line entries
801 std::vector<LineEntry> Entries;
802 while (Idx < Record.size()) {
803 int FID = Record[Idx++];
804 assert(FID >= 0 && "Serialized line entries for non-local file.");
805 // Remap FileID from 1-based old view.
806 FID += F.SLocEntryBaseID - 1;
807
808 // Extract the line entries
809 unsigned NumEntries = Record[Idx++];
810 assert(NumEntries && "Numentries is 00000");
811 Entries.clear();
812 Entries.reserve(NumEntries);
813 for (unsigned I = 0; I != NumEntries; ++I) {
814 unsigned FileOffset = Record[Idx++];
815 unsigned LineNo = Record[Idx++];
816 int FilenameID = FileIDs[Record[Idx++]];
817 SrcMgr::CharacteristicKind FileKind
818 = (SrcMgr::CharacteristicKind)Record[Idx++];
819 unsigned IncludeOffset = Record[Idx++];
820 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
821 FileKind, IncludeOffset));
822 }
823 LineTable.AddEntry(FileID::get(FID), Entries);
824 }
825
826 return false;
827}
828
829/// \brief Read a source manager block
830bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
831 using namespace SrcMgr;
832
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000833 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000834
835 // Set the source-location entry cursor to the current position in
836 // the stream. This cursor will be used to read the contents of the
837 // source manager block initially, and then lazily read
838 // source-location entries as needed.
839 SLocEntryCursor = F.Stream;
840
841 // The stream itself is going to skip over the source manager block.
842 if (F.Stream.SkipBlock()) {
843 Error("malformed block record in AST file");
844 return true;
845 }
846
847 // Enter the source manager block.
848 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
849 Error("malformed source manager block record in AST file");
850 return true;
851 }
852
853 RecordData Record;
854 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +0000855 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
856
857 switch (E.Kind) {
858 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
859 case llvm::BitstreamEntry::Error:
860 Error("malformed block record in AST file");
861 return true;
862 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000863 return false;
Chris Lattner88bde502013-01-19 21:39:22 +0000864 case llvm::BitstreamEntry::Record:
865 // The interesting case.
866 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000867 }
Chris Lattner88bde502013-01-19 21:39:22 +0000868
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000869 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000870 Record.clear();
Chris Lattner125eb3e2013-01-21 18:28:26 +0000871 StringRef Blob;
872 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000873 default: // Default behavior: ignore.
874 break;
875
876 case SM_SLOC_FILE_ENTRY:
877 case SM_SLOC_BUFFER_ENTRY:
878 case SM_SLOC_EXPANSION_ENTRY:
879 // Once we hit one of the source location entries, we're done.
880 return false;
881 }
882 }
883}
884
885/// \brief If a header file is not found at the path that we expect it to be
886/// and the PCH file was moved from its original location, try to resolve the
887/// file by assuming that header+PCH were moved together and the header is in
888/// the same place relative to the PCH.
889static std::string
890resolveFileRelativeToOriginalDir(const std::string &Filename,
891 const std::string &OriginalDir,
892 const std::string &CurrDir) {
893 assert(OriginalDir != CurrDir &&
894 "No point trying to resolve the file if the PCH dir didn't change");
895 using namespace llvm::sys;
896 SmallString<128> filePath(Filename);
897 fs::make_absolute(filePath);
898 assert(path::is_absolute(OriginalDir));
899 SmallString<128> currPCHPath(CurrDir);
900
901 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
902 fileDirE = path::end(path::parent_path(filePath));
903 path::const_iterator origDirI = path::begin(OriginalDir),
904 origDirE = path::end(OriginalDir);
905 // Skip the common path components from filePath and OriginalDir.
906 while (fileDirI != fileDirE && origDirI != origDirE &&
907 *fileDirI == *origDirI) {
908 ++fileDirI;
909 ++origDirI;
910 }
911 for (; origDirI != origDirE; ++origDirI)
912 path::append(currPCHPath, "..");
913 path::append(currPCHPath, fileDirI, fileDirE);
914 path::append(currPCHPath, path::filename(Filename));
915 return currPCHPath.str();
916}
917
918bool ASTReader::ReadSLocEntry(int ID) {
919 if (ID == 0)
920 return false;
921
922 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
923 Error("source location entry ID out-of-range for AST file");
924 return true;
925 }
926
927 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
928 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +0000929 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000930 unsigned BaseOffset = F->SLocEntryBaseOffset;
931
932 ++NumSLocEntriesRead;
Chris Lattner88bde502013-01-19 21:39:22 +0000933 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
934 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000935 Error("incorrectly-formatted source location entry in AST file");
936 return true;
937 }
Chris Lattner88bde502013-01-19 21:39:22 +0000938
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000939 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000940 StringRef Blob;
941 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000942 default:
943 Error("incorrectly-formatted source location entry in AST file");
944 return true;
945
946 case SM_SLOC_FILE_ENTRY: {
947 // We will detect whether a file changed and return 'Failure' for it, but
948 // we will also try to fail gracefully by setting up the SLocEntry.
949 unsigned InputID = Record[4];
950 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000951 const FileEntry *File = IF.getFile();
952 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000953
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +0000954 // Note that we only check if a File was returned. If it was out-of-date
955 // we have complained but we will continue creating a FileID to recover
956 // gracefully.
957 if (!File)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000958 return true;
959
960 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
961 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
962 // This is the module's main file.
963 IncludeLoc = getImportLocation(F);
964 }
965 SrcMgr::CharacteristicKind
966 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
967 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
968 ID, BaseOffset + Record[0]);
969 SrcMgr::FileInfo &FileInfo =
970 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
971 FileInfo.NumCreatedFIDs = Record[5];
972 if (Record[3])
973 FileInfo.setHasLineDirectives();
974
975 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
976 unsigned NumFileDecls = Record[7];
977 if (NumFileDecls) {
978 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
979 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
980 NumFileDecls));
981 }
982
983 const SrcMgr::ContentCache *ContentCache
984 = SourceMgr.getOrCreateContentCache(File,
985 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
986 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
987 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
988 unsigned Code = SLocEntryCursor.ReadCode();
989 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000990 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000991
992 if (RecCode != SM_SLOC_BUFFER_BLOB) {
993 Error("AST record has invalid code");
994 return true;
995 }
996
997 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +0000998 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000999 SourceMgr.overrideFileContents(File, Buffer);
1000 }
1001
1002 break;
1003 }
1004
1005 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001006 const char *Name = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001007 unsigned Offset = Record[0];
1008 SrcMgr::CharacteristicKind
1009 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1010 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1011 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1012 IncludeLoc = getImportLocation(F);
1013 }
1014 unsigned Code = SLocEntryCursor.ReadCode();
1015 Record.clear();
1016 unsigned RecCode
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001017 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001018
1019 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1020 Error("AST record has invalid code");
1021 return true;
1022 }
1023
1024 llvm::MemoryBuffer *Buffer
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001025 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001026 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1027 BaseOffset + Offset, IncludeLoc);
1028 break;
1029 }
1030
1031 case SM_SLOC_EXPANSION_ENTRY: {
1032 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1033 SourceMgr.createExpansionLoc(SpellingLoc,
1034 ReadSourceLocation(*F, Record[2]),
1035 ReadSourceLocation(*F, Record[3]),
1036 Record[4],
1037 ID,
1038 BaseOffset + Record[0]);
1039 break;
1040 }
1041 }
1042
1043 return false;
1044}
1045
1046std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1047 if (ID == 0)
1048 return std::make_pair(SourceLocation(), "");
1049
1050 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1051 Error("source location entry ID out-of-range for AST file");
1052 return std::make_pair(SourceLocation(), "");
1053 }
1054
1055 // Find which module file this entry lands in.
1056 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1057 if (M->Kind != MK_Module)
1058 return std::make_pair(SourceLocation(), "");
1059
1060 // FIXME: Can we map this down to a particular submodule? That would be
1061 // ideal.
1062 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1063}
1064
1065/// \brief Find the location where the module F is imported.
1066SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1067 if (F->ImportLoc.isValid())
1068 return F->ImportLoc;
1069
1070 // Otherwise we have a PCH. It's considered to be "imported" at the first
1071 // location of its includer.
1072 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1073 // Main file is the importer. We assume that it is the first entry in the
1074 // entry table. We can't ask the manager, because at the time of PCH loading
1075 // the main file entry doesn't exist yet.
1076 // The very first entry is the invalid instantiation loc, which takes up
1077 // offsets 0 and 1.
1078 return SourceLocation::getFromRawEncoding(2U);
1079 }
1080 //return F->Loaders[0]->FirstLoc;
1081 return F->ImportedBy[0]->FirstLoc;
1082}
1083
1084/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1085/// specified cursor. Read the abbreviations that are at the top of the block
1086/// and then leave the cursor pointing into the block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001087bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001088 if (Cursor.EnterSubBlock(BlockID)) {
1089 Error("malformed block record in AST file");
1090 return Failure;
1091 }
1092
1093 while (true) {
1094 uint64_t Offset = Cursor.GetCurrentBitNo();
1095 unsigned Code = Cursor.ReadCode();
1096
1097 // We expect all abbrevs to be at the start of the block.
1098 if (Code != llvm::bitc::DEFINE_ABBREV) {
1099 Cursor.JumpToBit(Offset);
1100 return false;
1101 }
1102 Cursor.ReadAbbrevRecord();
1103 }
1104}
1105
John McCallaeeacf72013-05-03 00:10:13 +00001106Token ASTReader::ReadToken(ModuleFile &F, const RecordData &Record,
1107 unsigned &Idx) {
1108 Token Tok;
1109 Tok.startToken();
1110 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1111 Tok.setLength(Record[Idx++]);
1112 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1113 Tok.setIdentifierInfo(II);
1114 Tok.setKind((tok::TokenKind)Record[Idx++]);
1115 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1116 return Tok;
1117}
1118
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001119MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001120 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001121
1122 // Keep track of where we are in the stream, then jump back there
1123 // after reading this macro.
1124 SavedStreamPosition SavedPosition(Stream);
1125
1126 Stream.JumpToBit(Offset);
1127 RecordData Record;
1128 SmallVector<IdentifierInfo*, 16> MacroArgs;
1129 MacroInfo *Macro = 0;
1130
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001131 while (true) {
Chris Lattner99a5af02013-01-20 00:00:22 +00001132 // Advance to the next record, but if we get to the end of the block, don't
1133 // pop it (removing all the abbreviations from the cursor) since we want to
1134 // be able to reseek within the block and read entries.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001135 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattner99a5af02013-01-20 00:00:22 +00001136 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1137
1138 switch (Entry.Kind) {
1139 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1140 case llvm::BitstreamEntry::Error:
1141 Error("malformed block record in AST file");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001142 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001143 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001144 return Macro;
Chris Lattner99a5af02013-01-20 00:00:22 +00001145 case llvm::BitstreamEntry::Record:
1146 // The interesting case.
1147 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001148 }
1149
1150 // Read a record.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001151 Record.clear();
1152 PreprocessorRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001153 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001154 switch (RecType) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001155 case PP_MACRO_DIRECTIVE_HISTORY:
1156 return Macro;
1157
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001158 case PP_MACRO_OBJECT_LIKE:
1159 case PP_MACRO_FUNCTION_LIKE: {
1160 // If we already have a macro, that means that we've hit the end
1161 // of the definition of the macro we were looking for. We're
1162 // done.
1163 if (Macro)
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001164 return Macro;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001165
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001166 unsigned NextIndex = 1; // Skip identifier ID.
1167 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001168 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001169 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis8169b672013-01-07 19:16:23 +00001170 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001172
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001173 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1174 // Decode function-like macro info.
1175 bool isC99VarArgs = Record[NextIndex++];
1176 bool isGNUVarArgs = Record[NextIndex++];
1177 bool hasCommaPasting = Record[NextIndex++];
1178 MacroArgs.clear();
1179 unsigned NumArgs = Record[NextIndex++];
1180 for (unsigned i = 0; i != NumArgs; ++i)
1181 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1182
1183 // Install function-like macro info.
1184 MI->setIsFunctionLike();
1185 if (isC99VarArgs) MI->setIsC99Varargs();
1186 if (isGNUVarArgs) MI->setIsGNUVarargs();
1187 if (hasCommaPasting) MI->setHasCommaPasting();
1188 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1189 PP.getPreprocessorAllocator());
1190 }
1191
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001192 // Remember that we saw this macro last so that we add the tokens that
1193 // form its body to it.
1194 Macro = MI;
1195
1196 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1197 Record[NextIndex]) {
1198 // We have a macro definition. Register the association
1199 PreprocessedEntityID
1200 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1201 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis0b849d32013-02-22 18:35:59 +00001202 PreprocessingRecord::PPEntityID
1203 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1204 MacroDefinition *PPDef =
1205 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1206 if (PPDef)
1207 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001208 }
1209
1210 ++NumMacrosRead;
1211 break;
1212 }
1213
1214 case PP_TOKEN: {
1215 // If we see a TOKEN before a PP_MACRO_*, then the file is
1216 // erroneous, just pretend we didn't see this.
1217 if (Macro == 0) break;
1218
John McCallaeeacf72013-05-03 00:10:13 +00001219 unsigned Idx = 0;
1220 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001221 Macro->AddTokenToBody(Tok);
1222 break;
1223 }
1224 }
1225 }
1226}
1227
1228PreprocessedEntityID
1229ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1230 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1231 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1232 assert(I != M.PreprocessedEntityRemap.end()
1233 && "Invalid index into preprocessed entity index remap");
1234
1235 return LocalID + I->second;
1236}
1237
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001238unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1239 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001240}
1241
1242HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001243HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1244 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1245 FE->getName() };
1246 return ikey;
1247}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001248
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001249bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1250 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001251 return false;
1252
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001253 if (strcmp(a.Filename, b.Filename) == 0)
1254 return true;
1255
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001256 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001257 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001258 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1259 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis1c1508b2013-03-04 20:33:40 +00001260 return (FEA && FEA == FEB);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001261}
1262
1263std::pair<unsigned, unsigned>
1264HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1265 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1266 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001267 return std::make_pair(KeyLen, DataLen);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001268}
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00001269
1270HeaderFileInfoTrait::internal_key_type
1271HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1272 internal_key_type ikey;
1273 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1274 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1275 ikey.Filename = (const char *)d;
1276 return ikey;
1277}
1278
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001279HeaderFileInfoTrait::data_type
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001280HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001281 unsigned DataLen) {
1282 const unsigned char *End = d + DataLen;
1283 using namespace clang::io;
1284 HeaderFileInfo HFI;
1285 unsigned Flags = *d++;
1286 HFI.isImport = (Flags >> 5) & 0x01;
1287 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1288 HFI.DirInfo = (Flags >> 2) & 0x03;
1289 HFI.Resolved = (Flags >> 1) & 0x01;
1290 HFI.IndexHeaderMapHeader = Flags & 0x01;
1291 HFI.NumIncludes = ReadUnalignedLE16(d);
1292 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1293 ReadUnalignedLE32(d));
1294 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1295 // The framework offset is 1 greater than the actual offset,
1296 // since 0 is used as an indicator for "no framework name".
1297 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1298 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1299 }
1300
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00001301 if (d != End) {
1302 uint32_t LocalSMID = ReadUnalignedLE32(d);
1303 if (LocalSMID) {
1304 // This header is part of a module. Associate it with the module to enable
1305 // implicit module import.
1306 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1307 Module *Mod = Reader.getSubmodule(GlobalSMID);
1308 HFI.isModuleHeader = true;
1309 FileManager &FileMgr = Reader.getFileManager();
1310 ModuleMap &ModMap =
1311 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1312 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), /*Excluded=*/false);
1313 }
1314 }
1315
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001316 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1317 (void)End;
1318
1319 // This HeaderFileInfo was externally loaded.
1320 HFI.External = true;
1321 return HFI;
1322}
1323
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001324void ASTReader::addPendingMacroFromModule(IdentifierInfo *II,
1325 ModuleFile *M,
1326 GlobalMacroID GMacID,
1327 SourceLocation ImportLoc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001328 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001329 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, ImportLoc));
1330}
1331
1332void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1333 ModuleFile *M,
1334 uint64_t MacroDirectivesOffset) {
1335 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1336 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001337}
1338
1339void ASTReader::ReadDefinedMacros() {
1340 // Note that we are loading defined macros.
1341 Deserializing Macros(this);
1342
1343 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1344 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001345 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001346
1347 // If there was no preprocessor block, skip this file.
1348 if (!MacroCursor.getBitStreamReader())
1349 continue;
1350
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001351 BitstreamCursor Cursor = MacroCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001352 Cursor.JumpToBit((*I)->MacroStartOffset);
1353
1354 RecordData Record;
1355 while (true) {
Chris Lattner88bde502013-01-19 21:39:22 +00001356 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1357
1358 switch (E.Kind) {
1359 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1360 case llvm::BitstreamEntry::Error:
1361 Error("malformed block record in AST file");
1362 return;
1363 case llvm::BitstreamEntry::EndBlock:
1364 goto NextCursor;
1365
1366 case llvm::BitstreamEntry::Record:
Chris Lattner88bde502013-01-19 21:39:22 +00001367 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001368 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattner88bde502013-01-19 21:39:22 +00001369 default: // Default behavior: ignore.
1370 break;
1371
1372 case PP_MACRO_OBJECT_LIKE:
1373 case PP_MACRO_FUNCTION_LIKE:
1374 getLocalIdentifier(**I, Record[0]);
1375 break;
1376
1377 case PP_TOKEN:
1378 // Ignore tokens.
1379 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001380 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001381 break;
1382 }
1383 }
Chris Lattner88bde502013-01-19 21:39:22 +00001384 NextCursor: ;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001385 }
1386}
1387
1388namespace {
1389 /// \brief Visitor class used to look up identifirs in an AST file.
1390 class IdentifierLookupVisitor {
1391 StringRef Name;
1392 unsigned PriorGeneration;
Douglas Gregore1698072013-01-25 00:38:33 +00001393 unsigned &NumIdentifierLookups;
1394 unsigned &NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001395 IdentifierInfo *Found;
Douglas Gregore1698072013-01-25 00:38:33 +00001396
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001397 public:
Douglas Gregore1698072013-01-25 00:38:33 +00001398 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1399 unsigned &NumIdentifierLookups,
1400 unsigned &NumIdentifierLookupHits)
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001401 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregore1698072013-01-25 00:38:33 +00001402 NumIdentifierLookups(NumIdentifierLookups),
1403 NumIdentifierLookupHits(NumIdentifierLookupHits),
1404 Found()
1405 {
1406 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407
1408 static bool visit(ModuleFile &M, void *UserData) {
1409 IdentifierLookupVisitor *This
1410 = static_cast<IdentifierLookupVisitor *>(UserData);
1411
1412 // If we've already searched this module file, skip it now.
1413 if (M.Generation <= This->PriorGeneration)
1414 return true;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001415
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001416 ASTIdentifierLookupTable *IdTable
1417 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1418 if (!IdTable)
1419 return false;
1420
1421 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1422 M, This->Found);
Douglas Gregore1698072013-01-25 00:38:33 +00001423 ++This->NumIdentifierLookups;
1424 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001425 if (Pos == IdTable->end())
1426 return false;
1427
1428 // Dereferencing the iterator has the effect of building the
1429 // IdentifierInfo node and populating it with the various
1430 // declarations it needs.
Douglas Gregore1698072013-01-25 00:38:33 +00001431 ++This->NumIdentifierLookupHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001432 This->Found = *Pos;
1433 return true;
1434 }
1435
1436 // \brief Retrieve the identifier info found within the module
1437 // files.
1438 IdentifierInfo *getIdentifierInfo() const { return Found; }
1439 };
1440}
1441
1442void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1443 // Note that we are loading an identifier.
1444 Deserializing AnIdentifier(this);
1445
1446 unsigned PriorGeneration = 0;
1447 if (getContext().getLangOpts().Modules)
1448 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregor1a49d972013-01-25 01:03:03 +00001449
1450 // If there is a global index, look there first to determine which modules
1451 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001452 GlobalModuleIndex::HitSet Hits;
1453 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001454 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001455 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1456 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00001457 }
1458 }
1459
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001460 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregore1698072013-01-25 00:38:33 +00001461 NumIdentifierLookups,
1462 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00001463 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001464 markIdentifierUpToDate(&II);
1465}
1466
1467void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1468 if (!II)
1469 return;
1470
1471 II->setOutOfDate(false);
1472
1473 // Update the generation for this identifier.
1474 if (getContext().getLangOpts().Modules)
1475 IdentifierGeneration[II] = CurrentGeneration;
1476}
1477
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001478void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1479 const PendingMacroInfo &PMInfo) {
1480 assert(II);
1481
1482 if (PMInfo.M->Kind != MK_Module) {
1483 installPCHMacroDirectives(II, *PMInfo.M,
1484 PMInfo.PCHMacroData.MacroDirectivesOffset);
1485 return;
1486 }
1487
1488 // Module Macro.
1489
1490 GlobalMacroID GMacID = PMInfo.ModuleMacroData.GMacID;
1491 SourceLocation ImportLoc =
1492 SourceLocation::getFromRawEncoding(PMInfo.ModuleMacroData.ImportLoc);
1493
1494 assert(GMacID);
1495 // If this macro has already been loaded, don't do so again.
1496 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1497 return;
1498
1499 MacroInfo *MI = getMacro(GMacID);
1500 SubmoduleID SubModID = MI->getOwningModuleID();
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001501 MacroDirective *MD = PP.AllocateDefMacroDirective(MI, ImportLoc,
1502 /*isImported=*/true);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001503
1504 // Determine whether this macro definition is visible.
1505 bool Hidden = false;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001506 Module *Owner = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001507 if (SubModID) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001508 if ((Owner = getSubmodule(SubModID))) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001509 if (Owner->NameVisibility == Module::Hidden) {
1510 // The owning module is not visible, and this macro definition
1511 // should not be, either.
1512 Hidden = true;
1513
1514 // Note that this macro definition was hidden because its owning
1515 // module is not yet visible.
1516 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
1517 }
1518 }
1519 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001520
1521 if (!Hidden)
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001522 installImportedMacro(II, MD, Owner);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001523}
1524
1525void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1526 ModuleFile &M, uint64_t Offset) {
1527 assert(M.Kind != MK_Module);
1528
1529 BitstreamCursor &Cursor = M.MacroCursor;
1530 SavedStreamPosition SavedPosition(Cursor);
1531 Cursor.JumpToBit(Offset);
1532
1533 llvm::BitstreamEntry Entry =
1534 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1535 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1536 Error("malformed block record in AST file");
1537 return;
1538 }
1539
1540 RecordData Record;
1541 PreprocessorRecordTypes RecType =
1542 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1543 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1544 Error("malformed block record in AST file");
1545 return;
1546 }
1547
1548 // Deserialize the macro directives history in reverse source-order.
1549 MacroDirective *Latest = 0, *Earliest = 0;
1550 unsigned Idx = 0, N = Record.size();
1551 while (Idx < N) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001552 MacroDirective *MD = 0;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001553 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001554 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1555 switch (K) {
1556 case MacroDirective::MD_Define: {
1557 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1558 MacroInfo *MI = getMacro(GMacID);
1559 bool isImported = Record[Idx++];
1560 bool isAmbiguous = Record[Idx++];
1561 DefMacroDirective *DefMD =
1562 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1563 DefMD->setAmbiguous(isAmbiguous);
1564 MD = DefMD;
1565 break;
1566 }
1567 case MacroDirective::MD_Undefine:
1568 MD = PP.AllocateUndefMacroDirective(Loc);
1569 break;
1570 case MacroDirective::MD_Visibility: {
1571 bool isPublic = Record[Idx++];
1572 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1573 break;
1574 }
1575 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001576
1577 if (!Latest)
1578 Latest = MD;
1579 if (Earliest)
1580 Earliest->setPrevious(MD);
1581 Earliest = MD;
1582 }
1583
1584 PP.setLoadedMacroDirective(II, Latest);
1585}
1586
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001587/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor7332ae42013-04-12 21:00:54 +00001588/// modules.
1589static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
1590 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001591 assert(PrevMI && NewMI);
1592 if (!NewOwner)
1593 return false;
1594 Module *PrevOwner = 0;
1595 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1596 PrevOwner = Reader.getSubmodule(PrevModID);
1597 if (!PrevOwner)
1598 return false;
1599 if (PrevOwner == NewOwner)
1600 return false;
Douglas Gregor7332ae42013-04-12 21:00:54 +00001601 return PrevOwner->IsSystem && NewOwner->IsSystem;
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001602}
1603
1604void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1605 Module *Owner) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001606 assert(II && MD);
1607
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001608 DefMacroDirective *DefMD = cast<DefMacroDirective>(MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001609 MacroDirective *Prev = PP.getMacroDirective(II);
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001610 if (Prev) {
1611 MacroDirective::DefInfo PrevDef = Prev->getDefinition();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001612 MacroInfo *PrevMI = PrevDef.getMacroInfo();
1613 MacroInfo *NewMI = DefMD->getInfo();
Argyrios Kyrtzidisbd25ff82013-04-03 17:39:30 +00001614 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP,
1615 /*Syntactically=*/true)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001616 // Before marking the macros as ambiguous, check if this is a case where
Douglas Gregor7332ae42013-04-12 21:00:54 +00001617 // both macros are in system headers. If so, we trust that the system
1618 // did not get it wrong. This also handles cases where Clang's own
1619 // headers have a different spelling of certain system macros:
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001620 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1621 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
Douglas Gregor7332ae42013-04-12 21:00:54 +00001622 if (!areDefinedInSystemModules(PrevMI, NewMI, Owner, *this)) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00001623 PrevDef.getDirective()->setAmbiguous(true);
1624 DefMD->setAmbiguous(true);
1625 }
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001626 }
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001627 }
1628
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +00001629 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00001630}
1631
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001632InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001633 // If this ID is bogus, just return an empty input file.
1634 if (ID == 0 || ID > F.InputFilesLoaded.size())
1635 return InputFile();
1636
1637 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001638 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001639 return F.InputFilesLoaded[ID-1];
1640
1641 // Go find this input file.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001642 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001643 SavedStreamPosition SavedPosition(Cursor);
1644 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1645
1646 unsigned Code = Cursor.ReadCode();
1647 RecordData Record;
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001648 StringRef Blob;
1649 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001650 case INPUT_FILE: {
1651 unsigned StoredID = Record[0];
1652 assert(ID == StoredID && "Bogus stored ID or offset");
1653 (void)StoredID;
1654 off_t StoredSize = (off_t)Record[1];
1655 time_t StoredTime = (time_t)Record[2];
1656 bool Overridden = (bool)Record[3];
1657
1658 // Get the file entry for this input file.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001659 StringRef OrigFilename = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001660 std::string Filename = OrigFilename;
1661 MaybeAddSystemRootToFilename(F, Filename);
1662 const FileEntry *File
1663 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1664 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1665
1666 // If we didn't find the file, resolve it relative to the
1667 // original directory from which this AST file was created.
1668 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1669 F.OriginalDir != CurrentDir) {
1670 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1671 F.OriginalDir,
1672 CurrentDir);
1673 if (!Resolved.empty())
1674 File = FileMgr.getFile(Resolved);
1675 }
1676
1677 // For an overridden file, create a virtual file with the stored
1678 // size/timestamp.
1679 if (Overridden && File == 0) {
1680 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1681 }
1682
1683 if (File == 0) {
1684 if (Complain) {
1685 std::string ErrorStr = "could not find file '";
1686 ErrorStr += Filename;
1687 ErrorStr += "' referenced by AST file";
1688 Error(ErrorStr.c_str());
1689 }
1690 return InputFile();
1691 }
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001692
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001693 // Check if there was a request to override the contents of the file
1694 // that was part of the precompiled header. Overridding such a file
1695 // can lead to problems when lexing using the source locations from the
1696 // PCH.
1697 SourceManager &SM = getSourceManager();
1698 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001699 if (Complain)
1700 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001701 // After emitting the diagnostic, recover by disabling the override so
1702 // that the original file will be used.
1703 SM.disableFileContentsOverride(File);
1704 // The FileEntry is a virtual file entry with the size of the contents
1705 // that would override the original contents. Set it to the original's
1706 // size/time.
1707 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1708 StoredSize, StoredTime);
1709 }
1710
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001711 bool IsOutOfDate = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001712
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001713 // For an overridden file, there is nothing to validate.
1714 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001715#if !defined(LLVM_ON_WIN32)
1716 // In our regression testing, the Windows file system seems to
1717 // have inconsistent modification times that sometimes
1718 // erroneously trigger this error-handling path.
1719 || StoredTime != File->getModificationTime()
1720#endif
1721 )) {
Douglas Gregor677e15f2013-03-19 00:28:20 +00001722 if (Complain) {
Argyrios Kyrtzidisf8f373f2013-03-08 20:42:38 +00001723 Error(diag::err_fe_pch_file_modified, Filename, F.FileName);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001724 }
1725
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001726 IsOutOfDate = true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001727 }
1728
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001729 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1730
1731 // Note that we've loaded this input file.
1732 F.InputFilesLoaded[ID-1] = IF;
1733 return IF;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001734 }
1735 }
1736
1737 return InputFile();
1738}
1739
1740const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1741 ModuleFile &M = ModuleMgr.getPrimaryModule();
1742 std::string Filename = filenameStrRef;
1743 MaybeAddSystemRootToFilename(M, Filename);
1744 const FileEntry *File = FileMgr.getFile(Filename);
1745 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1746 M.OriginalDir != CurrentDir) {
1747 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1748 M.OriginalDir,
1749 CurrentDir);
1750 if (!resolved.empty())
1751 File = FileMgr.getFile(resolved);
1752 }
1753
1754 return File;
1755}
1756
1757/// \brief If we are loading a relocatable PCH file, and the filename is
1758/// not an absolute path, add the system root to the beginning of the file
1759/// name.
1760void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1761 std::string &Filename) {
1762 // If this is not a relocatable PCH file, there's nothing to do.
1763 if (!M.RelocatablePCH)
1764 return;
1765
1766 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1767 return;
1768
1769 if (isysroot.empty()) {
1770 // If no system root was given, default to '/'
1771 Filename.insert(Filename.begin(), '/');
1772 return;
1773 }
1774
1775 unsigned Length = isysroot.size();
1776 if (isysroot[Length - 1] != '/')
1777 Filename.insert(Filename.begin(), '/');
1778
1779 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1780}
1781
1782ASTReader::ASTReadResult
1783ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001784 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001785 unsigned ClientLoadCapabilities) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001786 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001787
1788 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1789 Error("malformed block record in AST file");
1790 return Failure;
1791 }
1792
1793 // Read all of the records and blocks in the control block.
1794 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001795 while (1) {
1796 llvm::BitstreamEntry Entry = Stream.advance();
1797
1798 switch (Entry.Kind) {
1799 case llvm::BitstreamEntry::Error:
1800 Error("malformed block record in AST file");
1801 return Failure;
1802 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001803 // Validate all of the non-system input files.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001804 if (!DisableValidation) {
1805 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Argyrios Kyrtzidis398253a2013-03-06 18:12:50 +00001806 // All user input files reside at the index range [0, Record[1]).
1807 // Record is the one from INPUT_FILE_OFFSETS.
1808 for (unsigned I = 0, N = Record[1]; I < N; ++I) {
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001809 InputFile IF = getInputFile(F, I+1, Complain);
1810 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001811 return OutOfDate;
Argyrios Kyrtzidis8504b7b2013-03-01 03:26:04 +00001812 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001813 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001814 return Success;
Chris Lattner88bde502013-01-19 21:39:22 +00001815
1816 case llvm::BitstreamEntry::SubBlock:
1817 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 case INPUT_FILES_BLOCK_ID:
1819 F.InputFilesCursor = Stream;
1820 if (Stream.SkipBlock() || // Skip with the main cursor
1821 // Read the abbreviations
1822 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1823 Error("malformed block record in AST file");
1824 return Failure;
1825 }
1826 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00001827
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001828 default:
Chris Lattner88bde502013-01-19 21:39:22 +00001829 if (Stream.SkipBlock()) {
1830 Error("malformed block record in AST file");
1831 return Failure;
1832 }
1833 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834 }
Chris Lattner88bde502013-01-19 21:39:22 +00001835
1836 case llvm::BitstreamEntry::Record:
1837 // The interesting case.
1838 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 }
1840
1841 // Read and process a record.
1842 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001843 StringRef Blob;
1844 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001845 case METADATA: {
1846 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1847 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1848 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1849 : diag::warn_pch_version_too_new);
1850 return VersionMismatch;
1851 }
1852
1853 bool hasErrors = Record[5];
1854 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1855 Diag(diag::err_pch_with_compiler_errors);
1856 return HadErrors;
1857 }
1858
1859 F.RelocatablePCH = Record[4];
1860
1861 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001862 StringRef ASTBranch = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1864 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
1865 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1866 return VersionMismatch;
1867 }
1868 break;
1869 }
1870
1871 case IMPORTS: {
1872 // Load each of the imported PCH files.
1873 unsigned Idx = 0, N = Record.size();
1874 while (Idx < N) {
1875 // Read information about the AST file.
1876 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1877 // The import location will be the local one for now; we will adjust
1878 // all import locations of module imports after the global source
1879 // location info are setup.
1880 SourceLocation ImportLoc =
1881 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor677e15f2013-03-19 00:28:20 +00001882 off_t StoredSize = (off_t)Record[Idx++];
1883 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001884 unsigned Length = Record[Idx++];
1885 SmallString<128> ImportedFile(Record.begin() + Idx,
1886 Record.begin() + Idx + Length);
1887 Idx += Length;
1888
1889 // Load the AST file.
1890 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00001891 StoredSize, StoredModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001892 ClientLoadCapabilities)) {
1893 case Failure: return Failure;
1894 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregorac39f132013-03-19 00:38:50 +00001895 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001896 case OutOfDate: return OutOfDate;
1897 case VersionMismatch: return VersionMismatch;
1898 case ConfigurationMismatch: return ConfigurationMismatch;
1899 case HadErrors: return HadErrors;
1900 case Success: break;
1901 }
1902 }
1903 break;
1904 }
1905
1906 case LANGUAGE_OPTIONS: {
1907 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1908 if (Listener && &F == *ModuleMgr.begin() &&
1909 ParseLanguageOptions(Record, Complain, *Listener) &&
1910 !DisableValidation)
1911 return ConfigurationMismatch;
1912 break;
1913 }
1914
1915 case TARGET_OPTIONS: {
1916 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1917 if (Listener && &F == *ModuleMgr.begin() &&
1918 ParseTargetOptions(Record, Complain, *Listener) &&
1919 !DisableValidation)
1920 return ConfigurationMismatch;
1921 break;
1922 }
1923
1924 case DIAGNOSTIC_OPTIONS: {
1925 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1926 if (Listener && &F == *ModuleMgr.begin() &&
1927 ParseDiagnosticOptions(Record, Complain, *Listener) &&
1928 !DisableValidation)
1929 return ConfigurationMismatch;
1930 break;
1931 }
1932
1933 case FILE_SYSTEM_OPTIONS: {
1934 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1935 if (Listener && &F == *ModuleMgr.begin() &&
1936 ParseFileSystemOptions(Record, Complain, *Listener) &&
1937 !DisableValidation)
1938 return ConfigurationMismatch;
1939 break;
1940 }
1941
1942 case HEADER_SEARCH_OPTIONS: {
1943 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1944 if (Listener && &F == *ModuleMgr.begin() &&
1945 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
1946 !DisableValidation)
1947 return ConfigurationMismatch;
1948 break;
1949 }
1950
1951 case PREPROCESSOR_OPTIONS: {
1952 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1953 if (Listener && &F == *ModuleMgr.begin() &&
1954 ParsePreprocessorOptions(Record, Complain, *Listener,
1955 SuggestedPredefines) &&
1956 !DisableValidation)
1957 return ConfigurationMismatch;
1958 break;
1959 }
1960
1961 case ORIGINAL_FILE:
1962 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001963 F.ActualOriginalSourceFileName = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001964 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1965 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1966 break;
1967
1968 case ORIGINAL_FILE_ID:
1969 F.OriginalSourceFileID = FileID::get(Record[0]);
1970 break;
1971
1972 case ORIGINAL_PCH_DIR:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001973 F.OriginalDir = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001974 break;
1975
1976 case INPUT_FILE_OFFSETS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00001977 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001978 F.InputFilesLoaded.resize(Record[0]);
1979 break;
1980 }
1981 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001982}
1983
1984bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00001985 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001986
1987 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1988 Error("malformed block record in AST file");
1989 return true;
1990 }
1991
1992 // Read all of the records and blocks for the AST file.
1993 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00001994 while (1) {
1995 llvm::BitstreamEntry Entry = Stream.advance();
1996
1997 switch (Entry.Kind) {
1998 case llvm::BitstreamEntry::Error:
1999 Error("error at end of module block in AST file");
2000 return true;
2001 case llvm::BitstreamEntry::EndBlock: {
Richard Smith43828672013-04-03 22:49:41 +00002002 // Outside of C++, we do not store a lookup map for the translation unit.
2003 // Instead, mark it as needing a lookup map to be built if this module
2004 // contains any declarations lexically within it (which it always does!).
2005 // This usually has no cost, since we very rarely need the lookup map for
2006 // the translation unit outside C++.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002007 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smith43828672013-04-03 22:49:41 +00002008 if (DC->hasExternalLexicalStorage() &&
2009 !getContext().getLangOpts().CPlusPlus)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002010 DC->setMustBuildLookupTable();
Chris Lattner88bde502013-01-19 21:39:22 +00002011
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002012 return false;
2013 }
Chris Lattner88bde502013-01-19 21:39:22 +00002014 case llvm::BitstreamEntry::SubBlock:
2015 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002016 case DECLTYPES_BLOCK_ID:
2017 // We lazily load the decls block, but we want to set up the
2018 // DeclsCursor cursor to point into it. Clone our current bitcode
2019 // cursor to it, enter the block and read the abbrevs in that block.
2020 // With the main cursor, we just skip over it.
2021 F.DeclsCursor = Stream;
2022 if (Stream.SkipBlock() || // Skip with the main cursor.
2023 // Read the abbrevs.
2024 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2025 Error("malformed block record in AST file");
2026 return true;
2027 }
2028 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002029
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002030 case DECL_UPDATES_BLOCK_ID:
2031 if (Stream.SkipBlock()) {
2032 Error("malformed block record in AST file");
2033 return true;
2034 }
2035 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002036
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002037 case PREPROCESSOR_BLOCK_ID:
2038 F.MacroCursor = Stream;
2039 if (!PP.getExternalSource())
2040 PP.setExternalSource(this);
Chris Lattner88bde502013-01-19 21:39:22 +00002041
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002042 if (Stream.SkipBlock() ||
2043 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2044 Error("malformed block record in AST file");
2045 return true;
2046 }
2047 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2048 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002049
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002050 case PREPROCESSOR_DETAIL_BLOCK_ID:
2051 F.PreprocessorDetailCursor = Stream;
2052 if (Stream.SkipBlock() ||
Chris Lattner88bde502013-01-19 21:39:22 +00002053 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002054 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattner88bde502013-01-19 21:39:22 +00002055 Error("malformed preprocessor detail record in AST file");
2056 return true;
2057 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002058 F.PreprocessorDetailStartOffset
Chris Lattner88bde502013-01-19 21:39:22 +00002059 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2060
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002061 if (!PP.getPreprocessingRecord())
2062 PP.createPreprocessingRecord();
2063 if (!PP.getPreprocessingRecord()->getExternalSource())
2064 PP.getPreprocessingRecord()->SetExternalSource(*this);
2065 break;
2066
2067 case SOURCE_MANAGER_BLOCK_ID:
2068 if (ReadSourceManagerBlock(F))
2069 return true;
2070 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002071
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002072 case SUBMODULE_BLOCK_ID:
2073 if (ReadSubmoduleBlock(F))
2074 return true;
2075 break;
Chris Lattner88bde502013-01-19 21:39:22 +00002076
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002077 case COMMENTS_BLOCK_ID: {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00002078 BitstreamCursor C = Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002079 if (Stream.SkipBlock() ||
2080 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2081 Error("malformed comments block in AST file");
2082 return true;
2083 }
2084 CommentsCursors.push_back(std::make_pair(C, &F));
2085 break;
2086 }
Chris Lattner88bde502013-01-19 21:39:22 +00002087
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002088 default:
Chris Lattner88bde502013-01-19 21:39:22 +00002089 if (Stream.SkipBlock()) {
2090 Error("malformed block record in AST file");
2091 return true;
2092 }
2093 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002094 }
2095 continue;
Chris Lattner88bde502013-01-19 21:39:22 +00002096
2097 case llvm::BitstreamEntry::Record:
2098 // The interesting case.
2099 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100 }
2101
2102 // Read and process a record.
2103 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002104 StringRef Blob;
2105 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002106 default: // Default behavior: ignore.
2107 break;
2108
2109 case TYPE_OFFSET: {
2110 if (F.LocalNumTypes != 0) {
2111 Error("duplicate TYPE_OFFSET record in AST file");
2112 return true;
2113 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002114 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002115 F.LocalNumTypes = Record[0];
2116 unsigned LocalBaseTypeIndex = Record[1];
2117 F.BaseTypeIndex = getTotalNumTypes();
2118
2119 if (F.LocalNumTypes > 0) {
2120 // Introduce the global -> local mapping for types within this module.
2121 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2122
2123 // Introduce the local -> global mapping for types within this module.
2124 F.TypeRemap.insertOrReplace(
2125 std::make_pair(LocalBaseTypeIndex,
2126 F.BaseTypeIndex - LocalBaseTypeIndex));
2127
2128 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2129 }
2130 break;
2131 }
2132
2133 case DECL_OFFSET: {
2134 if (F.LocalNumDecls != 0) {
2135 Error("duplicate DECL_OFFSET record in AST file");
2136 return true;
2137 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002138 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002139 F.LocalNumDecls = Record[0];
2140 unsigned LocalBaseDeclID = Record[1];
2141 F.BaseDeclID = getTotalNumDecls();
2142
2143 if (F.LocalNumDecls > 0) {
2144 // Introduce the global -> local mapping for declarations within this
2145 // module.
2146 GlobalDeclMap.insert(
2147 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2148
2149 // Introduce the local -> global mapping for declarations within this
2150 // module.
2151 F.DeclRemap.insertOrReplace(
2152 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2153
2154 // Introduce the global -> local mapping for declarations within this
2155 // module.
2156 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2157
2158 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2159 }
2160 break;
2161 }
2162
2163 case TU_UPDATE_LEXICAL: {
2164 DeclContext *TU = Context.getTranslationUnitDecl();
2165 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002166 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002167 Info.NumLexicalDecls
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002168 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002169 TU->setHasExternalLexicalStorage(true);
2170 break;
2171 }
2172
2173 case UPDATE_VISIBLE: {
2174 unsigned Idx = 0;
2175 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2176 ASTDeclContextNameLookupTable *Table =
2177 ASTDeclContextNameLookupTable::Create(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002178 (const unsigned char *)Blob.data() + Record[Idx++],
2179 (const unsigned char *)Blob.data(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002180 ASTDeclContextNameLookupTrait(*this, F));
2181 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2182 DeclContext *TU = Context.getTranslationUnitDecl();
2183 F.DeclContextInfos[TU].NameLookupTableData = Table;
2184 TU->setHasExternalVisibleStorage(true);
2185 } else
2186 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2187 break;
2188 }
2189
2190 case IDENTIFIER_TABLE:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002191 F.IdentifierTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002192 if (Record[0]) {
2193 F.IdentifierLookupTable
2194 = ASTIdentifierLookupTable::Create(
2195 (const unsigned char *)F.IdentifierTableData + Record[0],
2196 (const unsigned char *)F.IdentifierTableData,
2197 ASTIdentifierLookupTrait(*this, F));
2198
2199 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2200 }
2201 break;
2202
2203 case IDENTIFIER_OFFSET: {
2204 if (F.LocalNumIdentifiers != 0) {
2205 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2206 return true;
2207 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002208 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002209 F.LocalNumIdentifiers = Record[0];
2210 unsigned LocalBaseIdentifierID = Record[1];
2211 F.BaseIdentifierID = getTotalNumIdentifiers();
2212
2213 if (F.LocalNumIdentifiers > 0) {
2214 // Introduce the global -> local mapping for identifiers within this
2215 // module.
2216 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2217 &F));
2218
2219 // Introduce the local -> global mapping for identifiers within this
2220 // module.
2221 F.IdentifierRemap.insertOrReplace(
2222 std::make_pair(LocalBaseIdentifierID,
2223 F.BaseIdentifierID - LocalBaseIdentifierID));
2224
2225 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2226 + F.LocalNumIdentifiers);
2227 }
2228 break;
2229 }
2230
2231 case EXTERNAL_DEFINITIONS:
2232 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2233 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2234 break;
2235
2236 case SPECIAL_TYPES:
Douglas Gregorf5cfc892013-02-01 23:45:03 +00002237 if (SpecialTypes.empty()) {
2238 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2239 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2240 break;
2241 }
2242
2243 if (SpecialTypes.size() != Record.size()) {
2244 Error("invalid special-types record");
2245 return true;
2246 }
2247
2248 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2249 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2250 if (!SpecialTypes[I])
2251 SpecialTypes[I] = ID;
2252 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2253 // merge step?
2254 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002255 break;
2256
2257 case STATISTICS:
2258 TotalNumStatements += Record[0];
2259 TotalNumMacros += Record[1];
2260 TotalLexicalDeclContexts += Record[2];
2261 TotalVisibleDeclContexts += Record[3];
2262 break;
2263
2264 case UNUSED_FILESCOPED_DECLS:
2265 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2266 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2267 break;
2268
2269 case DELEGATING_CTORS:
2270 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2271 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2272 break;
2273
2274 case WEAK_UNDECLARED_IDENTIFIERS:
2275 if (Record.size() % 4 != 0) {
2276 Error("invalid weak identifiers record");
2277 return true;
2278 }
2279
2280 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2281 // files. This isn't the way to do it :)
2282 WeakUndeclaredIdentifiers.clear();
2283
2284 // Translate the weak, undeclared identifiers into global IDs.
2285 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2286 WeakUndeclaredIdentifiers.push_back(
2287 getGlobalIdentifierID(F, Record[I++]));
2288 WeakUndeclaredIdentifiers.push_back(
2289 getGlobalIdentifierID(F, Record[I++]));
2290 WeakUndeclaredIdentifiers.push_back(
2291 ReadSourceLocation(F, Record, I).getRawEncoding());
2292 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2293 }
2294 break;
2295
Richard Smith5ea6ef42013-01-10 23:43:47 +00002296 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002297 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith5ea6ef42013-01-10 23:43:47 +00002298 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002299 break;
2300
2301 case SELECTOR_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002302 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002303 F.LocalNumSelectors = Record[0];
2304 unsigned LocalBaseSelectorID = Record[1];
2305 F.BaseSelectorID = getTotalNumSelectors();
2306
2307 if (F.LocalNumSelectors > 0) {
2308 // Introduce the global -> local mapping for selectors within this
2309 // module.
2310 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2311
2312 // Introduce the local -> global mapping for selectors within this
2313 // module.
2314 F.SelectorRemap.insertOrReplace(
2315 std::make_pair(LocalBaseSelectorID,
2316 F.BaseSelectorID - LocalBaseSelectorID));
2317
2318 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2319 }
2320 break;
2321 }
2322
2323 case METHOD_POOL:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002324 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002325 if (Record[0])
2326 F.SelectorLookupTable
2327 = ASTSelectorLookupTable::Create(
2328 F.SelectorLookupTableData + Record[0],
2329 F.SelectorLookupTableData,
2330 ASTSelectorLookupTrait(*this, F));
2331 TotalNumMethodPoolEntries += Record[1];
2332 break;
2333
2334 case REFERENCED_SELECTOR_POOL:
2335 if (!Record.empty()) {
2336 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2337 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2338 Record[Idx++]));
2339 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2340 getRawEncoding());
2341 }
2342 }
2343 break;
2344
2345 case PP_COUNTER_VALUE:
2346 if (!Record.empty() && Listener)
2347 Listener->ReadCounter(F, Record[0]);
2348 break;
2349
2350 case FILE_SORTED_DECLS:
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002351 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002352 F.NumFileSortedDecls = Record[0];
2353 break;
2354
2355 case SOURCE_LOCATION_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002356 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002357 F.LocalNumSLocEntries = Record[0];
2358 unsigned SLocSpaceSize = Record[1];
2359 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2360 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2361 SLocSpaceSize);
2362 // Make our entry in the range map. BaseID is negative and growing, so
2363 // we invert it. Because we invert it, though, we need the other end of
2364 // the range.
2365 unsigned RangeStart =
2366 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2367 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2368 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2369
2370 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2371 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2372 GlobalSLocOffsetMap.insert(
2373 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2374 - SLocSpaceSize,&F));
2375
2376 // Initialize the remapping table.
2377 // Invalid stays invalid.
2378 F.SLocRemap.insert(std::make_pair(0U, 0));
2379 // This module. Base was 2 when being compiled.
2380 F.SLocRemap.insert(std::make_pair(2U,
2381 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2382
2383 TotalNumSLocEntries += F.LocalNumSLocEntries;
2384 break;
2385 }
2386
2387 case MODULE_OFFSET_MAP: {
2388 // Additional remapping information.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002389 const unsigned char *Data = (const unsigned char*)Blob.data();
2390 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002391
2392 // Continuous range maps we may be updating in our module.
2393 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2394 ContinuousRangeMap<uint32_t, int, 2>::Builder
2395 IdentifierRemap(F.IdentifierRemap);
2396 ContinuousRangeMap<uint32_t, int, 2>::Builder
2397 MacroRemap(F.MacroRemap);
2398 ContinuousRangeMap<uint32_t, int, 2>::Builder
2399 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2400 ContinuousRangeMap<uint32_t, int, 2>::Builder
2401 SubmoduleRemap(F.SubmoduleRemap);
2402 ContinuousRangeMap<uint32_t, int, 2>::Builder
2403 SelectorRemap(F.SelectorRemap);
2404 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2405 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2406
2407 while(Data < DataEnd) {
2408 uint16_t Len = io::ReadUnalignedLE16(Data);
2409 StringRef Name = StringRef((const char*)Data, Len);
2410 Data += Len;
2411 ModuleFile *OM = ModuleMgr.lookup(Name);
2412 if (!OM) {
2413 Error("SourceLocation remap refers to unknown module");
2414 return true;
2415 }
2416
2417 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2418 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2419 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2420 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2421 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2422 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2423 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2424 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2425
2426 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2427 SLocRemap.insert(std::make_pair(SLocOffset,
2428 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2429 IdentifierRemap.insert(
2430 std::make_pair(IdentifierIDOffset,
2431 OM->BaseIdentifierID - IdentifierIDOffset));
2432 MacroRemap.insert(std::make_pair(MacroIDOffset,
2433 OM->BaseMacroID - MacroIDOffset));
2434 PreprocessedEntityRemap.insert(
2435 std::make_pair(PreprocessedEntityIDOffset,
2436 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2437 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2438 OM->BaseSubmoduleID - SubmoduleIDOffset));
2439 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2440 OM->BaseSelectorID - SelectorIDOffset));
2441 DeclRemap.insert(std::make_pair(DeclIDOffset,
2442 OM->BaseDeclID - DeclIDOffset));
2443
2444 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2445 OM->BaseTypeIndex - TypeIndexOffset));
2446
2447 // Global -> local mappings.
2448 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2449 }
2450 break;
2451 }
2452
2453 case SOURCE_MANAGER_LINE_TABLE:
2454 if (ParseLineTable(F, Record))
2455 return true;
2456 break;
2457
2458 case SOURCE_LOCATION_PRELOADS: {
2459 // Need to transform from the local view (1-based IDs) to the global view,
2460 // which is based off F.SLocEntryBaseID.
2461 if (!F.PreloadSLocEntries.empty()) {
2462 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2463 return true;
2464 }
2465
2466 F.PreloadSLocEntries.swap(Record);
2467 break;
2468 }
2469
2470 case EXT_VECTOR_DECLS:
2471 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2472 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2473 break;
2474
2475 case VTABLE_USES:
2476 if (Record.size() % 3 != 0) {
2477 Error("Invalid VTABLE_USES record");
2478 return true;
2479 }
2480
2481 // Later tables overwrite earlier ones.
2482 // FIXME: Modules will have some trouble with this. This is clearly not
2483 // the right way to do this.
2484 VTableUses.clear();
2485
2486 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2487 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2488 VTableUses.push_back(
2489 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2490 VTableUses.push_back(Record[Idx++]);
2491 }
2492 break;
2493
2494 case DYNAMIC_CLASSES:
2495 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2496 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2497 break;
2498
2499 case PENDING_IMPLICIT_INSTANTIATIONS:
2500 if (PendingInstantiations.size() % 2 != 0) {
2501 Error("Invalid existing PendingInstantiations");
2502 return true;
2503 }
2504
2505 if (Record.size() % 2 != 0) {
2506 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2507 return true;
2508 }
2509
2510 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2511 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2512 PendingInstantiations.push_back(
2513 ReadSourceLocation(F, Record, I).getRawEncoding());
2514 }
2515 break;
2516
2517 case SEMA_DECL_REFS:
2518 // Later tables overwrite earlier ones.
2519 // FIXME: Modules will have some trouble with this.
2520 SemaDeclRefs.clear();
2521 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2522 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2523 break;
2524
2525 case PPD_ENTITIES_OFFSETS: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002526 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2527 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2528 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002529
2530 unsigned LocalBasePreprocessedEntityID = Record[0];
2531
2532 unsigned StartingID;
2533 if (!PP.getPreprocessingRecord())
2534 PP.createPreprocessingRecord();
2535 if (!PP.getPreprocessingRecord()->getExternalSource())
2536 PP.getPreprocessingRecord()->SetExternalSource(*this);
2537 StartingID
2538 = PP.getPreprocessingRecord()
2539 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2540 F.BasePreprocessedEntityID = StartingID;
2541
2542 if (F.NumPreprocessedEntities > 0) {
2543 // Introduce the global -> local mapping for preprocessed entities in
2544 // this module.
2545 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2546
2547 // Introduce the local -> global mapping for preprocessed entities in
2548 // this module.
2549 F.PreprocessedEntityRemap.insertOrReplace(
2550 std::make_pair(LocalBasePreprocessedEntityID,
2551 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2552 }
2553
2554 break;
2555 }
2556
2557 case DECL_UPDATE_OFFSETS: {
2558 if (Record.size() % 2 != 0) {
2559 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2560 return true;
2561 }
2562 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2563 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2564 .push_back(std::make_pair(&F, Record[I+1]));
2565 break;
2566 }
2567
2568 case DECL_REPLACEMENTS: {
2569 if (Record.size() % 3 != 0) {
2570 Error("invalid DECL_REPLACEMENTS block in AST file");
2571 return true;
2572 }
2573 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2574 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2575 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2576 break;
2577 }
2578
2579 case OBJC_CATEGORIES_MAP: {
2580 if (F.LocalNumObjCCategoriesInMap != 0) {
2581 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2582 return true;
2583 }
2584
2585 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002586 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002587 break;
2588 }
2589
2590 case OBJC_CATEGORIES:
2591 F.ObjCCategories.swap(Record);
2592 break;
2593
2594 case CXX_BASE_SPECIFIER_OFFSETS: {
2595 if (F.LocalNumCXXBaseSpecifiers != 0) {
2596 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2597 return true;
2598 }
2599
2600 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002601 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002602 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2603 break;
2604 }
2605
2606 case DIAG_PRAGMA_MAPPINGS:
2607 if (F.PragmaDiagMappings.empty())
2608 F.PragmaDiagMappings.swap(Record);
2609 else
2610 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2611 Record.begin(), Record.end());
2612 break;
2613
2614 case CUDA_SPECIAL_DECL_REFS:
2615 // Later tables overwrite earlier ones.
2616 // FIXME: Modules will have trouble with this.
2617 CUDASpecialDeclRefs.clear();
2618 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2619 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2620 break;
2621
2622 case HEADER_SEARCH_TABLE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002623 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002624 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002625 if (Record[0]) {
2626 F.HeaderFileInfoTable
2627 = HeaderFileInfoLookupTable::Create(
2628 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2629 (const unsigned char *)F.HeaderFileInfoTableData,
2630 HeaderFileInfoTrait(*this, F,
2631 &PP.getHeaderSearchInfo(),
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002632 Blob.data() + Record[2]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002633
2634 PP.getHeaderSearchInfo().SetExternalSource(this);
2635 if (!PP.getHeaderSearchInfo().getExternalLookup())
2636 PP.getHeaderSearchInfo().SetExternalLookup(this);
2637 }
2638 break;
2639 }
2640
2641 case FP_PRAGMA_OPTIONS:
2642 // Later tables overwrite earlier ones.
2643 FPPragmaOptions.swap(Record);
2644 break;
2645
2646 case OPENCL_EXTENSIONS:
2647 // Later tables overwrite earlier ones.
2648 OpenCLExtensions.swap(Record);
2649 break;
2650
2651 case TENTATIVE_DEFINITIONS:
2652 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2653 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2654 break;
2655
2656 case KNOWN_NAMESPACES:
2657 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2658 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2659 break;
Nick Lewycky01a41142013-01-26 00:35:08 +00002660
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002661 case UNDEFINED_BUT_USED:
2662 if (UndefinedButUsed.size() % 2 != 0) {
2663 Error("Invalid existing UndefinedButUsed");
Nick Lewycky01a41142013-01-26 00:35:08 +00002664 return true;
2665 }
2666
2667 if (Record.size() % 2 != 0) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002668 Error("invalid undefined-but-used record");
Nick Lewycky01a41142013-01-26 00:35:08 +00002669 return true;
2670 }
2671 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00002672 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2673 UndefinedButUsed.push_back(
Nick Lewycky01a41142013-01-26 00:35:08 +00002674 ReadSourceLocation(F, Record, I).getRawEncoding());
2675 }
2676 break;
2677
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002678 case IMPORTED_MODULES: {
2679 if (F.Kind != MK_Module) {
2680 // If we aren't loading a module (which has its own exports), make
2681 // all of the imported modules visible.
2682 // FIXME: Deal with macros-only imports.
2683 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2684 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2685 ImportedModules.push_back(GlobalID);
2686 }
2687 }
2688 break;
2689 }
2690
2691 case LOCAL_REDECLARATIONS: {
2692 F.RedeclarationChains.swap(Record);
2693 break;
2694 }
2695
2696 case LOCAL_REDECLARATIONS_MAP: {
2697 if (F.LocalNumRedeclarationsInMap != 0) {
2698 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2699 return true;
2700 }
2701
2702 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002703 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002704 break;
2705 }
2706
2707 case MERGED_DECLARATIONS: {
2708 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2709 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2710 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2711 for (unsigned N = Record[Idx++]; N > 0; --N)
2712 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2713 }
2714 break;
2715 }
2716
2717 case MACRO_OFFSET: {
2718 if (F.LocalNumMacros != 0) {
2719 Error("duplicate MACRO_OFFSET record in AST file");
2720 return true;
2721 }
Chris Lattnerb3ce3572013-01-20 02:38:54 +00002722 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002723 F.LocalNumMacros = Record[0];
2724 unsigned LocalBaseMacroID = Record[1];
2725 F.BaseMacroID = getTotalNumMacros();
2726
2727 if (F.LocalNumMacros > 0) {
2728 // Introduce the global -> local mapping for macros within this module.
2729 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2730
2731 // Introduce the local -> global mapping for macros within this module.
2732 F.MacroRemap.insertOrReplace(
2733 std::make_pair(LocalBaseMacroID,
2734 F.BaseMacroID - LocalBaseMacroID));
2735
2736 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2737 }
2738 break;
2739 }
2740
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00002741 case MACRO_TABLE: {
2742 // FIXME: Not used yet.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002743 break;
2744 }
2745 }
2746 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002747}
2748
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002749/// \brief Move the given method to the back of the global list of methods.
2750static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2751 // Find the entry for this selector in the method pool.
2752 Sema::GlobalMethodPool::iterator Known
2753 = S.MethodPool.find(Method->getSelector());
2754 if (Known == S.MethodPool.end())
2755 return;
2756
2757 // Retrieve the appropriate method list.
2758 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2759 : Known->second.second;
2760 bool Found = false;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002761 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002762 if (!Found) {
2763 if (List->Method == Method) {
2764 Found = true;
2765 } else {
2766 // Keep searching.
2767 continue;
2768 }
2769 }
2770
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002771 if (List->getNext())
2772 List->Method = List->getNext()->Method;
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002773 else
2774 List->Method = Method;
2775 }
2776}
2777
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002778void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002779 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2780 switch (Names[I].getKind()) {
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002781 case HiddenName::Declaration: {
2782 Decl *D = Names[I].getDecl();
2783 bool wasHidden = D->Hidden;
2784 D->Hidden = false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002785
Douglas Gregor2cbd4272013-02-12 23:36:21 +00002786 if (wasHidden && SemaObj) {
2787 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2788 moveMethodToBackOfGlobalList(*SemaObj, Method);
2789 }
2790 }
2791 break;
2792 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002793 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +00002794 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002795 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002796 break;
2797 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002798 }
2799 }
2800}
2801
2802void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00002803 Module::NameVisibilityKind NameVisibility,
Douglas Gregor906d66a2013-03-20 21:10:35 +00002804 SourceLocation ImportLoc,
2805 bool Complain) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002806 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002807 SmallVector<Module *, 4> Stack;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002808 Stack.push_back(Mod);
2809 while (!Stack.empty()) {
2810 Mod = Stack.back();
2811 Stack.pop_back();
2812
2813 if (NameVisibility <= Mod->NameVisibility) {
2814 // This module already has this level of visibility (or greater), so
2815 // there is nothing more to do.
2816 continue;
2817 }
2818
2819 if (!Mod->isAvailable()) {
2820 // Modules that aren't available cannot be made visible.
2821 continue;
2822 }
2823
2824 // Update the module's name visibility.
2825 Mod->NameVisibility = NameVisibility;
2826
2827 // If we've already deserialized any names from this module,
2828 // mark them as visible.
2829 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2830 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00002831 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002832 HiddenNamesMap.erase(Hidden);
2833 }
2834
2835 // Push any non-explicit submodules onto the stack to be marked as
2836 // visible.
2837 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2838 SubEnd = Mod->submodule_end();
2839 Sub != SubEnd; ++Sub) {
2840 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
2841 Stack.push_back(*Sub);
2842 }
2843
2844 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis21a00042013-02-19 19:34:40 +00002845 SmallVector<Module *, 16> Exports;
2846 Mod->getExportedModules(Exports);
2847 for (SmallVectorImpl<Module *>::iterator
2848 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2849 Module *Exported = *I;
2850 if (Visited.insert(Exported))
2851 Stack.push_back(Exported);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002852 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00002853
2854 // Detect any conflicts.
2855 if (Complain) {
2856 assert(ImportLoc.isValid() && "Missing import location");
2857 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2858 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2859 Diag(ImportLoc, diag::warn_module_conflict)
2860 << Mod->getFullModuleName()
2861 << Mod->Conflicts[I].Other->getFullModuleName()
2862 << Mod->Conflicts[I].Message;
2863 // FIXME: Need note where the other module was imported.
2864 }
2865 }
2866 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002867 }
2868}
2869
Douglas Gregor1a49d972013-01-25 01:03:03 +00002870bool ASTReader::loadGlobalIndex() {
2871 if (GlobalIndex)
2872 return false;
2873
2874 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2875 !Context.getLangOpts().Modules)
2876 return true;
2877
2878 // Try to load the global index.
2879 TriedLoadingGlobalIndex = true;
2880 StringRef ModuleCachePath
2881 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2882 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor677e15f2013-03-19 00:28:20 +00002883 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002884 if (!Result.first)
2885 return true;
2886
2887 GlobalIndex.reset(Result.first);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002888 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregor1a49d972013-01-25 01:03:03 +00002889 return false;
2890}
2891
2892bool ASTReader::isGlobalIndexUnavailable() const {
2893 return Context.getLangOpts().Modules && UseGlobalIndex &&
2894 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2895}
2896
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002897ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2898 ModuleKind Type,
2899 SourceLocation ImportLoc,
2900 unsigned ClientLoadCapabilities) {
2901 // Bump the generation number.
2902 unsigned PreviousGeneration = CurrentGeneration++;
2903
2904 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002905 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002906 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2907 /*ImportedBy=*/0, Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00002908 0, 0,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002909 ClientLoadCapabilities)) {
2910 case Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002911 case Missing:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002912 case OutOfDate:
2913 case VersionMismatch:
2914 case ConfigurationMismatch:
2915 case HadErrors:
Douglas Gregor677e15f2013-03-19 00:28:20 +00002916 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2917 Context.getLangOpts().Modules
2918 ? &PP.getHeaderSearchInfo().getModuleMap()
2919 : 0);
Douglas Gregor1a49d972013-01-25 01:03:03 +00002920
2921 // If we find that any modules are unusable, the global index is going
2922 // to be out-of-date. Just remove it.
2923 GlobalIndex.reset();
Douglas Gregor188bdcd2013-01-25 23:32:03 +00002924 ModuleMgr.setGlobalIndex(0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002925 return ReadResult;
2926
2927 case Success:
2928 break;
2929 }
2930
2931 // Here comes stuff that we only do once the entire chain is loaded.
2932
2933 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002934 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2935 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002936 M != MEnd; ++M) {
2937 ModuleFile &F = *M->Mod;
2938
2939 // Read the AST block.
2940 if (ReadASTBlock(F))
2941 return Failure;
2942
2943 // Once read, set the ModuleFile bit base offset and update the size in
2944 // bits of all files we've seen.
2945 F.GlobalBitOffset = TotalModulesSizeInBits;
2946 TotalModulesSizeInBits += F.SizeInBits;
2947 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2948
2949 // Preload SLocEntries.
2950 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2951 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2952 // Load it through the SourceManager and don't call ReadSLocEntry()
2953 // directly because the entry may have already been loaded in which case
2954 // calling ReadSLocEntry() directly would trigger an assertion in
2955 // SourceManager.
2956 SourceMgr.getLoadedSLocEntryByID(Index);
2957 }
2958 }
2959
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002960 // Setup the import locations and notify the module manager that we've
2961 // committed to these module files.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002962 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2963 MEnd = Loaded.end();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002964 M != MEnd; ++M) {
2965 ModuleFile &F = *M->Mod;
Douglas Gregorfa69fc12013-03-22 18:50:14 +00002966
2967 ModuleMgr.moduleFileAccepted(&F);
2968
2969 // Set the import location.
Argyrios Kyrtzidis8b136d82013-02-01 16:36:14 +00002970 F.DirectImportLoc = ImportLoc;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002971 if (!M->ImportedBy)
2972 F.ImportLoc = M->ImportLoc;
2973 else
2974 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
2975 M->ImportLoc.getRawEncoding());
2976 }
2977
2978 // Mark all of the identifiers in the identifier table as being out of date,
2979 // so that various accessors know to check the loaded modules when the
2980 // identifier is used.
2981 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2982 IdEnd = PP.getIdentifierTable().end();
2983 Id != IdEnd; ++Id)
2984 Id->second->setOutOfDate(true);
2985
2986 // Resolve any unresolved module exports.
Douglas Gregor906d66a2013-03-20 21:10:35 +00002987 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
2988 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002989 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
2990 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregor906d66a2013-03-20 21:10:35 +00002991
2992 switch (Unresolved.Kind) {
2993 case UnresolvedModuleRef::Conflict:
2994 if (ResolvedMod) {
2995 Module::Conflict Conflict;
2996 Conflict.Other = ResolvedMod;
2997 Conflict.Message = Unresolved.String.str();
2998 Unresolved.Mod->Conflicts.push_back(Conflict);
2999 }
3000 continue;
3001
3002 case UnresolvedModuleRef::Import:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003003 if (ResolvedMod)
3004 Unresolved.Mod->Imports.push_back(ResolvedMod);
3005 continue;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003006
Douglas Gregor906d66a2013-03-20 21:10:35 +00003007 case UnresolvedModuleRef::Export:
3008 if (ResolvedMod || Unresolved.IsWildcard)
3009 Unresolved.Mod->Exports.push_back(
3010 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3011 continue;
3012 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003013 }
Douglas Gregor906d66a2013-03-20 21:10:35 +00003014 UnresolvedModuleRefs.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003015
3016 InitializeContext();
3017
3018 if (DeserializationListener)
3019 DeserializationListener->ReaderInitialized(this);
3020
3021 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3022 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3023 PrimaryModule.OriginalSourceFileID
3024 = FileID::get(PrimaryModule.SLocEntryBaseID
3025 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3026
3027 // If this AST file is a precompiled preamble, then set the
3028 // preamble file ID of the source manager to the file source file
3029 // from which the preamble was built.
3030 if (Type == MK_Preamble) {
3031 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3032 } else if (Type == MK_MainFile) {
3033 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3034 }
3035 }
3036
3037 // For any Objective-C class definitions we have already loaded, make sure
3038 // that we load any additional categories.
3039 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3040 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3041 ObjCClassesLoaded[I],
3042 PreviousGeneration);
3043 }
Douglas Gregor1a49d972013-01-25 01:03:03 +00003044
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003045 return Success;
3046}
3047
3048ASTReader::ASTReadResult
3049ASTReader::ReadASTCore(StringRef FileName,
3050 ModuleKind Type,
3051 SourceLocation ImportLoc,
3052 ModuleFile *ImportedBy,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003053 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor677e15f2013-03-19 00:28:20 +00003054 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003055 unsigned ClientLoadCapabilities) {
3056 ModuleFile *M;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003057 std::string ErrorStr;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003058 ModuleManager::AddModuleResult AddResult
3059 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3060 CurrentGeneration, ExpectedSize, ExpectedModTime,
3061 M, ErrorStr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003062
Douglas Gregor677e15f2013-03-19 00:28:20 +00003063 switch (AddResult) {
3064 case ModuleManager::AlreadyLoaded:
3065 return Success;
3066
3067 case ModuleManager::NewlyLoaded:
3068 // Load module file below.
3069 break;
3070
3071 case ModuleManager::Missing:
3072 // The module file was missing; if the client handle handle, that, return
3073 // it.
3074 if (ClientLoadCapabilities & ARR_Missing)
3075 return Missing;
3076
3077 // Otherwise, return an error.
3078 {
3079 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3080 + ErrorStr;
3081 Error(Msg);
3082 }
3083 return Failure;
3084
3085 case ModuleManager::OutOfDate:
3086 // We couldn't load the module file because it is out-of-date. If the
3087 // client can handle out-of-date, return it.
3088 if (ClientLoadCapabilities & ARR_OutOfDate)
3089 return OutOfDate;
3090
3091 // Otherwise, return an error.
3092 {
3093 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3094 + ErrorStr;
3095 Error(Msg);
3096 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003097 return Failure;
3098 }
3099
Douglas Gregor677e15f2013-03-19 00:28:20 +00003100 assert(M && "Missing module file");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003101
3102 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3103 // module?
3104 if (FileName != "-") {
3105 CurrentDir = llvm::sys::path::parent_path(FileName);
3106 if (CurrentDir.empty()) CurrentDir = ".";
3107 }
3108
3109 ModuleFile &F = *M;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003110 BitstreamCursor &Stream = F.Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003111 Stream.init(F.StreamFile);
3112 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3113
3114 // Sniff for the signature.
3115 if (Stream.Read(8) != 'C' ||
3116 Stream.Read(8) != 'P' ||
3117 Stream.Read(8) != 'C' ||
3118 Stream.Read(8) != 'H') {
3119 Diag(diag::err_not_a_pch_file) << FileName;
3120 return Failure;
3121 }
3122
3123 // This is used for compatibility with older PCH formats.
3124 bool HaveReadControlBlock = false;
3125
Chris Lattner99a5af02013-01-20 00:00:22 +00003126 while (1) {
3127 llvm::BitstreamEntry Entry = Stream.advance();
3128
3129 switch (Entry.Kind) {
3130 case llvm::BitstreamEntry::Error:
3131 case llvm::BitstreamEntry::EndBlock:
3132 case llvm::BitstreamEntry::Record:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003133 Error("invalid record at top-level of AST file");
3134 return Failure;
Chris Lattner99a5af02013-01-20 00:00:22 +00003135
3136 case llvm::BitstreamEntry::SubBlock:
3137 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003138 }
3139
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003140 // We only know the control subblock ID.
Chris Lattner99a5af02013-01-20 00:00:22 +00003141 switch (Entry.ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003142 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3143 if (Stream.ReadBlockInfoBlock()) {
3144 Error("malformed BlockInfoBlock in AST file");
3145 return Failure;
3146 }
3147 break;
3148 case CONTROL_BLOCK_ID:
3149 HaveReadControlBlock = true;
3150 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3151 case Success:
3152 break;
3153
3154 case Failure: return Failure;
Douglas Gregor677e15f2013-03-19 00:28:20 +00003155 case Missing: return Missing;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003156 case OutOfDate: return OutOfDate;
3157 case VersionMismatch: return VersionMismatch;
3158 case ConfigurationMismatch: return ConfigurationMismatch;
3159 case HadErrors: return HadErrors;
3160 }
3161 break;
3162 case AST_BLOCK_ID:
3163 if (!HaveReadControlBlock) {
3164 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3165 Diag(diag::warn_pch_version_too_old);
3166 return VersionMismatch;
3167 }
3168
3169 // Record that we've loaded this module.
3170 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3171 return Success;
3172
3173 default:
3174 if (Stream.SkipBlock()) {
3175 Error("malformed block record in AST file");
3176 return Failure;
3177 }
3178 break;
3179 }
3180 }
3181
3182 return Success;
3183}
3184
3185void ASTReader::InitializeContext() {
3186 // If there's a listener, notify them that we "read" the translation unit.
3187 if (DeserializationListener)
3188 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3189 Context.getTranslationUnitDecl());
3190
3191 // Make sure we load the declaration update records for the translation unit,
3192 // if there are any.
3193 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3194 Context.getTranslationUnitDecl());
3195
3196 // FIXME: Find a better way to deal with collisions between these
3197 // built-in types. Right now, we just ignore the problem.
3198
3199 // Load the special types.
3200 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3201 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3202 if (!Context.CFConstantStringTypeDecl)
3203 Context.setCFConstantStringType(GetType(String));
3204 }
3205
3206 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3207 QualType FileType = GetType(File);
3208 if (FileType.isNull()) {
3209 Error("FILE type is NULL");
3210 return;
3211 }
3212
3213 if (!Context.FILEDecl) {
3214 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3215 Context.setFILEDecl(Typedef->getDecl());
3216 else {
3217 const TagType *Tag = FileType->getAs<TagType>();
3218 if (!Tag) {
3219 Error("Invalid FILE type in AST file");
3220 return;
3221 }
3222 Context.setFILEDecl(Tag->getDecl());
3223 }
3224 }
3225 }
3226
3227 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3228 QualType Jmp_bufType = GetType(Jmp_buf);
3229 if (Jmp_bufType.isNull()) {
3230 Error("jmp_buf type is NULL");
3231 return;
3232 }
3233
3234 if (!Context.jmp_bufDecl) {
3235 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3236 Context.setjmp_bufDecl(Typedef->getDecl());
3237 else {
3238 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3239 if (!Tag) {
3240 Error("Invalid jmp_buf type in AST file");
3241 return;
3242 }
3243 Context.setjmp_bufDecl(Tag->getDecl());
3244 }
3245 }
3246 }
3247
3248 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3249 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3250 if (Sigjmp_bufType.isNull()) {
3251 Error("sigjmp_buf type is NULL");
3252 return;
3253 }
3254
3255 if (!Context.sigjmp_bufDecl) {
3256 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3257 Context.setsigjmp_bufDecl(Typedef->getDecl());
3258 else {
3259 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3260 assert(Tag && "Invalid sigjmp_buf type in AST file");
3261 Context.setsigjmp_bufDecl(Tag->getDecl());
3262 }
3263 }
3264 }
3265
3266 if (unsigned ObjCIdRedef
3267 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3268 if (Context.ObjCIdRedefinitionType.isNull())
3269 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3270 }
3271
3272 if (unsigned ObjCClassRedef
3273 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3274 if (Context.ObjCClassRedefinitionType.isNull())
3275 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3276 }
3277
3278 if (unsigned ObjCSelRedef
3279 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3280 if (Context.ObjCSelRedefinitionType.isNull())
3281 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3282 }
3283
3284 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3285 QualType Ucontext_tType = GetType(Ucontext_t);
3286 if (Ucontext_tType.isNull()) {
3287 Error("ucontext_t type is NULL");
3288 return;
3289 }
3290
3291 if (!Context.ucontext_tDecl) {
3292 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3293 Context.setucontext_tDecl(Typedef->getDecl());
3294 else {
3295 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3296 assert(Tag && "Invalid ucontext_t type in AST file");
3297 Context.setucontext_tDecl(Tag->getDecl());
3298 }
3299 }
3300 }
3301 }
3302
3303 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3304
3305 // If there were any CUDA special declarations, deserialize them.
3306 if (!CUDASpecialDeclRefs.empty()) {
3307 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3308 Context.setcudaConfigureCallDecl(
3309 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3310 }
3311
3312 // Re-export any modules that were imported by a non-module AST file.
3313 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3314 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis5ebcb202013-02-01 16:36:12 +00003315 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregor906d66a2013-03-20 21:10:35 +00003316 /*ImportLoc=*/SourceLocation(),
3317 /*Complain=*/false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003318 }
3319 ImportedModules.clear();
3320}
3321
3322void ASTReader::finalizeForWriting() {
3323 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3324 HiddenEnd = HiddenNamesMap.end();
3325 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis52151fd2013-03-27 01:25:34 +00003326 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003327 }
3328 HiddenNamesMap.clear();
3329}
3330
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003331/// SkipCursorToControlBlock - Given a cursor at the start of an AST file, scan
3332/// ahead and drop the cursor into the start of the CONTROL_BLOCK, returning
3333/// false on success and true on failure.
3334static bool SkipCursorToControlBlock(BitstreamCursor &Cursor) {
3335 while (1) {
3336 llvm::BitstreamEntry Entry = Cursor.advance();
3337 switch (Entry.Kind) {
3338 case llvm::BitstreamEntry::Error:
3339 case llvm::BitstreamEntry::EndBlock:
3340 return true;
3341
3342 case llvm::BitstreamEntry::Record:
3343 // Ignore top-level records.
3344 Cursor.skipRecord(Entry.ID);
3345 break;
3346
3347 case llvm::BitstreamEntry::SubBlock:
3348 if (Entry.ID == CONTROL_BLOCK_ID) {
3349 if (Cursor.EnterSubBlock(CONTROL_BLOCK_ID))
3350 return true;
3351 // Found it!
3352 return false;
3353 }
3354
3355 if (Cursor.SkipBlock())
3356 return true;
3357 }
3358 }
3359}
3360
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003361/// \brief Retrieve the name of the original source file name
3362/// directly from the AST file, without actually loading the AST
3363/// file.
3364std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3365 FileManager &FileMgr,
3366 DiagnosticsEngine &Diags) {
3367 // Open the AST file.
3368 std::string ErrStr;
3369 OwningPtr<llvm::MemoryBuffer> Buffer;
3370 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3371 if (!Buffer) {
3372 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3373 return std::string();
3374 }
3375
3376 // Initialize the stream
3377 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003378 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003379 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3380 (const unsigned char *)Buffer->getBufferEnd());
3381 Stream.init(StreamFile);
3382
3383 // Sniff for the signature.
3384 if (Stream.Read(8) != 'C' ||
3385 Stream.Read(8) != 'P' ||
3386 Stream.Read(8) != 'C' ||
3387 Stream.Read(8) != 'H') {
3388 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3389 return std::string();
3390 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003391
Chris Lattner88bde502013-01-19 21:39:22 +00003392 // Scan for the CONTROL_BLOCK_ID block.
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003393 if (SkipCursorToControlBlock(Stream)) {
3394 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3395 return std::string();
Chris Lattner88bde502013-01-19 21:39:22 +00003396 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003397
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003398 // Scan for ORIGINAL_FILE inside the control block.
3399 RecordData Record;
Chris Lattner88bde502013-01-19 21:39:22 +00003400 while (1) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003401 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattner88bde502013-01-19 21:39:22 +00003402 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3403 return std::string();
3404
3405 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3406 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3407 return std::string();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003408 }
Chris Lattner88bde502013-01-19 21:39:22 +00003409
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003410 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003411 StringRef Blob;
3412 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3413 return Blob.str();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003414 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003415}
3416
3417namespace {
3418 class SimplePCHValidator : public ASTReaderListener {
3419 const LangOptions &ExistingLangOpts;
3420 const TargetOptions &ExistingTargetOpts;
3421 const PreprocessorOptions &ExistingPPOpts;
3422 FileManager &FileMgr;
3423
3424 public:
3425 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3426 const TargetOptions &ExistingTargetOpts,
3427 const PreprocessorOptions &ExistingPPOpts,
3428 FileManager &FileMgr)
3429 : ExistingLangOpts(ExistingLangOpts),
3430 ExistingTargetOpts(ExistingTargetOpts),
3431 ExistingPPOpts(ExistingPPOpts),
3432 FileMgr(FileMgr)
3433 {
3434 }
3435
3436 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3437 bool Complain) {
3438 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3439 }
3440 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3441 bool Complain) {
3442 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3443 }
3444 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3445 bool Complain,
3446 std::string &SuggestedPredefines) {
3447 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00003448 SuggestedPredefines, ExistingLangOpts);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003449 }
3450 };
3451}
3452
3453bool ASTReader::readASTFileControlBlock(StringRef Filename,
3454 FileManager &FileMgr,
3455 ASTReaderListener &Listener) {
3456 // Open the AST file.
3457 std::string ErrStr;
3458 OwningPtr<llvm::MemoryBuffer> Buffer;
3459 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3460 if (!Buffer) {
3461 return true;
3462 }
3463
3464 // Initialize the stream
3465 llvm::BitstreamReader StreamFile;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003466 BitstreamCursor Stream;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003467 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3468 (const unsigned char *)Buffer->getBufferEnd());
3469 Stream.init(StreamFile);
3470
3471 // Sniff for the signature.
3472 if (Stream.Read(8) != 'C' ||
3473 Stream.Read(8) != 'P' ||
3474 Stream.Read(8) != 'C' ||
3475 Stream.Read(8) != 'H') {
3476 return true;
3477 }
3478
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003479 // Scan for the CONTROL_BLOCK_ID block.
3480 if (SkipCursorToControlBlock(Stream))
3481 return true;
3482
3483 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003484 RecordData Record;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003485 while (1) {
3486 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3487 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3488 return false;
3489
3490 if (Entry.Kind != llvm::BitstreamEntry::Record)
3491 return true;
3492
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003493 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003494 StringRef Blob;
3495 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003496 switch ((ControlRecordTypes)RecCode) {
3497 case METADATA: {
3498 if (Record[0] != VERSION_MAJOR)
3499 return true;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003500
Douglas Gregorc544ba02013-03-27 16:47:18 +00003501 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003502 return true;
Douglas Gregorc544ba02013-03-27 16:47:18 +00003503
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003504 break;
3505 }
3506 case LANGUAGE_OPTIONS:
3507 if (ParseLanguageOptions(Record, false, Listener))
3508 return true;
3509 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003510
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003511 case TARGET_OPTIONS:
3512 if (ParseTargetOptions(Record, false, Listener))
3513 return true;
3514 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003515
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003516 case DIAGNOSTIC_OPTIONS:
3517 if (ParseDiagnosticOptions(Record, false, Listener))
3518 return true;
3519 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003520
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003521 case FILE_SYSTEM_OPTIONS:
3522 if (ParseFileSystemOptions(Record, false, Listener))
3523 return true;
3524 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003525
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003526 case HEADER_SEARCH_OPTIONS:
3527 if (ParseHeaderSearchOptions(Record, false, Listener))
3528 return true;
3529 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003530
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003531 case PREPROCESSOR_OPTIONS: {
3532 std::string IgnoredSuggestedPredefines;
3533 if (ParsePreprocessorOptions(Record, false, Listener,
3534 IgnoredSuggestedPredefines))
3535 return true;
3536 break;
3537 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003538
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003539 default:
3540 // No other validation to perform.
3541 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003542 }
3543 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003544}
3545
3546
3547bool ASTReader::isAcceptableASTFile(StringRef Filename,
3548 FileManager &FileMgr,
3549 const LangOptions &LangOpts,
3550 const TargetOptions &TargetOpts,
3551 const PreprocessorOptions &PPOpts) {
3552 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3553 return !readASTFileControlBlock(Filename, FileMgr, validator);
3554}
3555
3556bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3557 // Enter the submodule block.
3558 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3559 Error("malformed submodule block record in AST file");
3560 return true;
3561 }
3562
3563 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3564 bool First = true;
3565 Module *CurrentModule = 0;
3566 RecordData Record;
3567 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003568 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3569
3570 switch (Entry.Kind) {
3571 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3572 case llvm::BitstreamEntry::Error:
3573 Error("malformed block record in AST file");
3574 return true;
3575 case llvm::BitstreamEntry::EndBlock:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003576 return false;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003577 case llvm::BitstreamEntry::Record:
3578 // The interesting case.
3579 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003580 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00003581
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003582 // Read a record.
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003583 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003584 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003585 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003586 default: // Default behavior: ignore.
3587 break;
3588
3589 case SUBMODULE_DEFINITION: {
3590 if (First) {
3591 Error("missing submodule metadata record at beginning of block");
3592 return true;
3593 }
3594
Douglas Gregor970e4412013-03-20 03:59:18 +00003595 if (Record.size() < 8) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003596 Error("malformed module definition");
3597 return true;
3598 }
3599
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003600 StringRef Name = Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003601 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3602 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3603 bool IsFramework = Record[2];
3604 bool IsExplicit = Record[3];
3605 bool IsSystem = Record[4];
3606 bool InferSubmodules = Record[5];
3607 bool InferExplicitSubmodules = Record[6];
3608 bool InferExportWildcard = Record[7];
Douglas Gregor970e4412013-03-20 03:59:18 +00003609 bool ConfigMacrosExhaustive = Record[8];
3610
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003611 Module *ParentModule = 0;
3612 if (Parent)
3613 ParentModule = getSubmodule(Parent);
3614
3615 // Retrieve this (sub)module from the module map, creating it if
3616 // necessary.
3617 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3618 IsFramework,
3619 IsExplicit).first;
3620 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3621 if (GlobalIndex >= SubmodulesLoaded.size() ||
3622 SubmodulesLoaded[GlobalIndex]) {
3623 Error("too many submodules");
3624 return true;
3625 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003626
Douglas Gregor677e15f2013-03-19 00:28:20 +00003627 if (!ParentModule) {
3628 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3629 if (CurFile != F.File) {
3630 if (!Diags.isDiagnosticInFlight()) {
3631 Diag(diag::err_module_file_conflict)
3632 << CurrentModule->getTopLevelModuleName()
3633 << CurFile->getName()
3634 << F.File->getName();
3635 }
3636 return true;
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003637 }
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003638 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003639
3640 CurrentModule->setASTFile(F.File);
Douglas Gregor8bf778e2013-02-06 22:40:31 +00003641 }
Douglas Gregor677e15f2013-03-19 00:28:20 +00003642
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003643 CurrentModule->IsFromModuleFile = true;
3644 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3645 CurrentModule->InferSubmodules = InferSubmodules;
3646 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3647 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor970e4412013-03-20 03:59:18 +00003648 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003649 if (DeserializationListener)
3650 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3651
3652 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003653
Douglas Gregor906d66a2013-03-20 21:10:35 +00003654 // Clear out data that will be replaced by what is the module file.
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003655 CurrentModule->LinkLibraries.clear();
Douglas Gregor970e4412013-03-20 03:59:18 +00003656 CurrentModule->ConfigMacros.clear();
Douglas Gregor906d66a2013-03-20 21:10:35 +00003657 CurrentModule->UnresolvedConflicts.clear();
3658 CurrentModule->Conflicts.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003659 break;
3660 }
3661
3662 case SUBMODULE_UMBRELLA_HEADER: {
3663 if (First) {
3664 Error("missing submodule metadata record at beginning of block");
3665 return true;
3666 }
3667
3668 if (!CurrentModule)
3669 break;
3670
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003671 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003672 if (!CurrentModule->getUmbrellaHeader())
3673 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3674 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3675 Error("mismatched umbrella headers in submodule");
3676 return true;
3677 }
3678 }
3679 break;
3680 }
3681
3682 case SUBMODULE_HEADER: {
3683 if (First) {
3684 Error("missing submodule metadata record at beginning of block");
3685 return true;
3686 }
3687
3688 if (!CurrentModule)
3689 break;
3690
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003691 // We lazily associate headers with their modules via the HeaderInfoTable.
3692 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3693 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003694 break;
3695 }
3696
3697 case SUBMODULE_EXCLUDED_HEADER: {
3698 if (First) {
3699 Error("missing submodule metadata record at beginning of block");
3700 return true;
3701 }
3702
3703 if (!CurrentModule)
3704 break;
3705
Argyrios Kyrtzidis55ea75b2013-03-13 21:13:51 +00003706 // We lazily associate headers with their modules via the HeaderInfoTable.
3707 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3708 // of complete filenames or remove it entirely.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003709 break;
3710 }
3711
3712 case SUBMODULE_TOPHEADER: {
3713 if (First) {
3714 Error("missing submodule metadata record at beginning of block");
3715 return true;
3716 }
3717
3718 if (!CurrentModule)
3719 break;
3720
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00003721 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003722 break;
3723 }
3724
3725 case SUBMODULE_UMBRELLA_DIR: {
3726 if (First) {
3727 Error("missing submodule metadata record at beginning of block");
3728 return true;
3729 }
3730
3731 if (!CurrentModule)
3732 break;
3733
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003734 if (const DirectoryEntry *Umbrella
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003735 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003736 if (!CurrentModule->getUmbrellaDir())
3737 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3738 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3739 Error("mismatched umbrella directories in submodule");
3740 return true;
3741 }
3742 }
3743 break;
3744 }
3745
3746 case SUBMODULE_METADATA: {
3747 if (!First) {
3748 Error("submodule metadata record not at beginning of block");
3749 return true;
3750 }
3751 First = false;
3752
3753 F.BaseSubmoduleID = getTotalNumSubmodules();
3754 F.LocalNumSubmodules = Record[0];
3755 unsigned LocalBaseSubmoduleID = Record[1];
3756 if (F.LocalNumSubmodules > 0) {
3757 // Introduce the global -> local mapping for submodules within this
3758 // module.
3759 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3760
3761 // Introduce the local -> global mapping for submodules within this
3762 // module.
3763 F.SubmoduleRemap.insertOrReplace(
3764 std::make_pair(LocalBaseSubmoduleID,
3765 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3766
3767 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3768 }
3769 break;
3770 }
3771
3772 case SUBMODULE_IMPORTS: {
3773 if (First) {
3774 Error("missing submodule metadata record at beginning of block");
3775 return true;
3776 }
3777
3778 if (!CurrentModule)
3779 break;
3780
3781 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003782 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003783 Unresolved.File = &F;
3784 Unresolved.Mod = CurrentModule;
3785 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003786 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003787 Unresolved.IsWildcard = false;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003788 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003789 }
3790 break;
3791 }
3792
3793 case SUBMODULE_EXPORTS: {
3794 if (First) {
3795 Error("missing submodule metadata record at beginning of block");
3796 return true;
3797 }
3798
3799 if (!CurrentModule)
3800 break;
3801
3802 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor906d66a2013-03-20 21:10:35 +00003803 UnresolvedModuleRef Unresolved;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003804 Unresolved.File = &F;
3805 Unresolved.Mod = CurrentModule;
3806 Unresolved.ID = Record[Idx];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003807 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003808 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregor906d66a2013-03-20 21:10:35 +00003809 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003810 }
3811
3812 // Once we've loaded the set of exports, there's no reason to keep
3813 // the parsed, unresolved exports around.
3814 CurrentModule->UnresolvedExports.clear();
3815 break;
3816 }
3817 case SUBMODULE_REQUIRES: {
3818 if (First) {
3819 Error("missing submodule metadata record at beginning of block");
3820 return true;
3821 }
3822
3823 if (!CurrentModule)
3824 break;
3825
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003826 CurrentModule->addRequirement(Blob, Context.getLangOpts(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003827 Context.getTargetInfo());
3828 break;
3829 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003830
3831 case SUBMODULE_LINK_LIBRARY:
3832 if (First) {
3833 Error("missing submodule metadata record at beginning of block");
3834 return true;
3835 }
3836
3837 if (!CurrentModule)
3838 break;
3839
3840 CurrentModule->LinkLibraries.push_back(
Chris Lattnerb3ce3572013-01-20 02:38:54 +00003841 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003842 break;
Douglas Gregor63a72682013-03-20 00:22:05 +00003843
3844 case SUBMODULE_CONFIG_MACRO:
3845 if (First) {
3846 Error("missing submodule metadata record at beginning of block");
3847 return true;
3848 }
3849
3850 if (!CurrentModule)
3851 break;
3852
3853 CurrentModule->ConfigMacros.push_back(Blob.str());
3854 break;
Douglas Gregor906d66a2013-03-20 21:10:35 +00003855
3856 case SUBMODULE_CONFLICT: {
3857 if (First) {
3858 Error("missing submodule metadata record at beginning of block");
3859 return true;
3860 }
3861
3862 if (!CurrentModule)
3863 break;
3864
3865 UnresolvedModuleRef Unresolved;
3866 Unresolved.File = &F;
3867 Unresolved.Mod = CurrentModule;
3868 Unresolved.ID = Record[0];
3869 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3870 Unresolved.IsWildcard = false;
3871 Unresolved.String = Blob;
3872 UnresolvedModuleRefs.push_back(Unresolved);
3873 break;
3874 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003875 }
3876 }
3877}
3878
3879/// \brief Parse the record that corresponds to a LangOptions data
3880/// structure.
3881///
3882/// This routine parses the language options from the AST file and then gives
3883/// them to the AST listener if one is set.
3884///
3885/// \returns true if the listener deems the file unacceptable, false otherwise.
3886bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3887 bool Complain,
3888 ASTReaderListener &Listener) {
3889 LangOptions LangOpts;
3890 unsigned Idx = 0;
3891#define LANGOPT(Name, Bits, Default, Description) \
3892 LangOpts.Name = Record[Idx++];
3893#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3894 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3895#include "clang/Basic/LangOptions.def"
Will Dietz4f45bc02013-01-18 11:30:38 +00003896#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
3897#include "clang/Basic/Sanitizers.def"
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003898
3899 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3900 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3901 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3902
3903 unsigned Length = Record[Idx++];
3904 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3905 Record.begin() + Idx + Length);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003906
3907 Idx += Length;
3908
3909 // Comment options.
3910 for (unsigned N = Record[Idx++]; N; --N) {
3911 LangOpts.CommentOpts.BlockCommandNames.push_back(
3912 ReadString(Record, Idx));
3913 }
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00003914 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +00003915
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003916 return Listener.ReadLanguageOptions(LangOpts, Complain);
3917}
3918
3919bool ASTReader::ParseTargetOptions(const RecordData &Record,
3920 bool Complain,
3921 ASTReaderListener &Listener) {
3922 unsigned Idx = 0;
3923 TargetOptions TargetOpts;
3924 TargetOpts.Triple = ReadString(Record, Idx);
3925 TargetOpts.CPU = ReadString(Record, Idx);
3926 TargetOpts.ABI = ReadString(Record, Idx);
3927 TargetOpts.CXXABI = ReadString(Record, Idx);
3928 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3929 for (unsigned N = Record[Idx++]; N; --N) {
3930 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3931 }
3932 for (unsigned N = Record[Idx++]; N; --N) {
3933 TargetOpts.Features.push_back(ReadString(Record, Idx));
3934 }
3935
3936 return Listener.ReadTargetOptions(TargetOpts, Complain);
3937}
3938
3939bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3940 ASTReaderListener &Listener) {
3941 DiagnosticOptions DiagOpts;
3942 unsigned Idx = 0;
3943#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3944#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3945 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3946#include "clang/Basic/DiagnosticOptions.def"
3947
3948 for (unsigned N = Record[Idx++]; N; --N) {
3949 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3950 }
3951
3952 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
3953}
3954
3955bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
3956 ASTReaderListener &Listener) {
3957 FileSystemOptions FSOpts;
3958 unsigned Idx = 0;
3959 FSOpts.WorkingDir = ReadString(Record, Idx);
3960 return Listener.ReadFileSystemOptions(FSOpts, Complain);
3961}
3962
3963bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
3964 bool Complain,
3965 ASTReaderListener &Listener) {
3966 HeaderSearchOptions HSOpts;
3967 unsigned Idx = 0;
3968 HSOpts.Sysroot = ReadString(Record, Idx);
3969
3970 // Include entries.
3971 for (unsigned N = Record[Idx++]; N; --N) {
3972 std::string Path = ReadString(Record, Idx);
3973 frontend::IncludeDirGroup Group
3974 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003975 bool IsFramework = Record[Idx++];
3976 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003977 HSOpts.UserEntries.push_back(
Daniel Dunbar59fd6352013-01-30 00:34:26 +00003978 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003979 }
3980
3981 // System header prefixes.
3982 for (unsigned N = Record[Idx++]; N; --N) {
3983 std::string Prefix = ReadString(Record, Idx);
3984 bool IsSystemHeader = Record[Idx++];
3985 HSOpts.SystemHeaderPrefixes.push_back(
3986 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
3987 }
3988
3989 HSOpts.ResourceDir = ReadString(Record, Idx);
3990 HSOpts.ModuleCachePath = ReadString(Record, Idx);
3991 HSOpts.DisableModuleHash = Record[Idx++];
3992 HSOpts.UseBuiltinIncludes = Record[Idx++];
3993 HSOpts.UseStandardSystemIncludes = Record[Idx++];
3994 HSOpts.UseStandardCXXIncludes = Record[Idx++];
3995 HSOpts.UseLibcxx = Record[Idx++];
3996
3997 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
3998}
3999
4000bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4001 bool Complain,
4002 ASTReaderListener &Listener,
4003 std::string &SuggestedPredefines) {
4004 PreprocessorOptions PPOpts;
4005 unsigned Idx = 0;
4006
4007 // Macro definitions/undefs
4008 for (unsigned N = Record[Idx++]; N; --N) {
4009 std::string Macro = ReadString(Record, Idx);
4010 bool IsUndef = Record[Idx++];
4011 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4012 }
4013
4014 // Includes
4015 for (unsigned N = Record[Idx++]; N; --N) {
4016 PPOpts.Includes.push_back(ReadString(Record, Idx));
4017 }
4018
4019 // Macro Includes
4020 for (unsigned N = Record[Idx++]; N; --N) {
4021 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4022 }
4023
4024 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidis65110ca2013-04-26 21:33:40 +00004025 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004026 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4027 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4028 PPOpts.ObjCXXARCStandardLibrary =
4029 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4030 SuggestedPredefines.clear();
4031 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4032 SuggestedPredefines);
4033}
4034
4035std::pair<ModuleFile *, unsigned>
4036ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4037 GlobalPreprocessedEntityMapType::iterator
4038 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4039 assert(I != GlobalPreprocessedEntityMap.end() &&
4040 "Corrupted global preprocessed entity map");
4041 ModuleFile *M = I->second;
4042 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4043 return std::make_pair(M, LocalIndex);
4044}
4045
4046std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4047ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4048 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4049 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4050 Mod.NumPreprocessedEntities);
4051
4052 return std::make_pair(PreprocessingRecord::iterator(),
4053 PreprocessingRecord::iterator());
4054}
4055
4056std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4057ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4058 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4059 ModuleDeclIterator(this, &Mod,
4060 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4061}
4062
4063PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4064 PreprocessedEntityID PPID = Index+1;
4065 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4066 ModuleFile &M = *PPInfo.first;
4067 unsigned LocalIndex = PPInfo.second;
4068 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4069
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004070 if (!PP.getPreprocessingRecord()) {
4071 Error("no preprocessing record");
4072 return 0;
4073 }
4074
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004075 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4076 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4077
4078 llvm::BitstreamEntry Entry =
4079 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4080 if (Entry.Kind != llvm::BitstreamEntry::Record)
4081 return 0;
4082
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004083 // Read the record.
4084 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4085 ReadSourceLocation(M, PPOffs.End));
4086 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004087 StringRef Blob;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004088 RecordData Record;
4089 PreprocessorDetailRecordTypes RecType =
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004090 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4091 Entry.ID, Record, &Blob);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004092 switch (RecType) {
4093 case PPD_MACRO_EXPANSION: {
4094 bool isBuiltin = Record[0];
4095 IdentifierInfo *Name = 0;
4096 MacroDefinition *Def = 0;
4097 if (isBuiltin)
4098 Name = getLocalIdentifier(M, Record[1]);
4099 else {
4100 PreprocessedEntityID
4101 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4102 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4103 }
4104
4105 MacroExpansion *ME;
4106 if (isBuiltin)
4107 ME = new (PPRec) MacroExpansion(Name, Range);
4108 else
4109 ME = new (PPRec) MacroExpansion(Def, Range);
4110
4111 return ME;
4112 }
4113
4114 case PPD_MACRO_DEFINITION: {
4115 // Decode the identifier info and then check again; if the macro is
4116 // still defined and associated with the identifier,
4117 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4118 MacroDefinition *MD
4119 = new (PPRec) MacroDefinition(II, Range);
4120
4121 if (DeserializationListener)
4122 DeserializationListener->MacroDefinitionRead(PPID, MD);
4123
4124 return MD;
4125 }
4126
4127 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004128 const char *FullFileNameStart = Blob.data() + Record[0];
4129 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004130 const FileEntry *File = 0;
4131 if (!FullFileName.empty())
4132 File = PP.getFileManager().getFile(FullFileName);
4133
4134 // FIXME: Stable encoding
4135 InclusionDirective::InclusionKind Kind
4136 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4137 InclusionDirective *ID
4138 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004139 StringRef(Blob.data(), Record[0]),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004140 Record[1], Record[3],
4141 File,
4142 Range);
4143 return ID;
4144 }
4145 }
4146
4147 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4148}
4149
4150/// \brief \arg SLocMapI points at a chunk of a module that contains no
4151/// preprocessed entities or the entities it contains are not the ones we are
4152/// looking for. Find the next module that contains entities and return the ID
4153/// of the first entry.
4154PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4155 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4156 ++SLocMapI;
4157 for (GlobalSLocOffsetMapType::const_iterator
4158 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4159 ModuleFile &M = *SLocMapI->second;
4160 if (M.NumPreprocessedEntities)
4161 return M.BasePreprocessedEntityID;
4162 }
4163
4164 return getTotalNumPreprocessedEntities();
4165}
4166
4167namespace {
4168
4169template <unsigned PPEntityOffset::*PPLoc>
4170struct PPEntityComp {
4171 const ASTReader &Reader;
4172 ModuleFile &M;
4173
4174 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4175
4176 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4177 SourceLocation LHS = getLoc(L);
4178 SourceLocation RHS = getLoc(R);
4179 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4180 }
4181
4182 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4183 SourceLocation LHS = getLoc(L);
4184 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4185 }
4186
4187 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4188 SourceLocation RHS = getLoc(R);
4189 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4190 }
4191
4192 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4193 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4194 }
4195};
4196
4197}
4198
4199/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4200PreprocessedEntityID
4201ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4202 if (SourceMgr.isLocalSourceLocation(BLoc))
4203 return getTotalNumPreprocessedEntities();
4204
4205 GlobalSLocOffsetMapType::const_iterator
4206 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004207 BLoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004208 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4209 "Corrupted global sloc offset map");
4210
4211 if (SLocMapI->second->NumPreprocessedEntities == 0)
4212 return findNextPreprocessedEntity(SLocMapI);
4213
4214 ModuleFile &M = *SLocMapI->second;
4215 typedef const PPEntityOffset *pp_iterator;
4216 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4217 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4218
4219 size_t Count = M.NumPreprocessedEntities;
4220 size_t Half;
4221 pp_iterator First = pp_begin;
4222 pp_iterator PPI;
4223
4224 // Do a binary search manually instead of using std::lower_bound because
4225 // The end locations of entities may be unordered (when a macro expansion
4226 // is inside another macro argument), but for this case it is not important
4227 // whether we get the first macro expansion or its containing macro.
4228 while (Count > 0) {
4229 Half = Count/2;
4230 PPI = First;
4231 std::advance(PPI, Half);
4232 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4233 BLoc)){
4234 First = PPI;
4235 ++First;
4236 Count = Count - Half - 1;
4237 } else
4238 Count = Half;
4239 }
4240
4241 if (PPI == pp_end)
4242 return findNextPreprocessedEntity(SLocMapI);
4243
4244 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4245}
4246
4247/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4248PreprocessedEntityID
4249ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4250 if (SourceMgr.isLocalSourceLocation(ELoc))
4251 return getTotalNumPreprocessedEntities();
4252
4253 GlobalSLocOffsetMapType::const_iterator
4254 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00004255 ELoc.getOffset() - 1);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004256 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4257 "Corrupted global sloc offset map");
4258
4259 if (SLocMapI->second->NumPreprocessedEntities == 0)
4260 return findNextPreprocessedEntity(SLocMapI);
4261
4262 ModuleFile &M = *SLocMapI->second;
4263 typedef const PPEntityOffset *pp_iterator;
4264 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4265 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4266 pp_iterator PPI =
4267 std::upper_bound(pp_begin, pp_end, ELoc,
4268 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4269
4270 if (PPI == pp_end)
4271 return findNextPreprocessedEntity(SLocMapI);
4272
4273 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4274}
4275
4276/// \brief Returns a pair of [Begin, End) indices of preallocated
4277/// preprocessed entities that \arg Range encompasses.
4278std::pair<unsigned, unsigned>
4279 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4280 if (Range.isInvalid())
4281 return std::make_pair(0,0);
4282 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4283
4284 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4285 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4286 return std::make_pair(BeginID, EndID);
4287}
4288
4289/// \brief Optionally returns true or false if the preallocated preprocessed
4290/// entity with index \arg Index came from file \arg FID.
David Blaikiedc84cd52013-02-20 22:23:23 +00004291Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004292 FileID FID) {
4293 if (FID.isInvalid())
4294 return false;
4295
4296 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4297 ModuleFile &M = *PPInfo.first;
4298 unsigned LocalIndex = PPInfo.second;
4299 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4300
4301 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4302 if (Loc.isInvalid())
4303 return false;
4304
4305 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4306 return true;
4307 else
4308 return false;
4309}
4310
4311namespace {
4312 /// \brief Visitor used to search for information about a header file.
4313 class HeaderFileInfoVisitor {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004314 const FileEntry *FE;
4315
David Blaikiedc84cd52013-02-20 22:23:23 +00004316 Optional<HeaderFileInfo> HFI;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004317
4318 public:
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004319 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4320 : FE(FE) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004321
4322 static bool visit(ModuleFile &M, void *UserData) {
4323 HeaderFileInfoVisitor *This
4324 = static_cast<HeaderFileInfoVisitor *>(UserData);
4325
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004326 HeaderFileInfoLookupTable *Table
4327 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4328 if (!Table)
4329 return false;
4330
4331 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidised3802e2013-03-06 18:12:47 +00004332 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004333 if (Pos == Table->end())
4334 return false;
4335
4336 This->HFI = *Pos;
4337 return true;
4338 }
4339
David Blaikiedc84cd52013-02-20 22:23:23 +00004340 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004341 };
4342}
4343
4344HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis36592b12013-03-06 18:12:44 +00004345 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004346 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
David Blaikiedc84cd52013-02-20 22:23:23 +00004347 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004348 if (Listener)
4349 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4350 return *HFI;
4351 }
4352
4353 return HeaderFileInfo();
4354}
4355
4356void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4357 // FIXME: Make it work properly with modules.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004358 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004359 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4360 ModuleFile &F = *(*I);
4361 unsigned Idx = 0;
4362 DiagStates.clear();
4363 assert(!Diag.DiagStates.empty());
4364 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4365 while (Idx < F.PragmaDiagMappings.size()) {
4366 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4367 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4368 if (DiagStateID != 0) {
4369 Diag.DiagStatePoints.push_back(
4370 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4371 FullSourceLoc(Loc, SourceMgr)));
4372 continue;
4373 }
4374
4375 assert(DiagStateID == 0);
4376 // A new DiagState was created here.
4377 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4378 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4379 DiagStates.push_back(NewState);
4380 Diag.DiagStatePoints.push_back(
4381 DiagnosticsEngine::DiagStatePoint(NewState,
4382 FullSourceLoc(Loc, SourceMgr)));
4383 while (1) {
4384 assert(Idx < F.PragmaDiagMappings.size() &&
4385 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4386 if (Idx >= F.PragmaDiagMappings.size()) {
4387 break; // Something is messed up but at least avoid infinite loop in
4388 // release build.
4389 }
4390 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4391 if (DiagID == (unsigned)-1) {
4392 break; // no more diag/map pairs for this location.
4393 }
4394 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4395 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4396 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4397 }
4398 }
4399 }
4400}
4401
4402/// \brief Get the correct cursor and offset for loading a type.
4403ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4404 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4405 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4406 ModuleFile *M = I->second;
4407 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4408}
4409
4410/// \brief Read and return the type with the given index..
4411///
4412/// The index is the type ID, shifted and minus the number of predefs. This
4413/// routine actually reads the record corresponding to the type at the given
4414/// location. It is a helper routine for GetType, which deals with reading type
4415/// IDs.
4416QualType ASTReader::readTypeRecord(unsigned Index) {
4417 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00004418 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004419
4420 // Keep track of where we are in the stream, then jump back there
4421 // after reading this type.
4422 SavedStreamPosition SavedPosition(DeclsCursor);
4423
4424 ReadingKindTracker ReadingKind(Read_Type, *this);
4425
4426 // Note that we are loading a type record.
4427 Deserializing AType(this);
4428
4429 unsigned Idx = 0;
4430 DeclsCursor.JumpToBit(Loc.Offset);
4431 RecordData Record;
4432 unsigned Code = DeclsCursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00004433 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004434 case TYPE_EXT_QUAL: {
4435 if (Record.size() != 2) {
4436 Error("Incorrect encoding of extended qualifier type");
4437 return QualType();
4438 }
4439 QualType Base = readType(*Loc.F, Record, Idx);
4440 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4441 return Context.getQualifiedType(Base, Quals);
4442 }
4443
4444 case TYPE_COMPLEX: {
4445 if (Record.size() != 1) {
4446 Error("Incorrect encoding of complex type");
4447 return QualType();
4448 }
4449 QualType ElemType = readType(*Loc.F, Record, Idx);
4450 return Context.getComplexType(ElemType);
4451 }
4452
4453 case TYPE_POINTER: {
4454 if (Record.size() != 1) {
4455 Error("Incorrect encoding of pointer type");
4456 return QualType();
4457 }
4458 QualType PointeeType = readType(*Loc.F, Record, Idx);
4459 return Context.getPointerType(PointeeType);
4460 }
4461
4462 case TYPE_BLOCK_POINTER: {
4463 if (Record.size() != 1) {
4464 Error("Incorrect encoding of block pointer type");
4465 return QualType();
4466 }
4467 QualType PointeeType = readType(*Loc.F, Record, Idx);
4468 return Context.getBlockPointerType(PointeeType);
4469 }
4470
4471 case TYPE_LVALUE_REFERENCE: {
4472 if (Record.size() != 2) {
4473 Error("Incorrect encoding of lvalue reference type");
4474 return QualType();
4475 }
4476 QualType PointeeType = readType(*Loc.F, Record, Idx);
4477 return Context.getLValueReferenceType(PointeeType, Record[1]);
4478 }
4479
4480 case TYPE_RVALUE_REFERENCE: {
4481 if (Record.size() != 1) {
4482 Error("Incorrect encoding of rvalue reference type");
4483 return QualType();
4484 }
4485 QualType PointeeType = readType(*Loc.F, Record, Idx);
4486 return Context.getRValueReferenceType(PointeeType);
4487 }
4488
4489 case TYPE_MEMBER_POINTER: {
4490 if (Record.size() != 2) {
4491 Error("Incorrect encoding of member pointer type");
4492 return QualType();
4493 }
4494 QualType PointeeType = readType(*Loc.F, Record, Idx);
4495 QualType ClassType = readType(*Loc.F, Record, Idx);
4496 if (PointeeType.isNull() || ClassType.isNull())
4497 return QualType();
4498
4499 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4500 }
4501
4502 case TYPE_CONSTANT_ARRAY: {
4503 QualType ElementType = readType(*Loc.F, Record, Idx);
4504 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4505 unsigned IndexTypeQuals = Record[2];
4506 unsigned Idx = 3;
4507 llvm::APInt Size = ReadAPInt(Record, Idx);
4508 return Context.getConstantArrayType(ElementType, Size,
4509 ASM, IndexTypeQuals);
4510 }
4511
4512 case TYPE_INCOMPLETE_ARRAY: {
4513 QualType ElementType = readType(*Loc.F, Record, Idx);
4514 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4515 unsigned IndexTypeQuals = Record[2];
4516 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4517 }
4518
4519 case TYPE_VARIABLE_ARRAY: {
4520 QualType ElementType = readType(*Loc.F, Record, Idx);
4521 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4522 unsigned IndexTypeQuals = Record[2];
4523 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4524 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4525 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4526 ASM, IndexTypeQuals,
4527 SourceRange(LBLoc, RBLoc));
4528 }
4529
4530 case TYPE_VECTOR: {
4531 if (Record.size() != 3) {
4532 Error("incorrect encoding of vector type in AST file");
4533 return QualType();
4534 }
4535
4536 QualType ElementType = readType(*Loc.F, Record, Idx);
4537 unsigned NumElements = Record[1];
4538 unsigned VecKind = Record[2];
4539 return Context.getVectorType(ElementType, NumElements,
4540 (VectorType::VectorKind)VecKind);
4541 }
4542
4543 case TYPE_EXT_VECTOR: {
4544 if (Record.size() != 3) {
4545 Error("incorrect encoding of extended vector type in AST file");
4546 return QualType();
4547 }
4548
4549 QualType ElementType = readType(*Loc.F, Record, Idx);
4550 unsigned NumElements = Record[1];
4551 return Context.getExtVectorType(ElementType, NumElements);
4552 }
4553
4554 case TYPE_FUNCTION_NO_PROTO: {
4555 if (Record.size() != 6) {
4556 Error("incorrect encoding of no-proto function type");
4557 return QualType();
4558 }
4559 QualType ResultType = readType(*Loc.F, Record, Idx);
4560 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4561 (CallingConv)Record[4], Record[5]);
4562 return Context.getFunctionNoProtoType(ResultType, Info);
4563 }
4564
4565 case TYPE_FUNCTION_PROTO: {
4566 QualType ResultType = readType(*Loc.F, Record, Idx);
4567
4568 FunctionProtoType::ExtProtoInfo EPI;
4569 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4570 /*hasregparm*/ Record[2],
4571 /*regparm*/ Record[3],
4572 static_cast<CallingConv>(Record[4]),
4573 /*produces*/ Record[5]);
4574
4575 unsigned Idx = 6;
4576 unsigned NumParams = Record[Idx++];
4577 SmallVector<QualType, 16> ParamTypes;
4578 for (unsigned I = 0; I != NumParams; ++I)
4579 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4580
4581 EPI.Variadic = Record[Idx++];
4582 EPI.HasTrailingReturn = Record[Idx++];
4583 EPI.TypeQuals = Record[Idx++];
4584 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4585 ExceptionSpecificationType EST =
4586 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4587 EPI.ExceptionSpecType = EST;
4588 SmallVector<QualType, 2> Exceptions;
4589 if (EST == EST_Dynamic) {
4590 EPI.NumExceptions = Record[Idx++];
4591 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4592 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4593 EPI.Exceptions = Exceptions.data();
4594 } else if (EST == EST_ComputedNoexcept) {
4595 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4596 } else if (EST == EST_Uninstantiated) {
4597 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4598 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4599 } else if (EST == EST_Unevaluated) {
4600 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4601 }
Jordan Rosebea522f2013-03-08 21:51:21 +00004602 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004603 }
4604
4605 case TYPE_UNRESOLVED_USING: {
4606 unsigned Idx = 0;
4607 return Context.getTypeDeclType(
4608 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4609 }
4610
4611 case TYPE_TYPEDEF: {
4612 if (Record.size() != 2) {
4613 Error("incorrect encoding of typedef type");
4614 return QualType();
4615 }
4616 unsigned Idx = 0;
4617 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4618 QualType Canonical = readType(*Loc.F, Record, Idx);
4619 if (!Canonical.isNull())
4620 Canonical = Context.getCanonicalType(Canonical);
4621 return Context.getTypedefType(Decl, Canonical);
4622 }
4623
4624 case TYPE_TYPEOF_EXPR:
4625 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4626
4627 case TYPE_TYPEOF: {
4628 if (Record.size() != 1) {
4629 Error("incorrect encoding of typeof(type) in AST file");
4630 return QualType();
4631 }
4632 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4633 return Context.getTypeOfType(UnderlyingType);
4634 }
4635
4636 case TYPE_DECLTYPE: {
4637 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4638 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4639 }
4640
4641 case TYPE_UNARY_TRANSFORM: {
4642 QualType BaseType = readType(*Loc.F, Record, Idx);
4643 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4644 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4645 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4646 }
4647
Richard Smitha2c36462013-04-26 16:15:35 +00004648 case TYPE_AUTO: {
4649 QualType Deduced = readType(*Loc.F, Record, Idx);
4650 bool IsDecltypeAuto = Record[Idx++];
Richard Smithdc7a4f52013-04-30 13:56:41 +00004651 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
4652 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smitha2c36462013-04-26 16:15:35 +00004653 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004654
4655 case TYPE_RECORD: {
4656 if (Record.size() != 2) {
4657 Error("incorrect encoding of record type");
4658 return QualType();
4659 }
4660 unsigned Idx = 0;
4661 bool IsDependent = Record[Idx++];
4662 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4663 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4664 QualType T = Context.getRecordType(RD);
4665 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4666 return T;
4667 }
4668
4669 case TYPE_ENUM: {
4670 if (Record.size() != 2) {
4671 Error("incorrect encoding of enum type");
4672 return QualType();
4673 }
4674 unsigned Idx = 0;
4675 bool IsDependent = Record[Idx++];
4676 QualType T
4677 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4678 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4679 return T;
4680 }
4681
4682 case TYPE_ATTRIBUTED: {
4683 if (Record.size() != 3) {
4684 Error("incorrect encoding of attributed type");
4685 return QualType();
4686 }
4687 QualType modifiedType = readType(*Loc.F, Record, Idx);
4688 QualType equivalentType = readType(*Loc.F, Record, Idx);
4689 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4690 return Context.getAttributedType(kind, modifiedType, equivalentType);
4691 }
4692
4693 case TYPE_PAREN: {
4694 if (Record.size() != 1) {
4695 Error("incorrect encoding of paren type");
4696 return QualType();
4697 }
4698 QualType InnerType = readType(*Loc.F, Record, Idx);
4699 return Context.getParenType(InnerType);
4700 }
4701
4702 case TYPE_PACK_EXPANSION: {
4703 if (Record.size() != 2) {
4704 Error("incorrect encoding of pack expansion type");
4705 return QualType();
4706 }
4707 QualType Pattern = readType(*Loc.F, Record, Idx);
4708 if (Pattern.isNull())
4709 return QualType();
David Blaikiedc84cd52013-02-20 22:23:23 +00004710 Optional<unsigned> NumExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00004711 if (Record[1])
4712 NumExpansions = Record[1] - 1;
4713 return Context.getPackExpansionType(Pattern, NumExpansions);
4714 }
4715
4716 case TYPE_ELABORATED: {
4717 unsigned Idx = 0;
4718 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4719 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4720 QualType NamedType = readType(*Loc.F, Record, Idx);
4721 return Context.getElaboratedType(Keyword, NNS, NamedType);
4722 }
4723
4724 case TYPE_OBJC_INTERFACE: {
4725 unsigned Idx = 0;
4726 ObjCInterfaceDecl *ItfD
4727 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4728 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4729 }
4730
4731 case TYPE_OBJC_OBJECT: {
4732 unsigned Idx = 0;
4733 QualType Base = readType(*Loc.F, Record, Idx);
4734 unsigned NumProtos = Record[Idx++];
4735 SmallVector<ObjCProtocolDecl*, 4> Protos;
4736 for (unsigned I = 0; I != NumProtos; ++I)
4737 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4738 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4739 }
4740
4741 case TYPE_OBJC_OBJECT_POINTER: {
4742 unsigned Idx = 0;
4743 QualType Pointee = readType(*Loc.F, Record, Idx);
4744 return Context.getObjCObjectPointerType(Pointee);
4745 }
4746
4747 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4748 unsigned Idx = 0;
4749 QualType Parm = readType(*Loc.F, Record, Idx);
4750 QualType Replacement = readType(*Loc.F, Record, Idx);
4751 return
4752 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4753 Replacement);
4754 }
4755
4756 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4757 unsigned Idx = 0;
4758 QualType Parm = readType(*Loc.F, Record, Idx);
4759 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4760 return Context.getSubstTemplateTypeParmPackType(
4761 cast<TemplateTypeParmType>(Parm),
4762 ArgPack);
4763 }
4764
4765 case TYPE_INJECTED_CLASS_NAME: {
4766 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4767 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4768 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4769 // for AST reading, too much interdependencies.
4770 return
4771 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4772 }
4773
4774 case TYPE_TEMPLATE_TYPE_PARM: {
4775 unsigned Idx = 0;
4776 unsigned Depth = Record[Idx++];
4777 unsigned Index = Record[Idx++];
4778 bool Pack = Record[Idx++];
4779 TemplateTypeParmDecl *D
4780 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4781 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4782 }
4783
4784 case TYPE_DEPENDENT_NAME: {
4785 unsigned Idx = 0;
4786 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4787 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4788 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4789 QualType Canon = readType(*Loc.F, Record, Idx);
4790 if (!Canon.isNull())
4791 Canon = Context.getCanonicalType(Canon);
4792 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4793 }
4794
4795 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4796 unsigned Idx = 0;
4797 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4798 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4799 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4800 unsigned NumArgs = Record[Idx++];
4801 SmallVector<TemplateArgument, 8> Args;
4802 Args.reserve(NumArgs);
4803 while (NumArgs--)
4804 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4805 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4806 Args.size(), Args.data());
4807 }
4808
4809 case TYPE_DEPENDENT_SIZED_ARRAY: {
4810 unsigned Idx = 0;
4811
4812 // ArrayType
4813 QualType ElementType = readType(*Loc.F, Record, Idx);
4814 ArrayType::ArraySizeModifier ASM
4815 = (ArrayType::ArraySizeModifier)Record[Idx++];
4816 unsigned IndexTypeQuals = Record[Idx++];
4817
4818 // DependentSizedArrayType
4819 Expr *NumElts = ReadExpr(*Loc.F);
4820 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4821
4822 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4823 IndexTypeQuals, Brackets);
4824 }
4825
4826 case TYPE_TEMPLATE_SPECIALIZATION: {
4827 unsigned Idx = 0;
4828 bool IsDependent = Record[Idx++];
4829 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4830 SmallVector<TemplateArgument, 8> Args;
4831 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4832 QualType Underlying = readType(*Loc.F, Record, Idx);
4833 QualType T;
4834 if (Underlying.isNull())
4835 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4836 Args.size());
4837 else
4838 T = Context.getTemplateSpecializationType(Name, Args.data(),
4839 Args.size(), Underlying);
4840 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4841 return T;
4842 }
4843
4844 case TYPE_ATOMIC: {
4845 if (Record.size() != 1) {
4846 Error("Incorrect encoding of atomic type");
4847 return QualType();
4848 }
4849 QualType ValueType = readType(*Loc.F, Record, Idx);
4850 return Context.getAtomicType(ValueType);
4851 }
4852 }
4853 llvm_unreachable("Invalid TypeCode!");
4854}
4855
4856class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4857 ASTReader &Reader;
4858 ModuleFile &F;
4859 const ASTReader::RecordData &Record;
4860 unsigned &Idx;
4861
4862 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4863 unsigned &I) {
4864 return Reader.ReadSourceLocation(F, R, I);
4865 }
4866
4867 template<typename T>
4868 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4869 return Reader.ReadDeclAs<T>(F, Record, Idx);
4870 }
4871
4872public:
4873 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4874 const ASTReader::RecordData &Record, unsigned &Idx)
4875 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4876 { }
4877
4878 // We want compile-time assurance that we've enumerated all of
4879 // these, so unfortunately we have to declare them first, then
4880 // define them out-of-line.
4881#define ABSTRACT_TYPELOC(CLASS, PARENT)
4882#define TYPELOC(CLASS, PARENT) \
4883 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4884#include "clang/AST/TypeLocNodes.def"
4885
4886 void VisitFunctionTypeLoc(FunctionTypeLoc);
4887 void VisitArrayTypeLoc(ArrayTypeLoc);
4888};
4889
4890void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4891 // nothing to do
4892}
4893void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4894 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4895 if (TL.needsExtraLocalData()) {
4896 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4897 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4898 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4899 TL.setModeAttr(Record[Idx++]);
4900 }
4901}
4902void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
4903 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4904}
4905void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
4906 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4907}
4908void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4909 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
4910}
4911void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4912 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
4913}
4914void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4915 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
4916}
4917void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4918 TL.setStarLoc(ReadSourceLocation(Record, Idx));
4919 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4920}
4921void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
4922 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4923 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
4924 if (Record[Idx++])
4925 TL.setSizeExpr(Reader.ReadExpr(F));
4926 else
4927 TL.setSizeExpr(0);
4928}
4929void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4930 VisitArrayTypeLoc(TL);
4931}
4932void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4933 VisitArrayTypeLoc(TL);
4934}
4935void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4936 VisitArrayTypeLoc(TL);
4937}
4938void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4939 DependentSizedArrayTypeLoc TL) {
4940 VisitArrayTypeLoc(TL);
4941}
4942void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4943 DependentSizedExtVectorTypeLoc TL) {
4944 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4945}
4946void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
4947 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4948}
4949void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
4950 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4951}
4952void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4953 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
4954 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4955 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4956 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
4957 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
4958 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
4959 }
4960}
4961void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
4962 VisitFunctionTypeLoc(TL);
4963}
4964void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
4965 VisitFunctionTypeLoc(TL);
4966}
4967void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
4968 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4969}
4970void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4971 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4972}
4973void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4974 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4975 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4976 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4977}
4978void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4979 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
4980 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4981 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4982 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4983}
4984void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
4985 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4986}
4987void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4988 TL.setKWLoc(ReadSourceLocation(Record, Idx));
4989 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
4990 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
4991 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
4992}
4993void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
4994 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4995}
4996void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
4997 TL.setNameLoc(ReadSourceLocation(Record, Idx));
4998}
4999void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5000 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5001}
5002void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5003 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5004 if (TL.hasAttrOperand()) {
5005 SourceRange range;
5006 range.setBegin(ReadSourceLocation(Record, Idx));
5007 range.setEnd(ReadSourceLocation(Record, Idx));
5008 TL.setAttrOperandParensRange(range);
5009 }
5010 if (TL.hasAttrExprOperand()) {
5011 if (Record[Idx++])
5012 TL.setAttrExprOperand(Reader.ReadExpr(F));
5013 else
5014 TL.setAttrExprOperand(0);
5015 } else if (TL.hasAttrEnumOperand())
5016 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5017}
5018void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5019 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5020}
5021void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5022 SubstTemplateTypeParmTypeLoc TL) {
5023 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5024}
5025void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5026 SubstTemplateTypeParmPackTypeLoc TL) {
5027 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5028}
5029void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5030 TemplateSpecializationTypeLoc TL) {
5031 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5032 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5033 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5034 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5035 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5036 TL.setArgLocInfo(i,
5037 Reader.GetTemplateArgumentLocInfo(F,
5038 TL.getTypePtr()->getArg(i).getKind(),
5039 Record, Idx));
5040}
5041void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5042 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5043 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5044}
5045void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5046 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5047 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5048}
5049void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5050 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5051}
5052void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5053 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5054 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5055 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5056}
5057void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5058 DependentTemplateSpecializationTypeLoc TL) {
5059 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5060 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5061 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5062 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5063 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5064 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5065 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5066 TL.setArgLocInfo(I,
5067 Reader.GetTemplateArgumentLocInfo(F,
5068 TL.getTypePtr()->getArg(I).getKind(),
5069 Record, Idx));
5070}
5071void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5072 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5073}
5074void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5075 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5076}
5077void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5078 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5079 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5080 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5081 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5082 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5083}
5084void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5085 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5086}
5087void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5088 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5089 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5090 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5091}
5092
5093TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5094 const RecordData &Record,
5095 unsigned &Idx) {
5096 QualType InfoTy = readType(F, Record, Idx);
5097 if (InfoTy.isNull())
5098 return 0;
5099
5100 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5101 TypeLocReader TLR(*this, F, Record, Idx);
5102 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5103 TLR.Visit(TL);
5104 return TInfo;
5105}
5106
5107QualType ASTReader::GetType(TypeID ID) {
5108 unsigned FastQuals = ID & Qualifiers::FastMask;
5109 unsigned Index = ID >> Qualifiers::FastWidth;
5110
5111 if (Index < NUM_PREDEF_TYPE_IDS) {
5112 QualType T;
5113 switch ((PredefinedTypeIDs)Index) {
5114 case PREDEF_TYPE_NULL_ID: return QualType();
5115 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5116 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5117
5118 case PREDEF_TYPE_CHAR_U_ID:
5119 case PREDEF_TYPE_CHAR_S_ID:
5120 // FIXME: Check that the signedness of CharTy is correct!
5121 T = Context.CharTy;
5122 break;
5123
5124 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5125 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5126 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5127 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5128 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5129 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5130 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5131 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5132 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5133 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5134 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5135 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5136 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5137 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5138 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5139 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5140 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5141 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5142 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5143 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5144 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5145 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5146 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5147 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5148 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5149 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5150 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5151 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00005152 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5153 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5154 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5155 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5156 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5157 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00005158 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00005159 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005160 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5161
5162 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5163 T = Context.getAutoRRefDeductType();
5164 break;
5165
5166 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5167 T = Context.ARCUnbridgedCastTy;
5168 break;
5169
5170 case PREDEF_TYPE_VA_LIST_TAG:
5171 T = Context.getVaListTagType();
5172 break;
5173
5174 case PREDEF_TYPE_BUILTIN_FN:
5175 T = Context.BuiltinFnTy;
5176 break;
5177 }
5178
5179 assert(!T.isNull() && "Unknown predefined type");
5180 return T.withFastQualifiers(FastQuals);
5181 }
5182
5183 Index -= NUM_PREDEF_TYPE_IDS;
5184 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5185 if (TypesLoaded[Index].isNull()) {
5186 TypesLoaded[Index] = readTypeRecord(Index);
5187 if (TypesLoaded[Index].isNull())
5188 return QualType();
5189
5190 TypesLoaded[Index]->setFromAST();
5191 if (DeserializationListener)
5192 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5193 TypesLoaded[Index]);
5194 }
5195
5196 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5197}
5198
5199QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5200 return GetType(getGlobalTypeID(F, LocalID));
5201}
5202
5203serialization::TypeID
5204ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5205 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5206 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5207
5208 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5209 return LocalID;
5210
5211 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5212 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5213 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5214
5215 unsigned GlobalIndex = LocalIndex + I->second;
5216 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5217}
5218
5219TemplateArgumentLocInfo
5220ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5221 TemplateArgument::ArgKind Kind,
5222 const RecordData &Record,
5223 unsigned &Index) {
5224 switch (Kind) {
5225 case TemplateArgument::Expression:
5226 return ReadExpr(F);
5227 case TemplateArgument::Type:
5228 return GetTypeSourceInfo(F, Record, Index);
5229 case TemplateArgument::Template: {
5230 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5231 Index);
5232 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5233 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5234 SourceLocation());
5235 }
5236 case TemplateArgument::TemplateExpansion: {
5237 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5238 Index);
5239 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5240 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5241 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5242 EllipsisLoc);
5243 }
5244 case TemplateArgument::Null:
5245 case TemplateArgument::Integral:
5246 case TemplateArgument::Declaration:
5247 case TemplateArgument::NullPtr:
5248 case TemplateArgument::Pack:
5249 // FIXME: Is this right?
5250 return TemplateArgumentLocInfo();
5251 }
5252 llvm_unreachable("unexpected template argument loc");
5253}
5254
5255TemplateArgumentLoc
5256ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5257 const RecordData &Record, unsigned &Index) {
5258 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5259
5260 if (Arg.getKind() == TemplateArgument::Expression) {
5261 if (Record[Index++]) // bool InfoHasSameExpr.
5262 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5263 }
5264 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5265 Record, Index));
5266}
5267
5268Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5269 return GetDecl(ID);
5270}
5271
5272uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5273 unsigned &Idx){
5274 if (Idx >= Record.size())
5275 return 0;
5276
5277 unsigned LocalID = Record[Idx++];
5278 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5279}
5280
5281CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5282 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00005283 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005284 SavedStreamPosition SavedPosition(Cursor);
5285 Cursor.JumpToBit(Loc.Offset);
5286 ReadingKindTracker ReadingKind(Read_Decl, *this);
5287 RecordData Record;
5288 unsigned Code = Cursor.ReadCode();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00005289 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005290 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5291 Error("Malformed AST file: missing C++ base specifiers");
5292 return 0;
5293 }
5294
5295 unsigned Idx = 0;
5296 unsigned NumBases = Record[Idx++];
5297 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5298 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5299 for (unsigned I = 0; I != NumBases; ++I)
5300 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5301 return Bases;
5302}
5303
5304serialization::DeclID
5305ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5306 if (LocalID < NUM_PREDEF_DECL_IDS)
5307 return LocalID;
5308
5309 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5310 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5311 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5312
5313 return LocalID + I->second;
5314}
5315
5316bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5317 ModuleFile &M) const {
5318 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5319 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5320 return &M == I->second;
5321}
5322
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005323ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005324 if (!D->isFromASTFile())
5325 return 0;
5326 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5327 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5328 return I->second;
5329}
5330
5331SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5332 if (ID < NUM_PREDEF_DECL_IDS)
5333 return SourceLocation();
5334
5335 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5336
5337 if (Index > DeclsLoaded.size()) {
5338 Error("declaration ID out-of-range for AST file");
5339 return SourceLocation();
5340 }
5341
5342 if (Decl *D = DeclsLoaded[Index])
5343 return D->getLocation();
5344
5345 unsigned RawLocation = 0;
5346 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5347 return ReadSourceLocation(*Rec.F, RawLocation);
5348}
5349
5350Decl *ASTReader::GetDecl(DeclID ID) {
5351 if (ID < NUM_PREDEF_DECL_IDS) {
5352 switch ((PredefinedDeclIDs)ID) {
5353 case PREDEF_DECL_NULL_ID:
5354 return 0;
5355
5356 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5357 return Context.getTranslationUnitDecl();
5358
5359 case PREDEF_DECL_OBJC_ID_ID:
5360 return Context.getObjCIdDecl();
5361
5362 case PREDEF_DECL_OBJC_SEL_ID:
5363 return Context.getObjCSelDecl();
5364
5365 case PREDEF_DECL_OBJC_CLASS_ID:
5366 return Context.getObjCClassDecl();
5367
5368 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5369 return Context.getObjCProtocolDecl();
5370
5371 case PREDEF_DECL_INT_128_ID:
5372 return Context.getInt128Decl();
5373
5374 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5375 return Context.getUInt128Decl();
5376
5377 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5378 return Context.getObjCInstanceTypeDecl();
5379
5380 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5381 return Context.getBuiltinVaListDecl();
5382 }
5383 }
5384
5385 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5386
5387 if (Index >= DeclsLoaded.size()) {
5388 assert(0 && "declaration ID out-of-range for AST file");
5389 Error("declaration ID out-of-range for AST file");
5390 return 0;
5391 }
5392
5393 if (!DeclsLoaded[Index]) {
5394 ReadDeclRecord(ID);
5395 if (DeserializationListener)
5396 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5397 }
5398
5399 return DeclsLoaded[Index];
5400}
5401
5402DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5403 DeclID GlobalID) {
5404 if (GlobalID < NUM_PREDEF_DECL_IDS)
5405 return GlobalID;
5406
5407 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5408 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5409 ModuleFile *Owner = I->second;
5410
5411 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5412 = M.GlobalToLocalDeclIDs.find(Owner);
5413 if (Pos == M.GlobalToLocalDeclIDs.end())
5414 return 0;
5415
5416 return GlobalID - Owner->BaseDeclID + Pos->second;
5417}
5418
5419serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5420 const RecordData &Record,
5421 unsigned &Idx) {
5422 if (Idx >= Record.size()) {
5423 Error("Corrupted AST file");
5424 return 0;
5425 }
5426
5427 return getGlobalDeclID(F, Record[Idx++]);
5428}
5429
5430/// \brief Resolve the offset of a statement into a statement.
5431///
5432/// This operation will read a new statement from the external
5433/// source each time it is called, and is meant to be used via a
5434/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5435Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5436 // Switch case IDs are per Decl.
5437 ClearSwitchCaseIDs();
5438
5439 // Offset here is a global offset across the entire chain.
5440 RecordLocation Loc = getLocalBitOffset(Offset);
5441 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5442 return ReadStmtFromStream(*Loc.F);
5443}
5444
5445namespace {
5446 class FindExternalLexicalDeclsVisitor {
5447 ASTReader &Reader;
5448 const DeclContext *DC;
5449 bool (*isKindWeWant)(Decl::Kind);
5450
5451 SmallVectorImpl<Decl*> &Decls;
5452 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5453
5454 public:
5455 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5456 bool (*isKindWeWant)(Decl::Kind),
5457 SmallVectorImpl<Decl*> &Decls)
5458 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5459 {
5460 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5461 PredefsVisited[I] = false;
5462 }
5463
5464 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5465 if (Preorder)
5466 return false;
5467
5468 FindExternalLexicalDeclsVisitor *This
5469 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5470
5471 ModuleFile::DeclContextInfosMap::iterator Info
5472 = M.DeclContextInfos.find(This->DC);
5473 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5474 return false;
5475
5476 // Load all of the declaration IDs
5477 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5478 *IDE = ID + Info->second.NumLexicalDecls;
5479 ID != IDE; ++ID) {
5480 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5481 continue;
5482
5483 // Don't add predefined declarations to the lexical context more
5484 // than once.
5485 if (ID->second < NUM_PREDEF_DECL_IDS) {
5486 if (This->PredefsVisited[ID->second])
5487 continue;
5488
5489 This->PredefsVisited[ID->second] = true;
5490 }
5491
5492 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5493 if (!This->DC->isDeclInLexicalTraversal(D))
5494 This->Decls.push_back(D);
5495 }
5496 }
5497
5498 return false;
5499 }
5500 };
5501}
5502
5503ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5504 bool (*isKindWeWant)(Decl::Kind),
5505 SmallVectorImpl<Decl*> &Decls) {
5506 // There might be lexical decls in multiple modules, for the TU at
5507 // least. Walk all of the modules in the order they were loaded.
5508 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5509 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5510 ++NumLexicalDeclContextsRead;
5511 return ELR_Success;
5512}
5513
5514namespace {
5515
5516class DeclIDComp {
5517 ASTReader &Reader;
5518 ModuleFile &Mod;
5519
5520public:
5521 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5522
5523 bool operator()(LocalDeclID L, LocalDeclID R) const {
5524 SourceLocation LHS = getLocation(L);
5525 SourceLocation RHS = getLocation(R);
5526 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5527 }
5528
5529 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5530 SourceLocation RHS = getLocation(R);
5531 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5532 }
5533
5534 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5535 SourceLocation LHS = getLocation(L);
5536 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5537 }
5538
5539 SourceLocation getLocation(LocalDeclID ID) const {
5540 return Reader.getSourceManager().getFileLoc(
5541 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5542 }
5543};
5544
5545}
5546
5547void ASTReader::FindFileRegionDecls(FileID File,
5548 unsigned Offset, unsigned Length,
5549 SmallVectorImpl<Decl *> &Decls) {
5550 SourceManager &SM = getSourceManager();
5551
5552 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5553 if (I == FileDeclIDs.end())
5554 return;
5555
5556 FileDeclsInfo &DInfo = I->second;
5557 if (DInfo.Decls.empty())
5558 return;
5559
5560 SourceLocation
5561 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5562 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5563
5564 DeclIDComp DIDComp(*this, *DInfo.Mod);
5565 ArrayRef<serialization::LocalDeclID>::iterator
5566 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5567 BeginLoc, DIDComp);
5568 if (BeginIt != DInfo.Decls.begin())
5569 --BeginIt;
5570
5571 // If we are pointing at a top-level decl inside an objc container, we need
5572 // to backtrack until we find it otherwise we will fail to report that the
5573 // region overlaps with an objc container.
5574 while (BeginIt != DInfo.Decls.begin() &&
5575 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5576 ->isTopLevelDeclInObjCContainer())
5577 --BeginIt;
5578
5579 ArrayRef<serialization::LocalDeclID>::iterator
5580 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5581 EndLoc, DIDComp);
5582 if (EndIt != DInfo.Decls.end())
5583 ++EndIt;
5584
5585 for (ArrayRef<serialization::LocalDeclID>::iterator
5586 DIt = BeginIt; DIt != EndIt; ++DIt)
5587 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5588}
5589
5590namespace {
5591 /// \brief ModuleFile visitor used to perform name lookup into a
5592 /// declaration context.
5593 class DeclContextNameLookupVisitor {
5594 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005595 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005596 DeclarationName Name;
5597 SmallVectorImpl<NamedDecl *> &Decls;
5598
5599 public:
5600 DeclContextNameLookupVisitor(ASTReader &Reader,
5601 SmallVectorImpl<const DeclContext *> &Contexts,
5602 DeclarationName Name,
5603 SmallVectorImpl<NamedDecl *> &Decls)
5604 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5605
5606 static bool visit(ModuleFile &M, void *UserData) {
5607 DeclContextNameLookupVisitor *This
5608 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5609
5610 // Check whether we have any visible declaration information for
5611 // this context in this module.
5612 ModuleFile::DeclContextInfosMap::iterator Info;
5613 bool FoundInfo = false;
5614 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5615 Info = M.DeclContextInfos.find(This->Contexts[I]);
5616 if (Info != M.DeclContextInfos.end() &&
5617 Info->second.NameLookupTableData) {
5618 FoundInfo = true;
5619 break;
5620 }
5621 }
5622
5623 if (!FoundInfo)
5624 return false;
5625
5626 // Look for this name within this module.
5627 ASTDeclContextNameLookupTable *LookupTable =
5628 Info->second.NameLookupTableData;
5629 ASTDeclContextNameLookupTable::iterator Pos
5630 = LookupTable->find(This->Name);
5631 if (Pos == LookupTable->end())
5632 return false;
5633
5634 bool FoundAnything = false;
5635 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5636 for (; Data.first != Data.second; ++Data.first) {
5637 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5638 if (!ND)
5639 continue;
5640
5641 if (ND->getDeclName() != This->Name) {
5642 // A name might be null because the decl's redeclarable part is
5643 // currently read before reading its name. The lookup is triggered by
5644 // building that decl (likely indirectly), and so it is later in the
5645 // sense of "already existing" and can be ignored here.
5646 continue;
5647 }
5648
5649 // Record this declaration.
5650 FoundAnything = true;
5651 This->Decls.push_back(ND);
5652 }
5653
5654 return FoundAnything;
5655 }
5656 };
5657}
5658
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005659/// \brief Retrieve the "definitive" module file for the definition of the
5660/// given declaration context, if there is one.
5661///
5662/// The "definitive" module file is the only place where we need to look to
5663/// find information about the declarations within the given declaration
5664/// context. For example, C++ and Objective-C classes, C structs/unions, and
5665/// Objective-C protocols, categories, and extensions are all defined in a
5666/// single place in the source code, so they have definitive module files
5667/// associated with them. C++ namespaces, on the other hand, can have
5668/// definitions in multiple different module files.
5669///
5670/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5671/// NDEBUG checking.
5672static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5673 ASTReader &Reader) {
Douglas Gregore0d20662013-01-22 17:08:30 +00005674 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5675 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005676
5677 return 0;
5678}
5679
Richard Smith3646c682013-02-07 03:30:24 +00005680bool
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005681ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5682 DeclarationName Name) {
5683 assert(DC->hasExternalVisibleStorage() &&
5684 "DeclContext has no visible decls in storage");
5685 if (!Name)
Richard Smith3646c682013-02-07 03:30:24 +00005686 return false;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005687
5688 SmallVector<NamedDecl *, 64> Decls;
5689
5690 // Compute the declaration contexts we need to look into. Multiple such
5691 // declaration contexts occur when two declaration contexts from disjoint
5692 // modules get merged, e.g., when two namespaces with the same name are
5693 // independently defined in separate modules.
5694 SmallVector<const DeclContext *, 2> Contexts;
5695 Contexts.push_back(DC);
5696
5697 if (DC->isNamespace()) {
5698 MergedDeclsMap::iterator Merged
5699 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5700 if (Merged != MergedDecls.end()) {
5701 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5702 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5703 }
5704 }
5705
5706 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor5a04f9f2013-01-21 15:25:38 +00005707
5708 // If we can definitively determine which module file to look into,
5709 // only look there. Otherwise, look in all module files.
5710 ModuleFile *Definitive;
5711 if (Contexts.size() == 1 &&
5712 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5713 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5714 } else {
5715 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5716 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005717 ++NumVisibleDeclContextsRead;
5718 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith3646c682013-02-07 03:30:24 +00005719 return !Decls.empty();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005720}
5721
5722namespace {
5723 /// \brief ModuleFile visitor used to retrieve all visible names in a
5724 /// declaration context.
5725 class DeclContextAllNamesVisitor {
5726 ASTReader &Reader;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005727 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005728 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005729 bool VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005730
5731 public:
5732 DeclContextAllNamesVisitor(ASTReader &Reader,
5733 SmallVectorImpl<const DeclContext *> &Contexts,
5734 llvm::DenseMap<DeclarationName,
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005735 SmallVector<NamedDecl *, 8> > &Decls,
5736 bool VisitAll)
5737 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005738
5739 static bool visit(ModuleFile &M, void *UserData) {
5740 DeclContextAllNamesVisitor *This
5741 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5742
5743 // Check whether we have any visible declaration information for
5744 // this context in this module.
5745 ModuleFile::DeclContextInfosMap::iterator Info;
5746 bool FoundInfo = false;
5747 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5748 Info = M.DeclContextInfos.find(This->Contexts[I]);
5749 if (Info != M.DeclContextInfos.end() &&
5750 Info->second.NameLookupTableData) {
5751 FoundInfo = true;
5752 break;
5753 }
5754 }
5755
5756 if (!FoundInfo)
5757 return false;
5758
5759 ASTDeclContextNameLookupTable *LookupTable =
5760 Info->second.NameLookupTableData;
5761 bool FoundAnything = false;
5762 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregora6b00fc2013-01-23 22:38:11 +00005763 I = LookupTable->data_begin(), E = LookupTable->data_end();
5764 I != E;
5765 ++I) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005766 ASTDeclContextNameLookupTrait::data_type Data = *I;
5767 for (; Data.first != Data.second; ++Data.first) {
5768 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5769 *Data.first);
5770 if (!ND)
5771 continue;
5772
5773 // Record this declaration.
5774 FoundAnything = true;
5775 This->Decls[ND->getDeclName()].push_back(ND);
5776 }
5777 }
5778
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005779 return FoundAnything && !This->VisitAll;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005780 }
5781 };
5782}
5783
5784void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5785 if (!DC->hasExternalVisibleStorage())
5786 return;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005787 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > Decls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005788
5789 // Compute the declaration contexts we need to look into. Multiple such
5790 // declaration contexts occur when two declaration contexts from disjoint
5791 // modules get merged, e.g., when two namespaces with the same name are
5792 // independently defined in separate modules.
5793 SmallVector<const DeclContext *, 2> Contexts;
5794 Contexts.push_back(DC);
5795
5796 if (DC->isNamespace()) {
5797 MergedDeclsMap::iterator Merged
5798 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5799 if (Merged != MergedDecls.end()) {
5800 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5801 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5802 }
5803 }
5804
Argyrios Kyrtzidisca40f302012-12-19 22:21:18 +00005805 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5806 /*VisitAll=*/DC->isFileContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005807 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5808 ++NumVisibleDeclContextsRead;
5809
5810 for (llvm::DenseMap<DeclarationName,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005811 SmallVector<NamedDecl *, 8> >::iterator
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005812 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5813 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5814 }
5815 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5816}
5817
5818/// \brief Under non-PCH compilation the consumer receives the objc methods
5819/// before receiving the implementation, and codegen depends on this.
5820/// We simulate this by deserializing and passing to consumer the methods of the
5821/// implementation before passing the deserialized implementation decl.
5822static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5823 ASTConsumer *Consumer) {
5824 assert(ImplD && Consumer);
5825
5826 for (ObjCImplDecl::method_iterator
5827 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5828 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5829
5830 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5831}
5832
5833void ASTReader::PassInterestingDeclsToConsumer() {
5834 assert(Consumer);
5835 while (!InterestingDecls.empty()) {
5836 Decl *D = InterestingDecls.front();
5837 InterestingDecls.pop_front();
5838
5839 PassInterestingDeclToConsumer(D);
5840 }
5841}
5842
5843void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5844 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5845 PassObjCImplDeclToConsumer(ImplD, Consumer);
5846 else
5847 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5848}
5849
5850void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5851 this->Consumer = Consumer;
5852
5853 if (!Consumer)
5854 return;
5855
5856 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5857 // Force deserialization of this decl, which will cause it to be queued for
5858 // passing to the consumer.
5859 GetDecl(ExternalDefinitions[I]);
5860 }
5861 ExternalDefinitions.clear();
5862
5863 PassInterestingDeclsToConsumer();
5864}
5865
5866void ASTReader::PrintStats() {
5867 std::fprintf(stderr, "*** AST File Statistics:\n");
5868
5869 unsigned NumTypesLoaded
5870 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5871 QualType());
5872 unsigned NumDeclsLoaded
5873 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5874 (Decl *)0);
5875 unsigned NumIdentifiersLoaded
5876 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5877 IdentifiersLoaded.end(),
5878 (IdentifierInfo *)0);
5879 unsigned NumMacrosLoaded
5880 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5881 MacrosLoaded.end(),
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00005882 (MacroInfo *)0);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005883 unsigned NumSelectorsLoaded
5884 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5885 SelectorsLoaded.end(),
5886 Selector());
5887
5888 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5889 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5890 NumSLocEntriesRead, TotalNumSLocEntries,
5891 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5892 if (!TypesLoaded.empty())
5893 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
5894 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5895 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5896 if (!DeclsLoaded.empty())
5897 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
5898 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5899 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5900 if (!IdentifiersLoaded.empty())
5901 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
5902 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5903 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5904 if (!MacrosLoaded.empty())
5905 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5906 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5907 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5908 if (!SelectorsLoaded.empty())
5909 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
5910 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5911 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5912 if (TotalNumStatements)
5913 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5914 NumStatementsRead, TotalNumStatements,
5915 ((float)NumStatementsRead/TotalNumStatements * 100));
5916 if (TotalNumMacros)
5917 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5918 NumMacrosRead, TotalNumMacros,
5919 ((float)NumMacrosRead/TotalNumMacros * 100));
5920 if (TotalLexicalDeclContexts)
5921 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5922 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5923 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5924 * 100));
5925 if (TotalVisibleDeclContexts)
5926 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5927 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5928 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5929 * 100));
5930 if (TotalNumMethodPoolEntries) {
5931 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
5932 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5933 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5934 * 100));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005935 }
Douglas Gregor95fb36e2013-01-28 17:54:36 +00005936 if (NumMethodPoolLookups) {
5937 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
5938 NumMethodPoolHits, NumMethodPoolLookups,
5939 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
5940 }
5941 if (NumMethodPoolTableLookups) {
5942 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
5943 NumMethodPoolTableHits, NumMethodPoolTableLookups,
5944 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
5945 * 100.0));
5946 }
5947
Douglas Gregore1698072013-01-25 00:38:33 +00005948 if (NumIdentifierLookupHits) {
5949 std::fprintf(stderr,
5950 " %u / %u identifier table lookups succeeded (%f%%)\n",
5951 NumIdentifierLookupHits, NumIdentifierLookups,
5952 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
5953 }
5954
Douglas Gregor1a49d972013-01-25 01:03:03 +00005955 if (GlobalIndex) {
5956 std::fprintf(stderr, "\n");
5957 GlobalIndex->printStats();
5958 }
5959
Guy Benyei7f92f2d2012-12-18 14:30:41 +00005960 std::fprintf(stderr, "\n");
5961 dump();
5962 std::fprintf(stderr, "\n");
5963}
5964
5965template<typename Key, typename ModuleFile, unsigned InitialCapacity>
5966static void
5967dumpModuleIDMap(StringRef Name,
5968 const ContinuousRangeMap<Key, ModuleFile *,
5969 InitialCapacity> &Map) {
5970 if (Map.begin() == Map.end())
5971 return;
5972
5973 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
5974 llvm::errs() << Name << ":\n";
5975 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5976 I != IEnd; ++I) {
5977 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5978 << "\n";
5979 }
5980}
5981
5982void ASTReader::dump() {
5983 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
5984 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
5985 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
5986 dumpModuleIDMap("Global type map", GlobalTypeMap);
5987 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
5988 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
5989 dumpModuleIDMap("Global macro map", GlobalMacroMap);
5990 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
5991 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
5992 dumpModuleIDMap("Global preprocessed entity map",
5993 GlobalPreprocessedEntityMap);
5994
5995 llvm::errs() << "\n*** PCH/Modules Loaded:";
5996 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5997 MEnd = ModuleMgr.end();
5998 M != MEnd; ++M)
5999 (*M)->dump();
6000}
6001
6002/// Return the amount of memory used by memory buffers, breaking down
6003/// by heap-backed versus mmap'ed memory.
6004void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6005 for (ModuleConstIterator I = ModuleMgr.begin(),
6006 E = ModuleMgr.end(); I != E; ++I) {
6007 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6008 size_t bytes = buf->getBufferSize();
6009 switch (buf->getBufferKind()) {
6010 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6011 sizes.malloc_bytes += bytes;
6012 break;
6013 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6014 sizes.mmap_bytes += bytes;
6015 break;
6016 }
6017 }
6018 }
6019}
6020
6021void ASTReader::InitializeSema(Sema &S) {
6022 SemaObj = &S;
6023 S.addExternalSource(this);
6024
6025 // Makes sure any declarations that were deserialized "too early"
6026 // still get added to the identifier's declaration chains.
6027 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006028 pushExternalDeclIntoScope(PreloadedDecls[I],
6029 PreloadedDecls[I]->getDeclName());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006030 }
6031 PreloadedDecls.clear();
6032
6033 // Load the offsets of the declarations that Sema references.
6034 // They will be lazily deserialized when needed.
6035 if (!SemaDeclRefs.empty()) {
6036 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6037 if (!SemaObj->StdNamespace)
6038 SemaObj->StdNamespace = SemaDeclRefs[0];
6039 if (!SemaObj->StdBadAlloc)
6040 SemaObj->StdBadAlloc = SemaDeclRefs[1];
6041 }
6042
6043 if (!FPPragmaOptions.empty()) {
6044 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6045 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6046 }
6047
6048 if (!OpenCLExtensions.empty()) {
6049 unsigned I = 0;
6050#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6051#include "clang/Basic/OpenCLExtensions.def"
6052
6053 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6054 }
6055}
6056
6057IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6058 // Note that we are loading an identifier.
6059 Deserializing AnIdentifier(this);
Douglas Gregor1a49d972013-01-25 01:03:03 +00006060 StringRef Name(NameStart, NameEnd - NameStart);
6061
6062 // If there is a global index, look there first to determine which modules
6063 // provably do not have any results for this identifier.
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006064 GlobalModuleIndex::HitSet Hits;
6065 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006066 if (!loadGlobalIndex()) {
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006067 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6068 HitsPtr = &Hits;
Douglas Gregor1a49d972013-01-25 01:03:03 +00006069 }
6070 }
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006071 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregore1698072013-01-25 00:38:33 +00006072 NumIdentifierLookups,
6073 NumIdentifierLookupHits);
Douglas Gregor188bdcd2013-01-25 23:32:03 +00006074 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006075 IdentifierInfo *II = Visitor.getIdentifierInfo();
6076 markIdentifierUpToDate(II);
6077 return II;
6078}
6079
6080namespace clang {
6081 /// \brief An identifier-lookup iterator that enumerates all of the
6082 /// identifiers stored within a set of AST files.
6083 class ASTIdentifierIterator : public IdentifierIterator {
6084 /// \brief The AST reader whose identifiers are being enumerated.
6085 const ASTReader &Reader;
6086
6087 /// \brief The current index into the chain of AST files stored in
6088 /// the AST reader.
6089 unsigned Index;
6090
6091 /// \brief The current position within the identifier lookup table
6092 /// of the current AST file.
6093 ASTIdentifierLookupTable::key_iterator Current;
6094
6095 /// \brief The end position within the identifier lookup table of
6096 /// the current AST file.
6097 ASTIdentifierLookupTable::key_iterator End;
6098
6099 public:
6100 explicit ASTIdentifierIterator(const ASTReader &Reader);
6101
6102 virtual StringRef Next();
6103 };
6104}
6105
6106ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6107 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6108 ASTIdentifierLookupTable *IdTable
6109 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6110 Current = IdTable->key_begin();
6111 End = IdTable->key_end();
6112}
6113
6114StringRef ASTIdentifierIterator::Next() {
6115 while (Current == End) {
6116 // If we have exhausted all of our AST files, we're done.
6117 if (Index == 0)
6118 return StringRef();
6119
6120 --Index;
6121 ASTIdentifierLookupTable *IdTable
6122 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6123 IdentifierLookupTable;
6124 Current = IdTable->key_begin();
6125 End = IdTable->key_end();
6126 }
6127
6128 // We have any identifiers remaining in the current AST file; return
6129 // the next one.
Douglas Gregor479633c2013-01-23 18:53:14 +00006130 StringRef Result = *Current;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006131 ++Current;
Douglas Gregor479633c2013-01-23 18:53:14 +00006132 return Result;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006133}
6134
Argyrios Kyrtzidis87f9d812013-04-17 22:10:55 +00006135IdentifierIterator *ASTReader::getIdentifiers() {
6136 if (!loadGlobalIndex())
6137 return GlobalIndex->createIdentifierIterator();
6138
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006139 return new ASTIdentifierIterator(*this);
6140}
6141
6142namespace clang { namespace serialization {
6143 class ReadMethodPoolVisitor {
6144 ASTReader &Reader;
6145 Selector Sel;
6146 unsigned PriorGeneration;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006147 unsigned InstanceBits;
6148 unsigned FactoryBits;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006149 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6150 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006151
6152 public:
6153 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6154 unsigned PriorGeneration)
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006155 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6156 InstanceBits(0), FactoryBits(0) { }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006157
6158 static bool visit(ModuleFile &M, void *UserData) {
6159 ReadMethodPoolVisitor *This
6160 = static_cast<ReadMethodPoolVisitor *>(UserData);
6161
6162 if (!M.SelectorLookupTable)
6163 return false;
6164
6165 // If we've already searched this module file, skip it now.
6166 if (M.Generation <= This->PriorGeneration)
6167 return true;
6168
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006169 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006170 ASTSelectorLookupTable *PoolTable
6171 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6172 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6173 if (Pos == PoolTable->end())
6174 return false;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006175
6176 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006177 ++This->Reader.NumSelectorsRead;
6178 // FIXME: Not quite happy with the statistics here. We probably should
6179 // disable this tracking when called via LoadSelector.
6180 // Also, should entries without methods count as misses?
6181 ++This->Reader.NumMethodPoolEntriesRead;
6182 ASTSelectorLookupTrait::data_type Data = *Pos;
6183 if (This->Reader.DeserializationListener)
6184 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6185 This->Sel);
6186
6187 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6188 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006189 This->InstanceBits = Data.InstanceBits;
6190 This->FactoryBits = Data.FactoryBits;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006191 return true;
6192 }
6193
6194 /// \brief Retrieve the instance methods found by this visitor.
6195 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6196 return InstanceMethods;
6197 }
6198
6199 /// \brief Retrieve the instance methods found by this visitor.
6200 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6201 return FactoryMethods;
6202 }
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006203
6204 unsigned getInstanceBits() const { return InstanceBits; }
6205 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006206 };
6207} } // end namespace clang::serialization
6208
6209/// \brief Add the given set of methods to the method list.
6210static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6211 ObjCMethodList &List) {
6212 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6213 S.addMethodToGlobalList(&List, Methods[I]);
6214 }
6215}
6216
6217void ASTReader::ReadMethodPool(Selector Sel) {
6218 // Get the selector generation and update it to the current generation.
6219 unsigned &Generation = SelectorGeneration[Sel];
6220 unsigned PriorGeneration = Generation;
6221 Generation = CurrentGeneration;
6222
6223 // Search for methods defined with this selector.
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006224 ++NumMethodPoolLookups;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006225 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6226 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6227
6228 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006229 Visitor.getFactoryMethods().empty())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006230 return;
Douglas Gregor95fb36e2013-01-28 17:54:36 +00006231
6232 ++NumMethodPoolHits;
6233
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006234 if (!getSema())
6235 return;
6236
6237 Sema &S = *getSema();
6238 Sema::GlobalMethodPool::iterator Pos
6239 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6240
6241 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6242 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00006243 Pos->second.first.setBits(Visitor.getInstanceBits());
6244 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006245}
6246
6247void ASTReader::ReadKnownNamespaces(
6248 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6249 Namespaces.clear();
6250
6251 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6252 if (NamespaceDecl *Namespace
6253 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6254 Namespaces.push_back(Namespace);
6255 }
6256}
6257
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006258void ASTReader::ReadUndefinedButUsed(
Nick Lewycky995e26b2013-01-31 03:23:57 +00006259 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006260 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6261 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky01a41142013-01-26 00:35:08 +00006262 SourceLocation Loc =
Nick Lewyckycd0655b2013-02-01 08:13:20 +00006263 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky01a41142013-01-26 00:35:08 +00006264 Undefined.insert(std::make_pair(D, Loc));
6265 }
6266}
Nick Lewycky01a41142013-01-26 00:35:08 +00006267
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006268void ASTReader::ReadTentativeDefinitions(
6269 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6270 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6271 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6272 if (Var)
6273 TentativeDefs.push_back(Var);
6274 }
6275 TentativeDefinitions.clear();
6276}
6277
6278void ASTReader::ReadUnusedFileScopedDecls(
6279 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6280 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6281 DeclaratorDecl *D
6282 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6283 if (D)
6284 Decls.push_back(D);
6285 }
6286 UnusedFileScopedDecls.clear();
6287}
6288
6289void ASTReader::ReadDelegatingConstructors(
6290 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6291 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6292 CXXConstructorDecl *D
6293 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6294 if (D)
6295 Decls.push_back(D);
6296 }
6297 DelegatingCtorDecls.clear();
6298}
6299
6300void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6301 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6302 TypedefNameDecl *D
6303 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6304 if (D)
6305 Decls.push_back(D);
6306 }
6307 ExtVectorDecls.clear();
6308}
6309
6310void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6311 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6312 CXXRecordDecl *D
6313 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6314 if (D)
6315 Decls.push_back(D);
6316 }
6317 DynamicClasses.clear();
6318}
6319
6320void
Richard Smith5ea6ef42013-01-10 23:43:47 +00006321ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6322 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6323 NamedDecl *D
6324 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006325 if (D)
6326 Decls.push_back(D);
6327 }
Richard Smith5ea6ef42013-01-10 23:43:47 +00006328 LocallyScopedExternCDecls.clear();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006329}
6330
6331void ASTReader::ReadReferencedSelectors(
6332 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6333 if (ReferencedSelectorsData.empty())
6334 return;
6335
6336 // If there are @selector references added them to its pool. This is for
6337 // implementation of -Wselector.
6338 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6339 unsigned I = 0;
6340 while (I < DataSize) {
6341 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6342 SourceLocation SelLoc
6343 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6344 Sels.push_back(std::make_pair(Sel, SelLoc));
6345 }
6346 ReferencedSelectorsData.clear();
6347}
6348
6349void ASTReader::ReadWeakUndeclaredIdentifiers(
6350 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6351 if (WeakUndeclaredIdentifiers.empty())
6352 return;
6353
6354 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6355 IdentifierInfo *WeakId
6356 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6357 IdentifierInfo *AliasId
6358 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6359 SourceLocation Loc
6360 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6361 bool Used = WeakUndeclaredIdentifiers[I++];
6362 WeakInfo WI(AliasId, Loc);
6363 WI.setUsed(Used);
6364 WeakIDs.push_back(std::make_pair(WeakId, WI));
6365 }
6366 WeakUndeclaredIdentifiers.clear();
6367}
6368
6369void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6370 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6371 ExternalVTableUse VT;
6372 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6373 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6374 VT.DefinitionRequired = VTableUses[Idx++];
6375 VTables.push_back(VT);
6376 }
6377
6378 VTableUses.clear();
6379}
6380
6381void ASTReader::ReadPendingInstantiations(
6382 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6383 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6384 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6385 SourceLocation Loc
6386 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6387
6388 Pending.push_back(std::make_pair(D, Loc));
6389 }
6390 PendingInstantiations.clear();
6391}
6392
6393void ASTReader::LoadSelector(Selector Sel) {
6394 // It would be complicated to avoid reading the methods anyway. So don't.
6395 ReadMethodPool(Sel);
6396}
6397
6398void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6399 assert(ID && "Non-zero identifier ID required");
6400 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6401 IdentifiersLoaded[ID - 1] = II;
6402 if (DeserializationListener)
6403 DeserializationListener->IdentifierRead(ID, II);
6404}
6405
6406/// \brief Set the globally-visible declarations associated with the given
6407/// identifier.
6408///
6409/// If the AST reader is currently in a state where the given declaration IDs
6410/// cannot safely be resolved, they are queued until it is safe to resolve
6411/// them.
6412///
6413/// \param II an IdentifierInfo that refers to one or more globally-visible
6414/// declarations.
6415///
6416/// \param DeclIDs the set of declaration IDs with the name @p II that are
6417/// visible at global scope.
6418///
Douglas Gregoraa945902013-02-18 15:53:43 +00006419/// \param Decls if non-null, this vector will be populated with the set of
6420/// deserialized declarations. These declarations will not be pushed into
6421/// scope.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006422void
6423ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6424 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregoraa945902013-02-18 15:53:43 +00006425 SmallVectorImpl<Decl *> *Decls) {
6426 if (NumCurrentElementsDeserializing && !Decls) {
6427 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006428 return;
6429 }
6430
6431 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6432 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6433 if (SemaObj) {
Douglas Gregoraa945902013-02-18 15:53:43 +00006434 // If we're simply supposed to record the declarations, do so now.
6435 if (Decls) {
6436 Decls->push_back(D);
6437 continue;
6438 }
6439
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006440 // Introduce this declaration into the translation-unit scope
6441 // and add it to the declaration chain for this identifier, so
6442 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00006443 pushExternalDeclIntoScope(D, II);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006444 } else {
6445 // Queue this declaration so that it will be added to the
6446 // translation unit scope and identifier's declaration chain
6447 // once a Sema object is known.
6448 PreloadedDecls.push_back(D);
6449 }
6450 }
6451}
6452
Douglas Gregor8222b892013-01-21 16:52:34 +00006453IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006454 if (ID == 0)
6455 return 0;
6456
6457 if (IdentifiersLoaded.empty()) {
6458 Error("no identifier table in AST file");
6459 return 0;
6460 }
6461
6462 ID -= 1;
6463 if (!IdentifiersLoaded[ID]) {
6464 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6465 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6466 ModuleFile *M = I->second;
6467 unsigned Index = ID - M->BaseIdentifierID;
6468 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6469
6470 // All of the strings in the AST file are preceded by a 16-bit length.
6471 // Extract that 16-bit length to avoid having to execute strlen().
6472 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6473 // unsigned integers. This is important to avoid integer overflow when
6474 // we cast them to 'unsigned'.
6475 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6476 unsigned StrLen = (((unsigned) StrLenPtr[0])
6477 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregor8222b892013-01-21 16:52:34 +00006478 IdentifiersLoaded[ID]
6479 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006480 if (DeserializationListener)
6481 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6482 }
6483
6484 return IdentifiersLoaded[ID];
6485}
6486
Douglas Gregor8222b892013-01-21 16:52:34 +00006487IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6488 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006489}
6490
6491IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6492 if (LocalID < NUM_PREDEF_IDENT_IDS)
6493 return LocalID;
6494
6495 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6496 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6497 assert(I != M.IdentifierRemap.end()
6498 && "Invalid index into identifier index remap");
6499
6500 return LocalID + I->second;
6501}
6502
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006503MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006504 if (ID == 0)
6505 return 0;
6506
6507 if (MacrosLoaded.empty()) {
6508 Error("no macro table in AST file");
6509 return 0;
6510 }
6511
6512 ID -= NUM_PREDEF_MACRO_IDS;
6513 if (!MacrosLoaded[ID]) {
6514 GlobalMacroMapType::iterator I
6515 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6516 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6517 ModuleFile *M = I->second;
6518 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00006519 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6520
6521 if (DeserializationListener)
6522 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6523 MacrosLoaded[ID]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006524 }
6525
6526 return MacrosLoaded[ID];
6527}
6528
6529MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6530 if (LocalID < NUM_PREDEF_MACRO_IDS)
6531 return LocalID;
6532
6533 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6534 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6535 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6536
6537 return LocalID + I->second;
6538}
6539
6540serialization::SubmoduleID
6541ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6542 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6543 return LocalID;
6544
6545 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6546 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6547 assert(I != M.SubmoduleRemap.end()
6548 && "Invalid index into submodule index remap");
6549
6550 return LocalID + I->second;
6551}
6552
6553Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6554 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6555 assert(GlobalID == 0 && "Unhandled global submodule ID");
6556 return 0;
6557 }
6558
6559 if (GlobalID > SubmodulesLoaded.size()) {
6560 Error("submodule ID out of range in AST file");
6561 return 0;
6562 }
6563
6564 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6565}
Douglas Gregorca2ab452013-01-12 01:29:50 +00006566
6567Module *ASTReader::getModule(unsigned ID) {
6568 return getSubmodule(ID);
6569}
6570
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006571Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6572 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6573}
6574
6575Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6576 if (ID == 0)
6577 return Selector();
6578
6579 if (ID > SelectorsLoaded.size()) {
6580 Error("selector ID out of range in AST file");
6581 return Selector();
6582 }
6583
6584 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6585 // Load this selector from the selector table.
6586 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6587 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6588 ModuleFile &M = *I->second;
6589 ASTSelectorLookupTrait Trait(*this, M);
6590 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6591 SelectorsLoaded[ID - 1] =
6592 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6593 if (DeserializationListener)
6594 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6595 }
6596
6597 return SelectorsLoaded[ID - 1];
6598}
6599
6600Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6601 return DecodeSelector(ID);
6602}
6603
6604uint32_t ASTReader::GetNumExternalSelectors() {
6605 // ID 0 (the null selector) is considered an external selector.
6606 return getTotalNumSelectors() + 1;
6607}
6608
6609serialization::SelectorID
6610ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6611 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6612 return LocalID;
6613
6614 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6615 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6616 assert(I != M.SelectorRemap.end()
6617 && "Invalid index into selector index remap");
6618
6619 return LocalID + I->second;
6620}
6621
6622DeclarationName
6623ASTReader::ReadDeclarationName(ModuleFile &F,
6624 const RecordData &Record, unsigned &Idx) {
6625 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6626 switch (Kind) {
6627 case DeclarationName::Identifier:
Douglas Gregor8222b892013-01-21 16:52:34 +00006628 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006629
6630 case DeclarationName::ObjCZeroArgSelector:
6631 case DeclarationName::ObjCOneArgSelector:
6632 case DeclarationName::ObjCMultiArgSelector:
6633 return DeclarationName(ReadSelector(F, Record, Idx));
6634
6635 case DeclarationName::CXXConstructorName:
6636 return Context.DeclarationNames.getCXXConstructorName(
6637 Context.getCanonicalType(readType(F, Record, Idx)));
6638
6639 case DeclarationName::CXXDestructorName:
6640 return Context.DeclarationNames.getCXXDestructorName(
6641 Context.getCanonicalType(readType(F, Record, Idx)));
6642
6643 case DeclarationName::CXXConversionFunctionName:
6644 return Context.DeclarationNames.getCXXConversionFunctionName(
6645 Context.getCanonicalType(readType(F, Record, Idx)));
6646
6647 case DeclarationName::CXXOperatorName:
6648 return Context.DeclarationNames.getCXXOperatorName(
6649 (OverloadedOperatorKind)Record[Idx++]);
6650
6651 case DeclarationName::CXXLiteralOperatorName:
6652 return Context.DeclarationNames.getCXXLiteralOperatorName(
6653 GetIdentifierInfo(F, Record, Idx));
6654
6655 case DeclarationName::CXXUsingDirective:
6656 return DeclarationName::getUsingDirectiveName();
6657 }
6658
6659 llvm_unreachable("Invalid NameKind!");
6660}
6661
6662void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6663 DeclarationNameLoc &DNLoc,
6664 DeclarationName Name,
6665 const RecordData &Record, unsigned &Idx) {
6666 switch (Name.getNameKind()) {
6667 case DeclarationName::CXXConstructorName:
6668 case DeclarationName::CXXDestructorName:
6669 case DeclarationName::CXXConversionFunctionName:
6670 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6671 break;
6672
6673 case DeclarationName::CXXOperatorName:
6674 DNLoc.CXXOperatorName.BeginOpNameLoc
6675 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6676 DNLoc.CXXOperatorName.EndOpNameLoc
6677 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6678 break;
6679
6680 case DeclarationName::CXXLiteralOperatorName:
6681 DNLoc.CXXLiteralOperatorName.OpNameLoc
6682 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6683 break;
6684
6685 case DeclarationName::Identifier:
6686 case DeclarationName::ObjCZeroArgSelector:
6687 case DeclarationName::ObjCOneArgSelector:
6688 case DeclarationName::ObjCMultiArgSelector:
6689 case DeclarationName::CXXUsingDirective:
6690 break;
6691 }
6692}
6693
6694void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6695 DeclarationNameInfo &NameInfo,
6696 const RecordData &Record, unsigned &Idx) {
6697 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6698 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6699 DeclarationNameLoc DNLoc;
6700 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6701 NameInfo.setInfo(DNLoc);
6702}
6703
6704void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6705 const RecordData &Record, unsigned &Idx) {
6706 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6707 unsigned NumTPLists = Record[Idx++];
6708 Info.NumTemplParamLists = NumTPLists;
6709 if (NumTPLists) {
6710 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6711 for (unsigned i=0; i != NumTPLists; ++i)
6712 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6713 }
6714}
6715
6716TemplateName
6717ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6718 unsigned &Idx) {
6719 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6720 switch (Kind) {
6721 case TemplateName::Template:
6722 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6723
6724 case TemplateName::OverloadedTemplate: {
6725 unsigned size = Record[Idx++];
6726 UnresolvedSet<8> Decls;
6727 while (size--)
6728 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6729
6730 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6731 }
6732
6733 case TemplateName::QualifiedTemplate: {
6734 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6735 bool hasTemplKeyword = Record[Idx++];
6736 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6737 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6738 }
6739
6740 case TemplateName::DependentTemplate: {
6741 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6742 if (Record[Idx++]) // isIdentifier
6743 return Context.getDependentTemplateName(NNS,
6744 GetIdentifierInfo(F, Record,
6745 Idx));
6746 return Context.getDependentTemplateName(NNS,
6747 (OverloadedOperatorKind)Record[Idx++]);
6748 }
6749
6750 case TemplateName::SubstTemplateTemplateParm: {
6751 TemplateTemplateParmDecl *param
6752 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6753 if (!param) return TemplateName();
6754 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6755 return Context.getSubstTemplateTemplateParm(param, replacement);
6756 }
6757
6758 case TemplateName::SubstTemplateTemplateParmPack: {
6759 TemplateTemplateParmDecl *Param
6760 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6761 if (!Param)
6762 return TemplateName();
6763
6764 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6765 if (ArgPack.getKind() != TemplateArgument::Pack)
6766 return TemplateName();
6767
6768 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6769 }
6770 }
6771
6772 llvm_unreachable("Unhandled template name kind!");
6773}
6774
6775TemplateArgument
6776ASTReader::ReadTemplateArgument(ModuleFile &F,
6777 const RecordData &Record, unsigned &Idx) {
6778 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6779 switch (Kind) {
6780 case TemplateArgument::Null:
6781 return TemplateArgument();
6782 case TemplateArgument::Type:
6783 return TemplateArgument(readType(F, Record, Idx));
6784 case TemplateArgument::Declaration: {
6785 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6786 bool ForReferenceParam = Record[Idx++];
6787 return TemplateArgument(D, ForReferenceParam);
6788 }
6789 case TemplateArgument::NullPtr:
6790 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6791 case TemplateArgument::Integral: {
6792 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6793 QualType T = readType(F, Record, Idx);
6794 return TemplateArgument(Context, Value, T);
6795 }
6796 case TemplateArgument::Template:
6797 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6798 case TemplateArgument::TemplateExpansion: {
6799 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikiedc84cd52013-02-20 22:23:23 +00006800 Optional<unsigned> NumTemplateExpansions;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00006801 if (unsigned NumExpansions = Record[Idx++])
6802 NumTemplateExpansions = NumExpansions - 1;
6803 return TemplateArgument(Name, NumTemplateExpansions);
6804 }
6805 case TemplateArgument::Expression:
6806 return TemplateArgument(ReadExpr(F));
6807 case TemplateArgument::Pack: {
6808 unsigned NumArgs = Record[Idx++];
6809 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6810 for (unsigned I = 0; I != NumArgs; ++I)
6811 Args[I] = ReadTemplateArgument(F, Record, Idx);
6812 return TemplateArgument(Args, NumArgs);
6813 }
6814 }
6815
6816 llvm_unreachable("Unhandled template argument kind!");
6817}
6818
6819TemplateParameterList *
6820ASTReader::ReadTemplateParameterList(ModuleFile &F,
6821 const RecordData &Record, unsigned &Idx) {
6822 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6823 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6824 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6825
6826 unsigned NumParams = Record[Idx++];
6827 SmallVector<NamedDecl *, 16> Params;
6828 Params.reserve(NumParams);
6829 while (NumParams--)
6830 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6831
6832 TemplateParameterList* TemplateParams =
6833 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6834 Params.data(), Params.size(), RAngleLoc);
6835 return TemplateParams;
6836}
6837
6838void
6839ASTReader::
6840ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6841 ModuleFile &F, const RecordData &Record,
6842 unsigned &Idx) {
6843 unsigned NumTemplateArgs = Record[Idx++];
6844 TemplArgs.reserve(NumTemplateArgs);
6845 while (NumTemplateArgs--)
6846 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6847}
6848
6849/// \brief Read a UnresolvedSet structure.
6850void ASTReader::ReadUnresolvedSet(ModuleFile &F, ASTUnresolvedSet &Set,
6851 const RecordData &Record, unsigned &Idx) {
6852 unsigned NumDecls = Record[Idx++];
6853 Set.reserve(Context, NumDecls);
6854 while (NumDecls--) {
6855 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6856 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6857 Set.addDecl(Context, D, AS);
6858 }
6859}
6860
6861CXXBaseSpecifier
6862ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6863 const RecordData &Record, unsigned &Idx) {
6864 bool isVirtual = static_cast<bool>(Record[Idx++]);
6865 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6866 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6867 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6868 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6869 SourceRange Range = ReadSourceRange(F, Record, Idx);
6870 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6871 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6872 EllipsisLoc);
6873 Result.setInheritConstructors(inheritConstructors);
6874 return Result;
6875}
6876
6877std::pair<CXXCtorInitializer **, unsigned>
6878ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6879 unsigned &Idx) {
6880 CXXCtorInitializer **CtorInitializers = 0;
6881 unsigned NumInitializers = Record[Idx++];
6882 if (NumInitializers) {
6883 CtorInitializers
6884 = new (Context) CXXCtorInitializer*[NumInitializers];
6885 for (unsigned i=0; i != NumInitializers; ++i) {
6886 TypeSourceInfo *TInfo = 0;
6887 bool IsBaseVirtual = false;
6888 FieldDecl *Member = 0;
6889 IndirectFieldDecl *IndirectMember = 0;
6890
6891 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6892 switch (Type) {
6893 case CTOR_INITIALIZER_BASE:
6894 TInfo = GetTypeSourceInfo(F, Record, Idx);
6895 IsBaseVirtual = Record[Idx++];
6896 break;
6897
6898 case CTOR_INITIALIZER_DELEGATING:
6899 TInfo = GetTypeSourceInfo(F, Record, Idx);
6900 break;
6901
6902 case CTOR_INITIALIZER_MEMBER:
6903 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6904 break;
6905
6906 case CTOR_INITIALIZER_INDIRECT_MEMBER:
6907 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6908 break;
6909 }
6910
6911 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6912 Expr *Init = ReadExpr(F);
6913 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6914 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6915 bool IsWritten = Record[Idx++];
6916 unsigned SourceOrderOrNumArrayIndices;
6917 SmallVector<VarDecl *, 8> Indices;
6918 if (IsWritten) {
6919 SourceOrderOrNumArrayIndices = Record[Idx++];
6920 } else {
6921 SourceOrderOrNumArrayIndices = Record[Idx++];
6922 Indices.reserve(SourceOrderOrNumArrayIndices);
6923 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6924 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6925 }
6926
6927 CXXCtorInitializer *BOMInit;
6928 if (Type == CTOR_INITIALIZER_BASE) {
6929 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6930 LParenLoc, Init, RParenLoc,
6931 MemberOrEllipsisLoc);
6932 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6933 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6934 Init, RParenLoc);
6935 } else if (IsWritten) {
6936 if (Member)
6937 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6938 LParenLoc, Init, RParenLoc);
6939 else
6940 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6941 MemberOrEllipsisLoc, LParenLoc,
6942 Init, RParenLoc);
6943 } else {
6944 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6945 LParenLoc, Init, RParenLoc,
6946 Indices.data(), Indices.size());
6947 }
6948
6949 if (IsWritten)
6950 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6951 CtorInitializers[i] = BOMInit;
6952 }
6953 }
6954
6955 return std::make_pair(CtorInitializers, NumInitializers);
6956}
6957
6958NestedNameSpecifier *
6959ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6960 const RecordData &Record, unsigned &Idx) {
6961 unsigned N = Record[Idx++];
6962 NestedNameSpecifier *NNS = 0, *Prev = 0;
6963 for (unsigned I = 0; I != N; ++I) {
6964 NestedNameSpecifier::SpecifierKind Kind
6965 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6966 switch (Kind) {
6967 case NestedNameSpecifier::Identifier: {
6968 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6969 NNS = NestedNameSpecifier::Create(Context, Prev, II);
6970 break;
6971 }
6972
6973 case NestedNameSpecifier::Namespace: {
6974 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6975 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6976 break;
6977 }
6978
6979 case NestedNameSpecifier::NamespaceAlias: {
6980 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6981 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6982 break;
6983 }
6984
6985 case NestedNameSpecifier::TypeSpec:
6986 case NestedNameSpecifier::TypeSpecWithTemplate: {
6987 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6988 if (!T)
6989 return 0;
6990
6991 bool Template = Record[Idx++];
6992 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6993 break;
6994 }
6995
6996 case NestedNameSpecifier::Global: {
6997 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6998 // No associated value, and there can't be a prefix.
6999 break;
7000 }
7001 }
7002 Prev = NNS;
7003 }
7004 return NNS;
7005}
7006
7007NestedNameSpecifierLoc
7008ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7009 unsigned &Idx) {
7010 unsigned N = Record[Idx++];
7011 NestedNameSpecifierLocBuilder Builder;
7012 for (unsigned I = 0; I != N; ++I) {
7013 NestedNameSpecifier::SpecifierKind Kind
7014 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7015 switch (Kind) {
7016 case NestedNameSpecifier::Identifier: {
7017 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7018 SourceRange Range = ReadSourceRange(F, Record, Idx);
7019 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7020 break;
7021 }
7022
7023 case NestedNameSpecifier::Namespace: {
7024 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7025 SourceRange Range = ReadSourceRange(F, Record, Idx);
7026 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7027 break;
7028 }
7029
7030 case NestedNameSpecifier::NamespaceAlias: {
7031 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7032 SourceRange Range = ReadSourceRange(F, Record, Idx);
7033 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7034 break;
7035 }
7036
7037 case NestedNameSpecifier::TypeSpec:
7038 case NestedNameSpecifier::TypeSpecWithTemplate: {
7039 bool Template = Record[Idx++];
7040 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7041 if (!T)
7042 return NestedNameSpecifierLoc();
7043 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7044
7045 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7046 Builder.Extend(Context,
7047 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7048 T->getTypeLoc(), ColonColonLoc);
7049 break;
7050 }
7051
7052 case NestedNameSpecifier::Global: {
7053 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7054 Builder.MakeGlobal(Context, ColonColonLoc);
7055 break;
7056 }
7057 }
7058 }
7059
7060 return Builder.getWithLocInContext(Context);
7061}
7062
7063SourceRange
7064ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7065 unsigned &Idx) {
7066 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7067 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7068 return SourceRange(beg, end);
7069}
7070
7071/// \brief Read an integral value
7072llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7073 unsigned BitWidth = Record[Idx++];
7074 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7075 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7076 Idx += NumWords;
7077 return Result;
7078}
7079
7080/// \brief Read a signed integral value
7081llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7082 bool isUnsigned = Record[Idx++];
7083 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7084}
7085
7086/// \brief Read a floating-point value
Tim Northover9ec55f22013-01-22 09:46:51 +00007087llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7088 const llvm::fltSemantics &Sem,
7089 unsigned &Idx) {
7090 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007091}
7092
7093// \brief Read a string
7094std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7095 unsigned Len = Record[Idx++];
7096 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7097 Idx += Len;
7098 return Result;
7099}
7100
7101VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7102 unsigned &Idx) {
7103 unsigned Major = Record[Idx++];
7104 unsigned Minor = Record[Idx++];
7105 unsigned Subminor = Record[Idx++];
7106 if (Minor == 0)
7107 return VersionTuple(Major);
7108 if (Subminor == 0)
7109 return VersionTuple(Major, Minor - 1);
7110 return VersionTuple(Major, Minor - 1, Subminor - 1);
7111}
7112
7113CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7114 const RecordData &Record,
7115 unsigned &Idx) {
7116 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7117 return CXXTemporary::Create(Context, Decl);
7118}
7119
7120DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7121 return Diag(SourceLocation(), DiagID);
7122}
7123
7124DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7125 return Diags.Report(Loc, DiagID);
7126}
7127
7128/// \brief Retrieve the identifier table associated with the
7129/// preprocessor.
7130IdentifierTable &ASTReader::getIdentifierTable() {
7131 return PP.getIdentifierTable();
7132}
7133
7134/// \brief Record that the given ID maps to the given switch-case
7135/// statement.
7136void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7137 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7138 "Already have a SwitchCase with this ID");
7139 (*CurrSwitchCaseStmts)[ID] = SC;
7140}
7141
7142/// \brief Retrieve the switch-case statement with the given ID.
7143SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7144 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7145 return (*CurrSwitchCaseStmts)[ID];
7146}
7147
7148void ASTReader::ClearSwitchCaseIDs() {
7149 CurrSwitchCaseStmts->clear();
7150}
7151
7152void ASTReader::ReadComments() {
7153 std::vector<RawComment *> Comments;
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007154 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007155 serialization::ModuleFile *> >::iterator
7156 I = CommentsCursors.begin(),
7157 E = CommentsCursors.end();
7158 I != E; ++I) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007159 BitstreamCursor &Cursor = I->first;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007160 serialization::ModuleFile &F = *I->second;
7161 SavedStreamPosition SavedPosition(Cursor);
7162
7163 RecordData Record;
7164 while (true) {
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007165 llvm::BitstreamEntry Entry =
7166 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7167
7168 switch (Entry.Kind) {
7169 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7170 case llvm::BitstreamEntry::Error:
7171 Error("malformed block record in AST file");
7172 return;
7173 case llvm::BitstreamEntry::EndBlock:
7174 goto NextCursor;
7175 case llvm::BitstreamEntry::Record:
7176 // The interesting case.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007177 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007178 }
7179
7180 // Read a record.
7181 Record.clear();
Chris Lattnerb3ce3572013-01-20 02:38:54 +00007182 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007183 case COMMENTS_RAW_COMMENT: {
7184 unsigned Idx = 0;
7185 SourceRange SR = ReadSourceRange(F, Record, Idx);
7186 RawComment::CommentKind Kind =
7187 (RawComment::CommentKind) Record[Idx++];
7188 bool IsTrailingComment = Record[Idx++];
7189 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +00007190 Comments.push_back(new (Context) RawComment(
7191 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7192 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007193 break;
7194 }
7195 }
7196 }
Chris Lattner8f9a1eb2013-01-20 00:56:42 +00007197 NextCursor:;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007198 }
7199 Context.Comments.addCommentsToFront(Comments);
7200}
7201
7202void ASTReader::finishPendingActions() {
7203 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007204 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007205 // If any identifiers with corresponding top-level declarations have
7206 // been loaded, load those declarations now.
Douglas Gregoraa945902013-02-18 15:53:43 +00007207 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> > TopLevelDecls;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007208 while (!PendingIdentifierInfos.empty()) {
Douglas Gregoraa945902013-02-18 15:53:43 +00007209 // FIXME: std::move
7210 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7211 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcc9bdcb2013-02-19 18:26:28 +00007212 PendingIdentifierInfos.pop_back();
Douglas Gregoraa945902013-02-18 15:53:43 +00007213
7214 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007215 }
7216
7217 // Load pending declaration chains.
7218 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7219 loadPendingDeclChain(PendingDeclChains[I]);
7220 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7221 }
7222 PendingDeclChains.clear();
7223
Douglas Gregoraa945902013-02-18 15:53:43 +00007224 // Make the most recent of the top-level declarations visible.
7225 for (llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >::iterator
7226 TLD = TopLevelDecls.begin(), TLDEnd = TopLevelDecls.end();
7227 TLD != TLDEnd; ++TLD) {
7228 IdentifierInfo *II = TLD->first;
7229 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007230 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregoraa945902013-02-18 15:53:43 +00007231 }
7232 }
7233
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007234 // Load any pending macro definitions.
7235 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007236 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7237 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7238 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7239 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidisdc1088f2013-01-19 03:14:56 +00007240 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7241 ++IDIdx) {
Argyrios Kyrtzidis9317ab92013-03-22 21:12:57 +00007242 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7243 if (Info.M->Kind != MK_Module)
7244 resolvePendingMacro(II, Info);
7245 }
7246 // Handle module imports.
7247 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7248 ++IDIdx) {
7249 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7250 if (Info.M->Kind == MK_Module)
7251 resolvePendingMacro(II, Info);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007252 }
7253 }
7254 PendingMacroIDs.clear();
Argyrios Kyrtzidis7640b022013-02-16 00:48:59 +00007255
7256 // Wire up the DeclContexts for Decls that we delayed setting until
7257 // recursive loading is completed.
7258 while (!PendingDeclContextInfos.empty()) {
7259 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7260 PendingDeclContextInfos.pop_front();
7261 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7262 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7263 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7264 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007265 }
7266
7267 // If we deserialized any C++ or Objective-C class definitions, any
7268 // Objective-C protocol definitions, or any redeclarable templates, make sure
7269 // that all redeclarations point to the definitions. Note that this can only
7270 // happen now, after the redeclaration chains have been fully wired.
7271 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7272 DEnd = PendingDefinitions.end();
7273 D != DEnd; ++D) {
7274 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7275 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7276 // Make sure that the TagType points at the definition.
7277 const_cast<TagType*>(TagT)->decl = TD;
7278 }
7279
7280 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7281 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7282 REnd = RD->redecls_end();
7283 R != REnd; ++R)
7284 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7285
7286 }
7287
7288 continue;
7289 }
7290
7291 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7292 // Make sure that the ObjCInterfaceType points at the definition.
7293 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7294 ->Decl = ID;
7295
7296 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7297 REnd = ID->redecls_end();
7298 R != REnd; ++R)
7299 R->Data = ID->Data;
7300
7301 continue;
7302 }
7303
7304 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7305 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7306 REnd = PD->redecls_end();
7307 R != REnd; ++R)
7308 R->Data = PD->Data;
7309
7310 continue;
7311 }
7312
7313 RedeclarableTemplateDecl *RTD
7314 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7315 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7316 REnd = RTD->redecls_end();
7317 R != REnd; ++R)
7318 R->Common = RTD->Common;
7319 }
7320 PendingDefinitions.clear();
7321
7322 // Load the bodies of any functions or methods we've encountered. We do
7323 // this now (delayed) so that we can be sure that the declaration chains
7324 // have been fully wired up.
7325 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7326 PBEnd = PendingBodies.end();
7327 PB != PBEnd; ++PB) {
7328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7329 // FIXME: Check for =delete/=default?
7330 // FIXME: Complain about ODR violations here?
7331 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7332 FD->setLazyBody(PB->second);
7333 continue;
7334 }
7335
7336 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7337 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7338 MD->setLazyBody(PB->second);
7339 }
7340 PendingBodies.clear();
7341}
7342
7343void ASTReader::FinishedDeserializing() {
7344 assert(NumCurrentElementsDeserializing &&
7345 "FinishedDeserializing not paired with StartedDeserializing");
7346 if (NumCurrentElementsDeserializing == 1) {
7347 // We decrease NumCurrentElementsDeserializing only after pending actions
7348 // are finished, to avoid recursively re-calling finishPendingActions().
7349 finishPendingActions();
7350 }
7351 --NumCurrentElementsDeserializing;
7352
7353 if (NumCurrentElementsDeserializing == 0 &&
7354 Consumer && !PassingDeclsToConsumer) {
7355 // Guard variable to avoid recursively redoing the process of passing
7356 // decls to consumer.
7357 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7358 true);
7359
7360 while (!InterestingDecls.empty()) {
7361 // We are not in recursive loading, so it's safe to pass the "interesting"
7362 // decls to the consumer.
7363 Decl *D = InterestingDecls.front();
7364 InterestingDecls.pop_front();
7365 PassInterestingDeclToConsumer(D);
7366 }
7367 }
7368}
7369
Argyrios Kyrtzidis0532df02013-04-26 21:33:35 +00007370void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
7371 D = cast<NamedDecl>(D->getMostRecentDecl());
7372
7373 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7374 SemaObj->TUScope->AddDecl(D);
7375 } else if (SemaObj->TUScope) {
7376 // Adding the decl to IdResolver may have failed because it was already in
7377 // (even though it was not added in scope). If it is already in, make sure
7378 // it gets in the scope as well.
7379 if (std::find(SemaObj->IdResolver.begin(Name),
7380 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7381 SemaObj->TUScope->AddDecl(D);
7382 }
7383}
7384
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007385ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7386 StringRef isysroot, bool DisableValidation,
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007387 bool AllowASTWithCompilerErrors, bool UseGlobalIndex)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007388 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7389 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7390 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7391 Consumer(0), ModuleMgr(PP.getFileManager()),
7392 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregore1698072013-01-25 00:38:33 +00007393 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Douglas Gregorf575d6e2013-01-25 00:45:27 +00007394 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007395 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7396 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregore1698072013-01-25 00:38:33 +00007397 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7398 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7399 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregor95fb36e2013-01-28 17:54:36 +00007400 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7401 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7402 TotalNumMethodPoolEntries(0),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00007403 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7404 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7405 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7406 PassingDeclsToConsumer(false),
7407 NumCXXBaseSpecifiersLoaded(0)
7408{
7409 SourceMgr.setExternalSLocEntrySource(this);
7410}
7411
7412ASTReader::~ASTReader() {
7413 for (DeclContextVisibleUpdatesPending::iterator
7414 I = PendingVisibleUpdates.begin(),
7415 E = PendingVisibleUpdates.end();
7416 I != E; ++I) {
7417 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7418 F = I->second.end();
7419 J != F; ++J)
7420 delete J->first;
7421 }
7422}