blob: 674aefeb1c54a68763c6f8066497f32e90b26229 [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/SourceManagerInternals.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Basic/TargetOptions.h"
30#include "clang/Basic/Version.h"
31#include "clang/Basic/VersionTuple.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/HeaderSearchOptions.h"
34#include "clang/Lex/MacroInfo.h"
35#include "clang/Lex/PreprocessingRecord.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Lex/PreprocessorOptions.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000041#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Serialization/ModuleManager.h"
43#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000044#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-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 Lattner91f373e2013-01-20 00:57:52 +000054#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <iterator>
56
57using namespace clang;
58using namespace clang::serialization;
59using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000060using llvm::BitstreamCursor;
Guy Benyei11169dd2012-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 Gribenkoacf2e782013-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 Benyei11169dd2012-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");
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
144#undef CHECK_TARGET_OPT
145
146 // Compare feature sets.
147 SmallVector<StringRef, 4> ExistingFeatures(
148 ExistingTargetOpts.FeaturesAsWritten.begin(),
149 ExistingTargetOpts.FeaturesAsWritten.end());
150 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
151 TargetOpts.FeaturesAsWritten.end());
152 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
153 std::sort(ReadFeatures.begin(), ReadFeatures.end());
154
155 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
156 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
157 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
158 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
159 ++ExistingIdx;
160 ++ReadIdx;
161 continue;
162 }
163
164 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
165 if (Diags)
166 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
167 << false << ReadFeatures[ReadIdx];
168 return true;
169 }
170
171 if (Diags)
172 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
173 << true << ExistingFeatures[ExistingIdx];
174 return true;
175 }
176
177 if (ExistingIdx < ExistingN) {
178 if (Diags)
179 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
180 << true << ExistingFeatures[ExistingIdx];
181 return true;
182 }
183
184 if (ReadIdx < ReadN) {
185 if (Diags)
186 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
187 << false << ReadFeatures[ReadIdx];
188 return true;
189 }
190
191 return false;
192}
193
194bool
195PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
196 bool Complain) {
197 const LangOptions &ExistingLangOpts = PP.getLangOpts();
198 return checkLanguageOptions(LangOpts, ExistingLangOpts,
199 Complain? &Reader.Diags : 0);
200}
201
202bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
203 bool Complain) {
204 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
205 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
206 Complain? &Reader.Diags : 0);
207}
208
209namespace {
210 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
211 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000212 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
213 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000214}
215
216/// \brief Collect the macro definitions provided by the given preprocessor
217/// options.
218static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
219 MacroDefinitionsMap &Macros,
220 SmallVectorImpl<StringRef> *MacroNames = 0){
221 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
222 StringRef Macro = PPOpts.Macros[I].first;
223 bool IsUndef = PPOpts.Macros[I].second;
224
225 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
226 StringRef MacroName = MacroPair.first;
227 StringRef MacroBody = MacroPair.second;
228
229 // For an #undef'd macro, we only care about the name.
230 if (IsUndef) {
231 if (MacroNames && !Macros.count(MacroName))
232 MacroNames->push_back(MacroName);
233
234 Macros[MacroName] = std::make_pair("", true);
235 continue;
236 }
237
238 // For a #define'd macro, figure out the actual definition.
239 if (MacroName.size() == Macro.size())
240 MacroBody = "1";
241 else {
242 // Note: GCC drops anything following an end-of-line character.
243 StringRef::size_type End = MacroBody.find_first_of("\n\r");
244 MacroBody = MacroBody.substr(0, End);
245 }
246
247 if (MacroNames && !Macros.count(MacroName))
248 MacroNames->push_back(MacroName);
249 Macros[MacroName] = std::make_pair(MacroBody, false);
250 }
251}
252
253/// \brief Check the preprocessor options deserialized from the control block
254/// against the preprocessor options in an existing preprocessor.
255///
256/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
257static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
258 const PreprocessorOptions &ExistingPPOpts,
259 DiagnosticsEngine *Diags,
260 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000261 std::string &SuggestedPredefines,
262 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000263 // Check macro definitions.
264 MacroDefinitionsMap ASTFileMacros;
265 collectMacroDefinitions(PPOpts, ASTFileMacros);
266 MacroDefinitionsMap ExistingMacros;
267 SmallVector<StringRef, 4> ExistingMacroNames;
268 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
269
270 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
271 // Dig out the macro definition in the existing preprocessor options.
272 StringRef MacroName = ExistingMacroNames[I];
273 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
274
275 // Check whether we know anything about this macro name or not.
276 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
277 = ASTFileMacros.find(MacroName);
278 if (Known == ASTFileMacros.end()) {
279 // FIXME: Check whether this identifier was referenced anywhere in the
280 // AST file. If so, we should reject the AST file. Unfortunately, this
281 // information isn't in the control block. What shall we do about it?
282
283 if (Existing.second) {
284 SuggestedPredefines += "#undef ";
285 SuggestedPredefines += MacroName.str();
286 SuggestedPredefines += '\n';
287 } else {
288 SuggestedPredefines += "#define ";
289 SuggestedPredefines += MacroName.str();
290 SuggestedPredefines += ' ';
291 SuggestedPredefines += Existing.first.str();
292 SuggestedPredefines += '\n';
293 }
294 continue;
295 }
296
297 // If the macro was defined in one but undef'd in the other, we have a
298 // conflict.
299 if (Existing.second != Known->second.second) {
300 if (Diags) {
301 Diags->Report(diag::err_pch_macro_def_undef)
302 << MacroName << Known->second.second;
303 }
304 return true;
305 }
306
307 // If the macro was #undef'd in both, or if the macro bodies are identical,
308 // it's fine.
309 if (Existing.second || Existing.first == Known->second.first)
310 continue;
311
312 // The macro bodies differ; complain.
313 if (Diags) {
314 Diags->Report(diag::err_pch_macro_def_conflict)
315 << MacroName << Known->second.first << Existing.first;
316 }
317 return true;
318 }
319
320 // Check whether we're using predefines.
321 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
322 if (Diags) {
323 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
324 }
325 return true;
326 }
327
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000328 // Detailed record is important since it is used for the module cache hash.
329 if (LangOpts.Modules &&
330 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
331 if (Diags) {
332 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
333 }
334 return true;
335 }
336
Guy Benyei11169dd2012-12-18 14:30:41 +0000337 // Compute the #include and #include_macros lines we need.
338 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
339 StringRef File = ExistingPPOpts.Includes[I];
340 if (File == ExistingPPOpts.ImplicitPCHInclude)
341 continue;
342
343 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
344 != PPOpts.Includes.end())
345 continue;
346
347 SuggestedPredefines += "#include \"";
348 SuggestedPredefines +=
349 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
350 SuggestedPredefines += "\"\n";
351 }
352
353 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
354 StringRef File = ExistingPPOpts.MacroIncludes[I];
355 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
356 File)
357 != PPOpts.MacroIncludes.end())
358 continue;
359
360 SuggestedPredefines += "#__include_macros \"";
361 SuggestedPredefines +=
362 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
363 SuggestedPredefines += "\"\n##\n";
364 }
365
366 return false;
367}
368
369bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
370 bool Complain,
371 std::string &SuggestedPredefines) {
372 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
373
374 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
375 Complain? &Reader.Diags : 0,
376 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000377 SuggestedPredefines,
378 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000379}
380
Guy Benyei11169dd2012-12-18 14:30:41 +0000381void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
382 PP.setCounterValue(Value);
383}
384
385//===----------------------------------------------------------------------===//
386// AST reader implementation
387//===----------------------------------------------------------------------===//
388
389void
390ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
391 DeserializationListener = Listener;
392}
393
394
395
396unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
397 return serialization::ComputeHash(Sel);
398}
399
400
401std::pair<unsigned, unsigned>
402ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
403 using namespace clang::io;
404 unsigned KeyLen = ReadUnalignedLE16(d);
405 unsigned DataLen = ReadUnalignedLE16(d);
406 return std::make_pair(KeyLen, DataLen);
407}
408
409ASTSelectorLookupTrait::internal_key_type
410ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
411 using namespace clang::io;
412 SelectorTable &SelTable = Reader.getContext().Selectors;
413 unsigned N = ReadUnalignedLE16(d);
414 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000415 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000416 if (N == 0)
417 return SelTable.getNullarySelector(FirstII);
418 else if (N == 1)
419 return SelTable.getUnarySelector(FirstII);
420
421 SmallVector<IdentifierInfo *, 16> Args;
422 Args.push_back(FirstII);
423 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000424 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000425
426 return SelTable.getSelector(N, Args.data());
427}
428
429ASTSelectorLookupTrait::data_type
430ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
431 unsigned DataLen) {
432 using namespace clang::io;
433
434 data_type Result;
435
436 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000437 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
438 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
439 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
440 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
441 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
442 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000443
444 // Load instance methods
445 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
446 if (ObjCMethodDecl *Method
447 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
448 Result.Instance.push_back(Method);
449 }
450
451 // Load factory methods
452 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
453 if (ObjCMethodDecl *Method
454 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
455 Result.Factory.push_back(Method);
456 }
457
458 return Result;
459}
460
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000461unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
462 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000463}
464
465std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000466ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 using namespace clang::io;
468 unsigned DataLen = ReadUnalignedLE16(d);
469 unsigned KeyLen = ReadUnalignedLE16(d);
470 return std::make_pair(KeyLen, DataLen);
471}
472
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000473ASTIdentifierLookupTraitBase::internal_key_type
474ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000475 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000476 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000477}
478
Douglas Gregordcf25082013-02-11 18:16:18 +0000479/// \brief Whether the given identifier is "interesting".
480static bool isInterestingIdentifier(IdentifierInfo &II) {
481 return II.isPoisoned() ||
482 II.isExtensionToken() ||
483 II.getObjCOrBuiltinID() ||
484 II.hasRevertedTokenIDToIdentifier() ||
485 II.hadMacroDefinition() ||
486 II.getFETokenInfo<void>();
487}
488
Guy Benyei11169dd2012-12-18 14:30:41 +0000489IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
490 const unsigned char* d,
491 unsigned DataLen) {
492 using namespace clang::io;
493 unsigned RawID = ReadUnalignedLE32(d);
494 bool IsInteresting = RawID & 0x01;
495
496 // Wipe out the "is interesting" bit.
497 RawID = RawID >> 1;
498
499 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
500 if (!IsInteresting) {
501 // For uninteresting identifiers, just build the IdentifierInfo
502 // and associate it with the persistent ID.
503 IdentifierInfo *II = KnownII;
504 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000505 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 KnownII = II;
507 }
508 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000509 if (!II->isFromAST()) {
510 bool WasInteresting = isInterestingIdentifier(*II);
511 II->setIsFromAST();
512 if (WasInteresting)
513 II->setChangedSinceDeserialization();
514 }
515 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000516 return II;
517 }
518
519 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
520 unsigned Bits = ReadUnalignedLE16(d);
521 bool CPlusPlusOperatorKeyword = Bits & 0x01;
522 Bits >>= 1;
523 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
524 Bits >>= 1;
525 bool Poisoned = Bits & 0x01;
526 Bits >>= 1;
527 bool ExtensionToken = Bits & 0x01;
528 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000529 bool hasSubmoduleMacros = Bits & 0x01;
530 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 bool hadMacroDefinition = Bits & 0x01;
532 Bits >>= 1;
533
534 assert(Bits == 0 && "Extra bits in the identifier?");
535 DataLen -= 8;
536
537 // Build the IdentifierInfo itself and link the identifier ID with
538 // the new IdentifierInfo.
539 IdentifierInfo *II = KnownII;
540 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000541 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000542 KnownII = II;
543 }
544 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000545 if (!II->isFromAST()) {
546 bool WasInteresting = isInterestingIdentifier(*II);
547 II->setIsFromAST();
548 if (WasInteresting)
549 II->setChangedSinceDeserialization();
550 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000551
552 // Set or check the various bits in the IdentifierInfo structure.
553 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000554 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 II->RevertTokenIDToIdentifier();
556 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
557 assert(II->isExtensionToken() == ExtensionToken &&
558 "Incorrect extension token flag");
559 (void)ExtensionToken;
560 if (Poisoned)
561 II->setIsPoisoned(true);
562 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
563 "Incorrect C++ operator keyword flag");
564 (void)CPlusPlusOperatorKeyword;
565
566 // If this identifier is a macro, deserialize the macro
567 // definition.
568 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000569 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
570 DataLen -= 4;
571 SmallVector<uint32_t, 8> LocalMacroIDs;
572 if (hasSubmoduleMacros) {
573 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
574 DataLen -= 4;
575 LocalMacroIDs.push_back(LocalMacroID);
576 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000577 DataLen -= 4;
578 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000579
580 if (F.Kind == MK_Module) {
581 for (SmallVectorImpl<uint32_t>::iterator
582 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; ++I) {
583 MacroID MacID = Reader.getGlobalMacroID(F, *I);
584 Reader.addPendingMacroFromModule(II, &F, MacID, F.DirectImportLoc);
585 }
586 } else {
587 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
588 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 }
590
591 Reader.SetIdentifierInfo(ID, II);
592
593 // Read all of the declarations visible at global scope with this
594 // name.
595 if (DataLen > 0) {
596 SmallVector<uint32_t, 4> DeclIDs;
597 for (; DataLen > 0; DataLen -= 4)
598 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
599 Reader.SetGloballyVisibleDecls(II, DeclIDs);
600 }
601
602 return II;
603}
604
605unsigned
606ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
607 llvm::FoldingSetNodeID ID;
608 ID.AddInteger(Key.Kind);
609
610 switch (Key.Kind) {
611 case DeclarationName::Identifier:
612 case DeclarationName::CXXLiteralOperatorName:
613 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
614 break;
615 case DeclarationName::ObjCZeroArgSelector:
616 case DeclarationName::ObjCOneArgSelector:
617 case DeclarationName::ObjCMultiArgSelector:
618 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
619 break;
620 case DeclarationName::CXXOperatorName:
621 ID.AddInteger((OverloadedOperatorKind)Key.Data);
622 break;
623 case DeclarationName::CXXConstructorName:
624 case DeclarationName::CXXDestructorName:
625 case DeclarationName::CXXConversionFunctionName:
626 case DeclarationName::CXXUsingDirective:
627 break;
628 }
629
630 return ID.ComputeHash();
631}
632
633ASTDeclContextNameLookupTrait::internal_key_type
634ASTDeclContextNameLookupTrait::GetInternalKey(
635 const external_key_type& Name) const {
636 DeclNameKey Key;
637 Key.Kind = Name.getNameKind();
638 switch (Name.getNameKind()) {
639 case DeclarationName::Identifier:
640 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
641 break;
642 case DeclarationName::ObjCZeroArgSelector:
643 case DeclarationName::ObjCOneArgSelector:
644 case DeclarationName::ObjCMultiArgSelector:
645 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
646 break;
647 case DeclarationName::CXXOperatorName:
648 Key.Data = Name.getCXXOverloadedOperator();
649 break;
650 case DeclarationName::CXXLiteralOperatorName:
651 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
652 break;
653 case DeclarationName::CXXConstructorName:
654 case DeclarationName::CXXDestructorName:
655 case DeclarationName::CXXConversionFunctionName:
656 case DeclarationName::CXXUsingDirective:
657 Key.Data = 0;
658 break;
659 }
660
661 return Key;
662}
663
664std::pair<unsigned, unsigned>
665ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
666 using namespace clang::io;
667 unsigned KeyLen = ReadUnalignedLE16(d);
668 unsigned DataLen = ReadUnalignedLE16(d);
669 return std::make_pair(KeyLen, DataLen);
670}
671
672ASTDeclContextNameLookupTrait::internal_key_type
673ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
674 using namespace clang::io;
675
676 DeclNameKey Key;
677 Key.Kind = (DeclarationName::NameKind)*d++;
678 switch (Key.Kind) {
679 case DeclarationName::Identifier:
680 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
681 break;
682 case DeclarationName::ObjCZeroArgSelector:
683 case DeclarationName::ObjCOneArgSelector:
684 case DeclarationName::ObjCMultiArgSelector:
685 Key.Data =
686 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
687 .getAsOpaquePtr();
688 break;
689 case DeclarationName::CXXOperatorName:
690 Key.Data = *d++; // OverloadedOperatorKind
691 break;
692 case DeclarationName::CXXLiteralOperatorName:
693 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
694 break;
695 case DeclarationName::CXXConstructorName:
696 case DeclarationName::CXXDestructorName:
697 case DeclarationName::CXXConversionFunctionName:
698 case DeclarationName::CXXUsingDirective:
699 Key.Data = 0;
700 break;
701 }
702
703 return Key;
704}
705
706ASTDeclContextNameLookupTrait::data_type
707ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
708 const unsigned char* d,
709 unsigned DataLen) {
710 using namespace clang::io;
711 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000712 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
713 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000714 return std::make_pair(Start, Start + NumDecls);
715}
716
717bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000718 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 const std::pair<uint64_t, uint64_t> &Offsets,
720 DeclContextInfo &Info) {
721 SavedStreamPosition SavedPosition(Cursor);
722 // First the lexical decls.
723 if (Offsets.first != 0) {
724 Cursor.JumpToBit(Offsets.first);
725
726 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000727 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000729 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 if (RecCode != DECL_CONTEXT_LEXICAL) {
731 Error("Expected lexical block");
732 return true;
733 }
734
Chris Lattner0e6c9402013-01-20 02:38:54 +0000735 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
736 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 }
738
739 // Now the lookup table.
740 if (Offsets.second != 0) {
741 Cursor.JumpToBit(Offsets.second);
742
743 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000744 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000746 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 if (RecCode != DECL_CONTEXT_VISIBLE) {
748 Error("Expected visible lookup table block");
749 return true;
750 }
751 Info.NameLookupTableData
752 = ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +0000753 (const unsigned char *)Blob.data() + Record[0],
754 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000755 ASTDeclContextNameLookupTrait(*this, M));
756 }
757
758 return false;
759}
760
761void ASTReader::Error(StringRef Msg) {
762 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000763 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
764 Diag(diag::note_module_cache_path)
765 << PP.getHeaderSearchInfo().getModuleCachePath();
766 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000767}
768
769void ASTReader::Error(unsigned DiagID,
770 StringRef Arg1, StringRef Arg2) {
771 if (Diags.isDiagnosticInFlight())
772 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
773 else
774 Diag(DiagID) << Arg1 << Arg2;
775}
776
777//===----------------------------------------------------------------------===//
778// Source Manager Deserialization
779//===----------------------------------------------------------------------===//
780
781/// \brief Read the line table in the source manager block.
782/// \returns true if there was an error.
783bool ASTReader::ParseLineTable(ModuleFile &F,
784 SmallVectorImpl<uint64_t> &Record) {
785 unsigned Idx = 0;
786 LineTableInfo &LineTable = SourceMgr.getLineTable();
787
788 // Parse the file names
789 std::map<int, int> FileIDs;
790 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
791 // Extract the file name
792 unsigned FilenameLen = Record[Idx++];
793 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
794 Idx += FilenameLen;
795 MaybeAddSystemRootToFilename(F, Filename);
796 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
797 }
798
799 // Parse the line entries
800 std::vector<LineEntry> Entries;
801 while (Idx < Record.size()) {
802 int FID = Record[Idx++];
803 assert(FID >= 0 && "Serialized line entries for non-local file.");
804 // Remap FileID from 1-based old view.
805 FID += F.SLocEntryBaseID - 1;
806
807 // Extract the line entries
808 unsigned NumEntries = Record[Idx++];
809 assert(NumEntries && "Numentries is 00000");
810 Entries.clear();
811 Entries.reserve(NumEntries);
812 for (unsigned I = 0; I != NumEntries; ++I) {
813 unsigned FileOffset = Record[Idx++];
814 unsigned LineNo = Record[Idx++];
815 int FilenameID = FileIDs[Record[Idx++]];
816 SrcMgr::CharacteristicKind FileKind
817 = (SrcMgr::CharacteristicKind)Record[Idx++];
818 unsigned IncludeOffset = Record[Idx++];
819 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
820 FileKind, IncludeOffset));
821 }
822 LineTable.AddEntry(FileID::get(FID), Entries);
823 }
824
825 return false;
826}
827
828/// \brief Read a source manager block
829bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
830 using namespace SrcMgr;
831
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000832 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000833
834 // Set the source-location entry cursor to the current position in
835 // the stream. This cursor will be used to read the contents of the
836 // source manager block initially, and then lazily read
837 // source-location entries as needed.
838 SLocEntryCursor = F.Stream;
839
840 // The stream itself is going to skip over the source manager block.
841 if (F.Stream.SkipBlock()) {
842 Error("malformed block record in AST file");
843 return true;
844 }
845
846 // Enter the source manager block.
847 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
848 Error("malformed source manager block record in AST file");
849 return true;
850 }
851
852 RecordData Record;
853 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000854 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
855
856 switch (E.Kind) {
857 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
858 case llvm::BitstreamEntry::Error:
859 Error("malformed block record in AST file");
860 return true;
861 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000863 case llvm::BitstreamEntry::Record:
864 // The interesting case.
865 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000867
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000870 StringRef Blob;
871 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 default: // Default behavior: ignore.
873 break;
874
875 case SM_SLOC_FILE_ENTRY:
876 case SM_SLOC_BUFFER_ENTRY:
877 case SM_SLOC_EXPANSION_ENTRY:
878 // Once we hit one of the source location entries, we're done.
879 return false;
880 }
881 }
882}
883
884/// \brief If a header file is not found at the path that we expect it to be
885/// and the PCH file was moved from its original location, try to resolve the
886/// file by assuming that header+PCH were moved together and the header is in
887/// the same place relative to the PCH.
888static std::string
889resolveFileRelativeToOriginalDir(const std::string &Filename,
890 const std::string &OriginalDir,
891 const std::string &CurrDir) {
892 assert(OriginalDir != CurrDir &&
893 "No point trying to resolve the file if the PCH dir didn't change");
894 using namespace llvm::sys;
895 SmallString<128> filePath(Filename);
896 fs::make_absolute(filePath);
897 assert(path::is_absolute(OriginalDir));
898 SmallString<128> currPCHPath(CurrDir);
899
900 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
901 fileDirE = path::end(path::parent_path(filePath));
902 path::const_iterator origDirI = path::begin(OriginalDir),
903 origDirE = path::end(OriginalDir);
904 // Skip the common path components from filePath and OriginalDir.
905 while (fileDirI != fileDirE && origDirI != origDirE &&
906 *fileDirI == *origDirI) {
907 ++fileDirI;
908 ++origDirI;
909 }
910 for (; origDirI != origDirE; ++origDirI)
911 path::append(currPCHPath, "..");
912 path::append(currPCHPath, fileDirI, fileDirE);
913 path::append(currPCHPath, path::filename(Filename));
914 return currPCHPath.str();
915}
916
917bool ASTReader::ReadSLocEntry(int ID) {
918 if (ID == 0)
919 return false;
920
921 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
922 Error("source location entry ID out-of-range for AST file");
923 return true;
924 }
925
926 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
927 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000928 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000929 unsigned BaseOffset = F->SLocEntryBaseOffset;
930
931 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000932 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
933 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 Error("incorrectly-formatted source location entry in AST file");
935 return true;
936 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000937
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000939 StringRef Blob;
940 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 default:
942 Error("incorrectly-formatted source location entry in AST file");
943 return true;
944
945 case SM_SLOC_FILE_ENTRY: {
946 // We will detect whether a file changed and return 'Failure' for it, but
947 // we will also try to fail gracefully by setting up the SLocEntry.
948 unsigned InputID = Record[4];
949 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000950 const FileEntry *File = IF.getFile();
951 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +0000952
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000953 // Note that we only check if a File was returned. If it was out-of-date
954 // we have complained but we will continue creating a FileID to recover
955 // gracefully.
956 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 return true;
958
959 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
960 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
961 // This is the module's main file.
962 IncludeLoc = getImportLocation(F);
963 }
964 SrcMgr::CharacteristicKind
965 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
966 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
967 ID, BaseOffset + Record[0]);
968 SrcMgr::FileInfo &FileInfo =
969 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
970 FileInfo.NumCreatedFIDs = Record[5];
971 if (Record[3])
972 FileInfo.setHasLineDirectives();
973
974 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
975 unsigned NumFileDecls = Record[7];
976 if (NumFileDecls) {
977 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
978 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
979 NumFileDecls));
980 }
981
982 const SrcMgr::ContentCache *ContentCache
983 = SourceMgr.getOrCreateContentCache(File,
984 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
985 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
986 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
987 unsigned Code = SLocEntryCursor.ReadCode();
988 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000989 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000990
991 if (RecCode != SM_SLOC_BUFFER_BLOB) {
992 Error("AST record has invalid code");
993 return true;
994 }
995
996 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +0000997 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 SourceMgr.overrideFileContents(File, Buffer);
999 }
1000
1001 break;
1002 }
1003
1004 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001005 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001006 unsigned Offset = Record[0];
1007 SrcMgr::CharacteristicKind
1008 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1009 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1010 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1011 IncludeLoc = getImportLocation(F);
1012 }
1013 unsigned Code = SLocEntryCursor.ReadCode();
1014 Record.clear();
1015 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001016 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001017
1018 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1019 Error("AST record has invalid code");
1020 return true;
1021 }
1022
1023 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001024 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1026 BaseOffset + Offset, IncludeLoc);
1027 break;
1028 }
1029
1030 case SM_SLOC_EXPANSION_ENTRY: {
1031 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1032 SourceMgr.createExpansionLoc(SpellingLoc,
1033 ReadSourceLocation(*F, Record[2]),
1034 ReadSourceLocation(*F, Record[3]),
1035 Record[4],
1036 ID,
1037 BaseOffset + Record[0]);
1038 break;
1039 }
1040 }
1041
1042 return false;
1043}
1044
1045std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1046 if (ID == 0)
1047 return std::make_pair(SourceLocation(), "");
1048
1049 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1050 Error("source location entry ID out-of-range for AST file");
1051 return std::make_pair(SourceLocation(), "");
1052 }
1053
1054 // Find which module file this entry lands in.
1055 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1056 if (M->Kind != MK_Module)
1057 return std::make_pair(SourceLocation(), "");
1058
1059 // FIXME: Can we map this down to a particular submodule? That would be
1060 // ideal.
1061 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1062}
1063
1064/// \brief Find the location where the module F is imported.
1065SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1066 if (F->ImportLoc.isValid())
1067 return F->ImportLoc;
1068
1069 // Otherwise we have a PCH. It's considered to be "imported" at the first
1070 // location of its includer.
1071 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1072 // Main file is the importer. We assume that it is the first entry in the
1073 // entry table. We can't ask the manager, because at the time of PCH loading
1074 // the main file entry doesn't exist yet.
1075 // The very first entry is the invalid instantiation loc, which takes up
1076 // offsets 0 and 1.
1077 return SourceLocation::getFromRawEncoding(2U);
1078 }
1079 //return F->Loaders[0]->FirstLoc;
1080 return F->ImportedBy[0]->FirstLoc;
1081}
1082
1083/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1084/// specified cursor. Read the abbreviations that are at the top of the block
1085/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001086bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 if (Cursor.EnterSubBlock(BlockID)) {
1088 Error("malformed block record in AST file");
1089 return Failure;
1090 }
1091
1092 while (true) {
1093 uint64_t Offset = Cursor.GetCurrentBitNo();
1094 unsigned Code = Cursor.ReadCode();
1095
1096 // We expect all abbrevs to be at the start of the block.
1097 if (Code != llvm::bitc::DEFINE_ABBREV) {
1098 Cursor.JumpToBit(Offset);
1099 return false;
1100 }
1101 Cursor.ReadAbbrevRecord();
1102 }
1103}
1104
Richard Smithe40f2ba2013-08-07 21:41:30 +00001105Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001106 unsigned &Idx) {
1107 Token Tok;
1108 Tok.startToken();
1109 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1110 Tok.setLength(Record[Idx++]);
1111 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1112 Tok.setIdentifierInfo(II);
1113 Tok.setKind((tok::TokenKind)Record[Idx++]);
1114 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1115 return Tok;
1116}
1117
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001118MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001119 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001120
1121 // Keep track of where we are in the stream, then jump back there
1122 // after reading this macro.
1123 SavedStreamPosition SavedPosition(Stream);
1124
1125 Stream.JumpToBit(Offset);
1126 RecordData Record;
1127 SmallVector<IdentifierInfo*, 16> MacroArgs;
1128 MacroInfo *Macro = 0;
1129
Guy Benyei11169dd2012-12-18 14:30:41 +00001130 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001131 // Advance to the next record, but if we get to the end of the block, don't
1132 // pop it (removing all the abbreviations from the cursor) since we want to
1133 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001134 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001135 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1136
1137 switch (Entry.Kind) {
1138 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1139 case llvm::BitstreamEntry::Error:
1140 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001141 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001142 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001143 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001144 case llvm::BitstreamEntry::Record:
1145 // The interesting case.
1146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 }
1148
1149 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 Record.clear();
1151 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001152 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001154 case PP_MACRO_DIRECTIVE_HISTORY:
1155 return Macro;
1156
Guy Benyei11169dd2012-12-18 14:30:41 +00001157 case PP_MACRO_OBJECT_LIKE:
1158 case PP_MACRO_FUNCTION_LIKE: {
1159 // If we already have a macro, that means that we've hit the end
1160 // of the definition of the macro we were looking for. We're
1161 // done.
1162 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001163 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001165 unsigned NextIndex = 1; // Skip identifier ID.
1166 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001168 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001169 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001171
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1173 // Decode function-like macro info.
1174 bool isC99VarArgs = Record[NextIndex++];
1175 bool isGNUVarArgs = Record[NextIndex++];
1176 bool hasCommaPasting = Record[NextIndex++];
1177 MacroArgs.clear();
1178 unsigned NumArgs = Record[NextIndex++];
1179 for (unsigned i = 0; i != NumArgs; ++i)
1180 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1181
1182 // Install function-like macro info.
1183 MI->setIsFunctionLike();
1184 if (isC99VarArgs) MI->setIsC99Varargs();
1185 if (isGNUVarArgs) MI->setIsGNUVarargs();
1186 if (hasCommaPasting) MI->setHasCommaPasting();
1187 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1188 PP.getPreprocessorAllocator());
1189 }
1190
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 // Remember that we saw this macro last so that we add the tokens that
1192 // form its body to it.
1193 Macro = MI;
1194
1195 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1196 Record[NextIndex]) {
1197 // We have a macro definition. Register the association
1198 PreprocessedEntityID
1199 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1200 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001201 PreprocessingRecord::PPEntityID
1202 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1203 MacroDefinition *PPDef =
1204 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1205 if (PPDef)
1206 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 }
1208
1209 ++NumMacrosRead;
1210 break;
1211 }
1212
1213 case PP_TOKEN: {
1214 // If we see a TOKEN before a PP_MACRO_*, then the file is
1215 // erroneous, just pretend we didn't see this.
1216 if (Macro == 0) break;
1217
John McCallf413f5e2013-05-03 00:10:13 +00001218 unsigned Idx = 0;
1219 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 Macro->AddTokenToBody(Tok);
1221 break;
1222 }
1223 }
1224 }
1225}
1226
1227PreprocessedEntityID
1228ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1229 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1230 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1231 assert(I != M.PreprocessedEntityRemap.end()
1232 && "Invalid index into preprocessed entity index remap");
1233
1234 return LocalID + I->second;
1235}
1236
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001237unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1238 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001239}
1240
1241HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001242HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1243 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1244 FE->getName() };
1245 return ikey;
1246}
Guy Benyei11169dd2012-12-18 14:30:41 +00001247
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001248bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1249 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 return false;
1251
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001252 if (strcmp(a.Filename, b.Filename) == 0)
1253 return true;
1254
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001256 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001257 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1258 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001259 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260}
1261
1262std::pair<unsigned, unsigned>
1263HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1264 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1265 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001266 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001267}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001268
1269HeaderFileInfoTrait::internal_key_type
1270HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1271 internal_key_type ikey;
1272 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1273 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1274 ikey.Filename = (const char *)d;
1275 return ikey;
1276}
1277
Guy Benyei11169dd2012-12-18 14:30:41 +00001278HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001279HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 unsigned DataLen) {
1281 const unsigned char *End = d + DataLen;
1282 using namespace clang::io;
1283 HeaderFileInfo HFI;
1284 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001285 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1286 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001287 HFI.isImport = (Flags >> 5) & 0x01;
1288 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1289 HFI.DirInfo = (Flags >> 2) & 0x03;
1290 HFI.Resolved = (Flags >> 1) & 0x01;
1291 HFI.IndexHeaderMapHeader = Flags & 0x01;
1292 HFI.NumIncludes = ReadUnalignedLE16(d);
1293 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1294 ReadUnalignedLE32(d));
1295 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1296 // The framework offset is 1 greater than the actual offset,
1297 // since 0 is used as an indicator for "no framework name".
1298 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1299 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1300 }
1301
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001302 if (d != End) {
1303 uint32_t LocalSMID = ReadUnalignedLE32(d);
1304 if (LocalSMID) {
1305 // This header is part of a module. Associate it with the module to enable
1306 // implicit module import.
1307 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1308 Module *Mod = Reader.getSubmodule(GlobalSMID);
1309 HFI.isModuleHeader = true;
1310 FileManager &FileMgr = Reader.getFileManager();
1311 ModuleMap &ModMap =
1312 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001313 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001314 }
1315 }
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1318 (void)End;
1319
1320 // This HeaderFileInfo was externally loaded.
1321 HFI.External = true;
1322 return HFI;
1323}
1324
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001325void ASTReader::addPendingMacroFromModule(IdentifierInfo *II,
1326 ModuleFile *M,
1327 GlobalMacroID GMacID,
1328 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001330 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, ImportLoc));
1331}
1332
1333void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1334 ModuleFile *M,
1335 uint64_t MacroDirectivesOffset) {
1336 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1337 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001338}
1339
1340void ASTReader::ReadDefinedMacros() {
1341 // Note that we are loading defined macros.
1342 Deserializing Macros(this);
1343
1344 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1345 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001346 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001347
1348 // If there was no preprocessor block, skip this file.
1349 if (!MacroCursor.getBitStreamReader())
1350 continue;
1351
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001352 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 Cursor.JumpToBit((*I)->MacroStartOffset);
1354
1355 RecordData Record;
1356 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001357 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1358
1359 switch (E.Kind) {
1360 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1361 case llvm::BitstreamEntry::Error:
1362 Error("malformed block record in AST file");
1363 return;
1364 case llvm::BitstreamEntry::EndBlock:
1365 goto NextCursor;
1366
1367 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001368 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001369 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001370 default: // Default behavior: ignore.
1371 break;
1372
1373 case PP_MACRO_OBJECT_LIKE:
1374 case PP_MACRO_FUNCTION_LIKE:
1375 getLocalIdentifier(**I, Record[0]);
1376 break;
1377
1378 case PP_TOKEN:
1379 // Ignore tokens.
1380 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 break;
1383 }
1384 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001385 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 }
1387}
1388
1389namespace {
1390 /// \brief Visitor class used to look up identifirs in an AST file.
1391 class IdentifierLookupVisitor {
1392 StringRef Name;
1393 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001394 unsigned &NumIdentifierLookups;
1395 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001397
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001399 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1400 unsigned &NumIdentifierLookups,
1401 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001402 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001403 NumIdentifierLookups(NumIdentifierLookups),
1404 NumIdentifierLookupHits(NumIdentifierLookupHits),
1405 Found()
1406 {
1407 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001408
1409 static bool visit(ModuleFile &M, void *UserData) {
1410 IdentifierLookupVisitor *This
1411 = static_cast<IdentifierLookupVisitor *>(UserData);
1412
1413 // If we've already searched this module file, skip it now.
1414 if (M.Generation <= This->PriorGeneration)
1415 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001416
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 ASTIdentifierLookupTable *IdTable
1418 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1419 if (!IdTable)
1420 return false;
1421
1422 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1423 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001424 ++This->NumIdentifierLookups;
1425 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 if (Pos == IdTable->end())
1427 return false;
1428
1429 // Dereferencing the iterator has the effect of building the
1430 // IdentifierInfo node and populating it with the various
1431 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001432 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 This->Found = *Pos;
1434 return true;
1435 }
1436
1437 // \brief Retrieve the identifier info found within the module
1438 // files.
1439 IdentifierInfo *getIdentifierInfo() const { return Found; }
1440 };
1441}
1442
1443void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1444 // Note that we are loading an identifier.
1445 Deserializing AnIdentifier(this);
1446
1447 unsigned PriorGeneration = 0;
1448 if (getContext().getLangOpts().Modules)
1449 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001450
1451 // If there is a global index, look there first to determine which modules
1452 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001453 GlobalModuleIndex::HitSet Hits;
1454 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001455 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001456 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1457 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001458 }
1459 }
1460
Douglas Gregor7211ac12013-01-25 23:32:03 +00001461 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001462 NumIdentifierLookups,
1463 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001464 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001465 markIdentifierUpToDate(&II);
1466}
1467
1468void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1469 if (!II)
1470 return;
1471
1472 II->setOutOfDate(false);
1473
1474 // Update the generation for this identifier.
1475 if (getContext().getLangOpts().Modules)
1476 IdentifierGeneration[II] = CurrentGeneration;
1477}
1478
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001479void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1480 const PendingMacroInfo &PMInfo) {
1481 assert(II);
1482
1483 if (PMInfo.M->Kind != MK_Module) {
1484 installPCHMacroDirectives(II, *PMInfo.M,
1485 PMInfo.PCHMacroData.MacroDirectivesOffset);
1486 return;
1487 }
1488
1489 // Module Macro.
1490
1491 GlobalMacroID GMacID = PMInfo.ModuleMacroData.GMacID;
1492 SourceLocation ImportLoc =
1493 SourceLocation::getFromRawEncoding(PMInfo.ModuleMacroData.ImportLoc);
1494
1495 assert(GMacID);
1496 // If this macro has already been loaded, don't do so again.
1497 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1498 return;
1499
1500 MacroInfo *MI = getMacro(GMacID);
1501 SubmoduleID SubModID = MI->getOwningModuleID();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001502 MacroDirective *MD = PP.AllocateDefMacroDirective(MI, ImportLoc,
1503 /*isImported=*/true);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001504
1505 // Determine whether this macro definition is visible.
1506 bool Hidden = false;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001507 Module *Owner = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001508 if (SubModID) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001509 if ((Owner = getSubmodule(SubModID))) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001510 if (Owner->NameVisibility == Module::Hidden) {
1511 // The owning module is not visible, and this macro definition
1512 // should not be, either.
1513 Hidden = true;
1514
1515 // Note that this macro definition was hidden because its owning
1516 // module is not yet visible.
1517 HiddenNamesMap[Owner].push_back(HiddenName(II, MD));
1518 }
1519 }
1520 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001521
1522 if (!Hidden)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001523 installImportedMacro(II, MD, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524}
1525
1526void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1527 ModuleFile &M, uint64_t Offset) {
1528 assert(M.Kind != MK_Module);
1529
1530 BitstreamCursor &Cursor = M.MacroCursor;
1531 SavedStreamPosition SavedPosition(Cursor);
1532 Cursor.JumpToBit(Offset);
1533
1534 llvm::BitstreamEntry Entry =
1535 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1536 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1537 Error("malformed block record in AST file");
1538 return;
1539 }
1540
1541 RecordData Record;
1542 PreprocessorRecordTypes RecType =
1543 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1544 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1545 Error("malformed block record in AST file");
1546 return;
1547 }
1548
1549 // Deserialize the macro directives history in reverse source-order.
1550 MacroDirective *Latest = 0, *Earliest = 0;
1551 unsigned Idx = 0, N = Record.size();
1552 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001553 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001554 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001555 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1556 switch (K) {
1557 case MacroDirective::MD_Define: {
1558 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1559 MacroInfo *MI = getMacro(GMacID);
1560 bool isImported = Record[Idx++];
1561 bool isAmbiguous = Record[Idx++];
1562 DefMacroDirective *DefMD =
1563 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1564 DefMD->setAmbiguous(isAmbiguous);
1565 MD = DefMD;
1566 break;
1567 }
1568 case MacroDirective::MD_Undefine:
1569 MD = PP.AllocateUndefMacroDirective(Loc);
1570 break;
1571 case MacroDirective::MD_Visibility: {
1572 bool isPublic = Record[Idx++];
1573 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1574 break;
1575 }
1576 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001577
1578 if (!Latest)
1579 Latest = MD;
1580 if (Earliest)
1581 Earliest->setPrevious(MD);
1582 Earliest = MD;
1583 }
1584
1585 PP.setLoadedMacroDirective(II, Latest);
1586}
1587
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001588/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001589/// modules.
1590static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001591 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001592 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001593 Module *PrevOwner = 0;
1594 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1595 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001596 SourceManager &SrcMgr = Reader.getSourceManager();
1597 bool PrevInSystem
1598 = PrevOwner? PrevOwner->IsSystem
1599 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1600 bool NewInSystem
1601 = NewOwner? NewOwner->IsSystem
1602 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1603 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001604 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001605 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001606}
1607
1608void ASTReader::installImportedMacro(IdentifierInfo *II, MacroDirective *MD,
1609 Module *Owner) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001610 assert(II && MD);
1611
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001612 DefMacroDirective *DefMD = cast<DefMacroDirective>(MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001613 MacroDirective *Prev = PP.getMacroDirective(II);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001614 if (Prev) {
1615 MacroDirective::DefInfo PrevDef = Prev->getDefinition();
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001616 MacroInfo *PrevMI = PrevDef.getMacroInfo();
1617 MacroInfo *NewMI = DefMD->getInfo();
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00001618 if (NewMI != PrevMI && !PrevMI->isIdenticalTo(*NewMI, PP,
1619 /*Syntactically=*/true)) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001620 // Before marking the macros as ambiguous, check if this is a case where
Douglas Gregor0b202052013-04-12 21:00:54 +00001621 // both macros are in system headers. If so, we trust that the system
1622 // did not get it wrong. This also handles cases where Clang's own
1623 // headers have a different spelling of certain system macros:
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001624 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1625 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
Douglas Gregor0b202052013-04-12 21:00:54 +00001626 if (!areDefinedInSystemModules(PrevMI, NewMI, Owner, *this)) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001627 PrevDef.getDirective()->setAmbiguous(true);
1628 DefMD->setAmbiguous(true);
1629 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001630 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001631 }
1632
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001633 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001634}
1635
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001636InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 // If this ID is bogus, just return an empty input file.
1638 if (ID == 0 || ID > F.InputFilesLoaded.size())
1639 return InputFile();
1640
1641 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001642 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 return F.InputFilesLoaded[ID-1];
1644
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001645 if (F.InputFilesLoaded[ID-1].isNotFound())
1646 return InputFile();
1647
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001649 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 SavedStreamPosition SavedPosition(Cursor);
1651 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1652
1653 unsigned Code = Cursor.ReadCode();
1654 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001655 StringRef Blob;
1656 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 case INPUT_FILE: {
1658 unsigned StoredID = Record[0];
1659 assert(ID == StoredID && "Bogus stored ID or offset");
1660 (void)StoredID;
1661 off_t StoredSize = (off_t)Record[1];
1662 time_t StoredTime = (time_t)Record[2];
1663 bool Overridden = (bool)Record[3];
1664
1665 // Get the file entry for this input file.
Chris Lattner0e6c9402013-01-20 02:38:54 +00001666 StringRef OrigFilename = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 std::string Filename = OrigFilename;
1668 MaybeAddSystemRootToFilename(F, Filename);
1669 const FileEntry *File
1670 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1671 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1672
1673 // If we didn't find the file, resolve it relative to the
1674 // original directory from which this AST file was created.
1675 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1676 F.OriginalDir != CurrentDir) {
1677 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1678 F.OriginalDir,
1679 CurrentDir);
1680 if (!Resolved.empty())
1681 File = FileMgr.getFile(Resolved);
1682 }
1683
1684 // For an overridden file, create a virtual file with the stored
1685 // size/timestamp.
1686 if (Overridden && File == 0) {
1687 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1688 }
1689
1690 if (File == 0) {
1691 if (Complain) {
1692 std::string ErrorStr = "could not find file '";
1693 ErrorStr += Filename;
1694 ErrorStr += "' referenced by AST file";
1695 Error(ErrorStr.c_str());
1696 }
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001697 // Record that we didn't find the file.
1698 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
Guy Benyei11169dd2012-12-18 14:30:41 +00001699 return InputFile();
1700 }
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 // Check if there was a request to override the contents of the file
1703 // that was part of the precompiled header. Overridding such a file
1704 // can lead to problems when lexing using the source locations from the
1705 // PCH.
1706 SourceManager &SM = getSourceManager();
1707 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001708 if (Complain)
1709 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 // After emitting the diagnostic, recover by disabling the override so
1711 // that the original file will be used.
1712 SM.disableFileContentsOverride(File);
1713 // The FileEntry is a virtual file entry with the size of the contents
1714 // that would override the original contents. Set it to the original's
1715 // size/time.
1716 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1717 StoredSize, StoredTime);
1718 }
1719
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001720 bool IsOutOfDate = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00001721
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001722 // For an overridden file, there is nothing to validate.
1723 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001724#if !defined(LLVM_ON_WIN32)
1725 // In our regression testing, the Windows file system seems to
1726 // have inconsistent modification times that sometimes
1727 // erroneously trigger this error-handling path.
1728 || StoredTime != File->getModificationTime()
1729#endif
1730 )) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00001731 if (Complain) {
Ben Langmuire82630d2014-01-17 00:19:09 +00001732 // Build a list of the PCH imports that got us here (in reverse).
1733 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1734 while (ImportStack.back()->ImportedBy.size() > 0)
1735 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1736
1737 // The top-level PCH is stale.
1738 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1739 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1740
1741 // Print the import stack.
1742 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1743 Diag(diag::note_pch_required_by)
1744 << Filename << ImportStack[0]->FileName;
1745 for (unsigned I = 1; I < ImportStack.size(); ++I)
1746 Diag(diag::note_pch_required_by)
1747 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor940e8052013-05-10 22:15:13 +00001748 }
Ben Langmuire82630d2014-01-17 00:19:09 +00001749
1750 if (!Diags.isDiagnosticInFlight())
1751 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001752 }
1753
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001754 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 }
1756
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001757 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1758
1759 // Note that we've loaded this input file.
1760 F.InputFilesLoaded[ID-1] = IF;
1761 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 }
1763 }
1764
1765 return InputFile();
1766}
1767
1768const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1769 ModuleFile &M = ModuleMgr.getPrimaryModule();
1770 std::string Filename = filenameStrRef;
1771 MaybeAddSystemRootToFilename(M, Filename);
1772 const FileEntry *File = FileMgr.getFile(Filename);
1773 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1774 M.OriginalDir != CurrentDir) {
1775 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1776 M.OriginalDir,
1777 CurrentDir);
1778 if (!resolved.empty())
1779 File = FileMgr.getFile(resolved);
1780 }
1781
1782 return File;
1783}
1784
1785/// \brief If we are loading a relocatable PCH file, and the filename is
1786/// not an absolute path, add the system root to the beginning of the file
1787/// name.
1788void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1789 std::string &Filename) {
1790 // If this is not a relocatable PCH file, there's nothing to do.
1791 if (!M.RelocatablePCH)
1792 return;
1793
1794 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1795 return;
1796
1797 if (isysroot.empty()) {
1798 // If no system root was given, default to '/'
1799 Filename.insert(Filename.begin(), '/');
1800 return;
1801 }
1802
1803 unsigned Length = isysroot.size();
1804 if (isysroot[Length - 1] != '/')
1805 Filename.insert(Filename.begin(), '/');
1806
1807 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1808}
1809
1810ASTReader::ASTReadResult
1811ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001812 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001814 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00001815
1816 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1817 Error("malformed block record in AST file");
1818 return Failure;
1819 }
1820
1821 // Read all of the records and blocks in the control block.
1822 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001823 while (1) {
1824 llvm::BitstreamEntry Entry = Stream.advance();
1825
1826 switch (Entry.Kind) {
1827 case llvm::BitstreamEntry::Error:
1828 Error("malformed block record in AST file");
1829 return Failure;
1830 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001831 // Validate all of the non-system input files.
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 if (!DisableValidation) {
1833 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuir3d4417c2014-02-07 17:31:11 +00001834 // All user input files reside at the index range [0, Record[1]), and
1835 // system input files reside at [Record[1], Record[0]).
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001836 // Record is the one from INPUT_FILE_OFFSETS.
Ben Langmuir3d4417c2014-02-07 17:31:11 +00001837 unsigned NumInputs = Record[0];
1838 unsigned NumUserInputs = Record[1];
1839 unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
1840 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001841 InputFile IF = getInputFile(F, I+1, Complain);
1842 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001844 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001846 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001847
1848 case llvm::BitstreamEntry::SubBlock:
1849 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 case INPUT_FILES_BLOCK_ID:
1851 F.InputFilesCursor = Stream;
1852 if (Stream.SkipBlock() || // Skip with the main cursor
1853 // Read the abbreviations
1854 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
1855 Error("malformed block record in AST file");
1856 return Failure;
1857 }
1858 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001859
Guy Benyei11169dd2012-12-18 14:30:41 +00001860 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001861 if (Stream.SkipBlock()) {
1862 Error("malformed block record in AST file");
1863 return Failure;
1864 }
1865 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001867
1868 case llvm::BitstreamEntry::Record:
1869 // The interesting case.
1870 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 }
1872
1873 // Read and process a record.
1874 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001875 StringRef Blob;
1876 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 case METADATA: {
1878 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1879 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00001880 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
1881 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 return VersionMismatch;
1883 }
1884
1885 bool hasErrors = Record[5];
1886 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
1887 Diag(diag::err_pch_with_compiler_errors);
1888 return HadErrors;
1889 }
1890
1891 F.RelocatablePCH = Record[4];
1892
1893 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001894 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1896 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00001897 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00001898 return VersionMismatch;
1899 }
1900 break;
1901 }
1902
1903 case IMPORTS: {
1904 // Load each of the imported PCH files.
1905 unsigned Idx = 0, N = Record.size();
1906 while (Idx < N) {
1907 // Read information about the AST file.
1908 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1909 // The import location will be the local one for now; we will adjust
1910 // all import locations of module imports after the global source
1911 // location info are setup.
1912 SourceLocation ImportLoc =
1913 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00001914 off_t StoredSize = (off_t)Record[Idx++];
1915 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 unsigned Length = Record[Idx++];
1917 SmallString<128> ImportedFile(Record.begin() + Idx,
1918 Record.begin() + Idx + Length);
1919 Idx += Length;
1920
1921 // Load the AST file.
1922 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00001923 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00001924 ClientLoadCapabilities)) {
1925 case Failure: return Failure;
1926 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00001927 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 case OutOfDate: return OutOfDate;
1929 case VersionMismatch: return VersionMismatch;
1930 case ConfigurationMismatch: return ConfigurationMismatch;
1931 case HadErrors: return HadErrors;
1932 case Success: break;
1933 }
1934 }
1935 break;
1936 }
1937
1938 case LANGUAGE_OPTIONS: {
1939 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
1940 if (Listener && &F == *ModuleMgr.begin() &&
1941 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001942 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001943 return ConfigurationMismatch;
1944 break;
1945 }
1946
1947 case TARGET_OPTIONS: {
1948 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1949 if (Listener && &F == *ModuleMgr.begin() &&
1950 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001951 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001952 return ConfigurationMismatch;
1953 break;
1954 }
1955
1956 case DIAGNOSTIC_OPTIONS: {
1957 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1958 if (Listener && &F == *ModuleMgr.begin() &&
1959 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001960 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001961 return ConfigurationMismatch;
1962 break;
1963 }
1964
1965 case FILE_SYSTEM_OPTIONS: {
1966 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1967 if (Listener && &F == *ModuleMgr.begin() &&
1968 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001969 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001970 return ConfigurationMismatch;
1971 break;
1972 }
1973
1974 case HEADER_SEARCH_OPTIONS: {
1975 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1976 if (Listener && &F == *ModuleMgr.begin() &&
1977 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001978 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001979 return ConfigurationMismatch;
1980 break;
1981 }
1982
1983 case PREPROCESSOR_OPTIONS: {
1984 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
1985 if (Listener && &F == *ModuleMgr.begin() &&
1986 ParsePreprocessorOptions(Record, Complain, *Listener,
1987 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001988 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00001989 return ConfigurationMismatch;
1990 break;
1991 }
1992
1993 case ORIGINAL_FILE:
1994 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00001995 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
1997 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
1998 break;
1999
2000 case ORIGINAL_FILE_ID:
2001 F.OriginalSourceFileID = FileID::get(Record[0]);
2002 break;
2003
2004 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002005 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002006 break;
2007
2008 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002009 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 F.InputFilesLoaded.resize(Record[0]);
2011 break;
2012 }
2013 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002014}
2015
2016bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002017 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002018
2019 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2020 Error("malformed block record in AST file");
2021 return true;
2022 }
2023
2024 // Read all of the records and blocks for the AST file.
2025 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002026 while (1) {
2027 llvm::BitstreamEntry Entry = Stream.advance();
2028
2029 switch (Entry.Kind) {
2030 case llvm::BitstreamEntry::Error:
2031 Error("error at end of module block in AST file");
2032 return true;
2033 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002034 // Outside of C++, we do not store a lookup map for the translation unit.
2035 // Instead, mark it as needing a lookup map to be built if this module
2036 // contains any declarations lexically within it (which it always does!).
2037 // This usually has no cost, since we very rarely need the lookup map for
2038 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002040 if (DC->hasExternalLexicalStorage() &&
2041 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002043
Guy Benyei11169dd2012-12-18 14:30:41 +00002044 return false;
2045 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002046 case llvm::BitstreamEntry::SubBlock:
2047 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 case DECLTYPES_BLOCK_ID:
2049 // We lazily load the decls block, but we want to set up the
2050 // DeclsCursor cursor to point into it. Clone our current bitcode
2051 // cursor to it, enter the block and read the abbrevs in that block.
2052 // With the main cursor, we just skip over it.
2053 F.DeclsCursor = Stream;
2054 if (Stream.SkipBlock() || // Skip with the main cursor.
2055 // Read the abbrevs.
2056 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2057 Error("malformed block record in AST file");
2058 return true;
2059 }
2060 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002061
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 case DECL_UPDATES_BLOCK_ID:
2063 if (Stream.SkipBlock()) {
2064 Error("malformed block record in AST file");
2065 return true;
2066 }
2067 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002068
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 case PREPROCESSOR_BLOCK_ID:
2070 F.MacroCursor = Stream;
2071 if (!PP.getExternalSource())
2072 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002073
Guy Benyei11169dd2012-12-18 14:30:41 +00002074 if (Stream.SkipBlock() ||
2075 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2076 Error("malformed block record in AST file");
2077 return true;
2078 }
2079 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2080 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002081
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 case PREPROCESSOR_DETAIL_BLOCK_ID:
2083 F.PreprocessorDetailCursor = Stream;
2084 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002085 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002087 Error("malformed preprocessor detail record in AST file");
2088 return true;
2089 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002091 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2092
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 if (!PP.getPreprocessingRecord())
2094 PP.createPreprocessingRecord();
2095 if (!PP.getPreprocessingRecord()->getExternalSource())
2096 PP.getPreprocessingRecord()->SetExternalSource(*this);
2097 break;
2098
2099 case SOURCE_MANAGER_BLOCK_ID:
2100 if (ReadSourceManagerBlock(F))
2101 return true;
2102 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002103
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 case SUBMODULE_BLOCK_ID:
2105 if (ReadSubmoduleBlock(F))
2106 return true;
2107 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002108
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002110 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 if (Stream.SkipBlock() ||
2112 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2113 Error("malformed comments block in AST file");
2114 return true;
2115 }
2116 CommentsCursors.push_back(std::make_pair(C, &F));
2117 break;
2118 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002119
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002121 if (Stream.SkipBlock()) {
2122 Error("malformed block record in AST file");
2123 return true;
2124 }
2125 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 }
2127 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002128
2129 case llvm::BitstreamEntry::Record:
2130 // The interesting case.
2131 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 }
2133
2134 // Read and process a record.
2135 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002136 StringRef Blob;
2137 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 default: // Default behavior: ignore.
2139 break;
2140
2141 case TYPE_OFFSET: {
2142 if (F.LocalNumTypes != 0) {
2143 Error("duplicate TYPE_OFFSET record in AST file");
2144 return true;
2145 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002146 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 F.LocalNumTypes = Record[0];
2148 unsigned LocalBaseTypeIndex = Record[1];
2149 F.BaseTypeIndex = getTotalNumTypes();
2150
2151 if (F.LocalNumTypes > 0) {
2152 // Introduce the global -> local mapping for types within this module.
2153 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2154
2155 // Introduce the local -> global mapping for types within this module.
2156 F.TypeRemap.insertOrReplace(
2157 std::make_pair(LocalBaseTypeIndex,
2158 F.BaseTypeIndex - LocalBaseTypeIndex));
2159
2160 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2161 }
2162 break;
2163 }
2164
2165 case DECL_OFFSET: {
2166 if (F.LocalNumDecls != 0) {
2167 Error("duplicate DECL_OFFSET record in AST file");
2168 return true;
2169 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002170 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 F.LocalNumDecls = Record[0];
2172 unsigned LocalBaseDeclID = Record[1];
2173 F.BaseDeclID = getTotalNumDecls();
2174
2175 if (F.LocalNumDecls > 0) {
2176 // Introduce the global -> local mapping for declarations within this
2177 // module.
2178 GlobalDeclMap.insert(
2179 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2180
2181 // Introduce the local -> global mapping for declarations within this
2182 // module.
2183 F.DeclRemap.insertOrReplace(
2184 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2185
2186 // Introduce the global -> local mapping for declarations within this
2187 // module.
2188 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2189
2190 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2191 }
2192 break;
2193 }
2194
2195 case TU_UPDATE_LEXICAL: {
2196 DeclContext *TU = Context.getTranslationUnitDecl();
2197 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002198 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002200 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 TU->setHasExternalLexicalStorage(true);
2202 break;
2203 }
2204
2205 case UPDATE_VISIBLE: {
2206 unsigned Idx = 0;
2207 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2208 ASTDeclContextNameLookupTable *Table =
2209 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002210 (const unsigned char *)Blob.data() + Record[Idx++],
2211 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 ASTDeclContextNameLookupTrait(*this, F));
2213 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2214 DeclContext *TU = Context.getTranslationUnitDecl();
2215 F.DeclContextInfos[TU].NameLookupTableData = Table;
2216 TU->setHasExternalVisibleStorage(true);
2217 } else
2218 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2219 break;
2220 }
2221
2222 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002223 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 if (Record[0]) {
2225 F.IdentifierLookupTable
2226 = ASTIdentifierLookupTable::Create(
2227 (const unsigned char *)F.IdentifierTableData + Record[0],
2228 (const unsigned char *)F.IdentifierTableData,
2229 ASTIdentifierLookupTrait(*this, F));
2230
2231 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2232 }
2233 break;
2234
2235 case IDENTIFIER_OFFSET: {
2236 if (F.LocalNumIdentifiers != 0) {
2237 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2238 return true;
2239 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002240 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 F.LocalNumIdentifiers = Record[0];
2242 unsigned LocalBaseIdentifierID = Record[1];
2243 F.BaseIdentifierID = getTotalNumIdentifiers();
2244
2245 if (F.LocalNumIdentifiers > 0) {
2246 // Introduce the global -> local mapping for identifiers within this
2247 // module.
2248 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2249 &F));
2250
2251 // Introduce the local -> global mapping for identifiers within this
2252 // module.
2253 F.IdentifierRemap.insertOrReplace(
2254 std::make_pair(LocalBaseIdentifierID,
2255 F.BaseIdentifierID - LocalBaseIdentifierID));
2256
2257 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2258 + F.LocalNumIdentifiers);
2259 }
2260 break;
2261 }
2262
Ben Langmuir332aafe2014-01-31 01:06:56 +00002263 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002265 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 break;
2267
2268 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002269 if (SpecialTypes.empty()) {
2270 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2271 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2272 break;
2273 }
2274
2275 if (SpecialTypes.size() != Record.size()) {
2276 Error("invalid special-types record");
2277 return true;
2278 }
2279
2280 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2281 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2282 if (!SpecialTypes[I])
2283 SpecialTypes[I] = ID;
2284 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2285 // merge step?
2286 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 break;
2288
2289 case STATISTICS:
2290 TotalNumStatements += Record[0];
2291 TotalNumMacros += Record[1];
2292 TotalLexicalDeclContexts += Record[2];
2293 TotalVisibleDeclContexts += Record[3];
2294 break;
2295
2296 case UNUSED_FILESCOPED_DECLS:
2297 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2298 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2299 break;
2300
2301 case DELEGATING_CTORS:
2302 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2303 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2304 break;
2305
2306 case WEAK_UNDECLARED_IDENTIFIERS:
2307 if (Record.size() % 4 != 0) {
2308 Error("invalid weak identifiers record");
2309 return true;
2310 }
2311
2312 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2313 // files. This isn't the way to do it :)
2314 WeakUndeclaredIdentifiers.clear();
2315
2316 // Translate the weak, undeclared identifiers into global IDs.
2317 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2318 WeakUndeclaredIdentifiers.push_back(
2319 getGlobalIdentifierID(F, Record[I++]));
2320 WeakUndeclaredIdentifiers.push_back(
2321 getGlobalIdentifierID(F, Record[I++]));
2322 WeakUndeclaredIdentifiers.push_back(
2323 ReadSourceLocation(F, Record, I).getRawEncoding());
2324 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2325 }
2326 break;
2327
Richard Smith78165b52013-01-10 23:43:47 +00002328 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002330 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 break;
2332
2333 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002334 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 F.LocalNumSelectors = Record[0];
2336 unsigned LocalBaseSelectorID = Record[1];
2337 F.BaseSelectorID = getTotalNumSelectors();
2338
2339 if (F.LocalNumSelectors > 0) {
2340 // Introduce the global -> local mapping for selectors within this
2341 // module.
2342 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2343
2344 // Introduce the local -> global mapping for selectors within this
2345 // module.
2346 F.SelectorRemap.insertOrReplace(
2347 std::make_pair(LocalBaseSelectorID,
2348 F.BaseSelectorID - LocalBaseSelectorID));
2349
2350 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2351 }
2352 break;
2353 }
2354
2355 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002356 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 if (Record[0])
2358 F.SelectorLookupTable
2359 = ASTSelectorLookupTable::Create(
2360 F.SelectorLookupTableData + Record[0],
2361 F.SelectorLookupTableData,
2362 ASTSelectorLookupTrait(*this, F));
2363 TotalNumMethodPoolEntries += Record[1];
2364 break;
2365
2366 case REFERENCED_SELECTOR_POOL:
2367 if (!Record.empty()) {
2368 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2369 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2370 Record[Idx++]));
2371 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2372 getRawEncoding());
2373 }
2374 }
2375 break;
2376
2377 case PP_COUNTER_VALUE:
2378 if (!Record.empty() && Listener)
2379 Listener->ReadCounter(F, Record[0]);
2380 break;
2381
2382 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002383 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 F.NumFileSortedDecls = Record[0];
2385 break;
2386
2387 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002388 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 F.LocalNumSLocEntries = Record[0];
2390 unsigned SLocSpaceSize = Record[1];
2391 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2392 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2393 SLocSpaceSize);
2394 // Make our entry in the range map. BaseID is negative and growing, so
2395 // we invert it. Because we invert it, though, we need the other end of
2396 // the range.
2397 unsigned RangeStart =
2398 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2399 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2400 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2401
2402 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2403 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2404 GlobalSLocOffsetMap.insert(
2405 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2406 - SLocSpaceSize,&F));
2407
2408 // Initialize the remapping table.
2409 // Invalid stays invalid.
2410 F.SLocRemap.insert(std::make_pair(0U, 0));
2411 // This module. Base was 2 when being compiled.
2412 F.SLocRemap.insert(std::make_pair(2U,
2413 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2414
2415 TotalNumSLocEntries += F.LocalNumSLocEntries;
2416 break;
2417 }
2418
2419 case MODULE_OFFSET_MAP: {
2420 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002421 const unsigned char *Data = (const unsigned char*)Blob.data();
2422 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002423
2424 // Continuous range maps we may be updating in our module.
2425 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2426 ContinuousRangeMap<uint32_t, int, 2>::Builder
2427 IdentifierRemap(F.IdentifierRemap);
2428 ContinuousRangeMap<uint32_t, int, 2>::Builder
2429 MacroRemap(F.MacroRemap);
2430 ContinuousRangeMap<uint32_t, int, 2>::Builder
2431 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2432 ContinuousRangeMap<uint32_t, int, 2>::Builder
2433 SubmoduleRemap(F.SubmoduleRemap);
2434 ContinuousRangeMap<uint32_t, int, 2>::Builder
2435 SelectorRemap(F.SelectorRemap);
2436 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2437 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2438
2439 while(Data < DataEnd) {
2440 uint16_t Len = io::ReadUnalignedLE16(Data);
2441 StringRef Name = StringRef((const char*)Data, Len);
2442 Data += Len;
2443 ModuleFile *OM = ModuleMgr.lookup(Name);
2444 if (!OM) {
2445 Error("SourceLocation remap refers to unknown module");
2446 return true;
2447 }
2448
2449 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2450 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2451 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2452 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2453 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2454 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2455 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2456 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2457
2458 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2459 SLocRemap.insert(std::make_pair(SLocOffset,
2460 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2461 IdentifierRemap.insert(
2462 std::make_pair(IdentifierIDOffset,
2463 OM->BaseIdentifierID - IdentifierIDOffset));
2464 MacroRemap.insert(std::make_pair(MacroIDOffset,
2465 OM->BaseMacroID - MacroIDOffset));
2466 PreprocessedEntityRemap.insert(
2467 std::make_pair(PreprocessedEntityIDOffset,
2468 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2469 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2470 OM->BaseSubmoduleID - SubmoduleIDOffset));
2471 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2472 OM->BaseSelectorID - SelectorIDOffset));
2473 DeclRemap.insert(std::make_pair(DeclIDOffset,
2474 OM->BaseDeclID - DeclIDOffset));
2475
2476 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2477 OM->BaseTypeIndex - TypeIndexOffset));
2478
2479 // Global -> local mappings.
2480 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2481 }
2482 break;
2483 }
2484
2485 case SOURCE_MANAGER_LINE_TABLE:
2486 if (ParseLineTable(F, Record))
2487 return true;
2488 break;
2489
2490 case SOURCE_LOCATION_PRELOADS: {
2491 // Need to transform from the local view (1-based IDs) to the global view,
2492 // which is based off F.SLocEntryBaseID.
2493 if (!F.PreloadSLocEntries.empty()) {
2494 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2495 return true;
2496 }
2497
2498 F.PreloadSLocEntries.swap(Record);
2499 break;
2500 }
2501
2502 case EXT_VECTOR_DECLS:
2503 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2504 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2505 break;
2506
2507 case VTABLE_USES:
2508 if (Record.size() % 3 != 0) {
2509 Error("Invalid VTABLE_USES record");
2510 return true;
2511 }
2512
2513 // Later tables overwrite earlier ones.
2514 // FIXME: Modules will have some trouble with this. This is clearly not
2515 // the right way to do this.
2516 VTableUses.clear();
2517
2518 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2519 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2520 VTableUses.push_back(
2521 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2522 VTableUses.push_back(Record[Idx++]);
2523 }
2524 break;
2525
2526 case DYNAMIC_CLASSES:
2527 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2528 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2529 break;
2530
2531 case PENDING_IMPLICIT_INSTANTIATIONS:
2532 if (PendingInstantiations.size() % 2 != 0) {
2533 Error("Invalid existing PendingInstantiations");
2534 return true;
2535 }
2536
2537 if (Record.size() % 2 != 0) {
2538 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2539 return true;
2540 }
2541
2542 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2543 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2544 PendingInstantiations.push_back(
2545 ReadSourceLocation(F, Record, I).getRawEncoding());
2546 }
2547 break;
2548
2549 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002550 if (Record.size() != 2) {
2551 Error("Invalid SEMA_DECL_REFS block");
2552 return true;
2553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2555 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2556 break;
2557
2558 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002559 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2560 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2561 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002562
2563 unsigned LocalBasePreprocessedEntityID = Record[0];
2564
2565 unsigned StartingID;
2566 if (!PP.getPreprocessingRecord())
2567 PP.createPreprocessingRecord();
2568 if (!PP.getPreprocessingRecord()->getExternalSource())
2569 PP.getPreprocessingRecord()->SetExternalSource(*this);
2570 StartingID
2571 = PP.getPreprocessingRecord()
2572 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2573 F.BasePreprocessedEntityID = StartingID;
2574
2575 if (F.NumPreprocessedEntities > 0) {
2576 // Introduce the global -> local mapping for preprocessed entities in
2577 // this module.
2578 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2579
2580 // Introduce the local -> global mapping for preprocessed entities in
2581 // this module.
2582 F.PreprocessedEntityRemap.insertOrReplace(
2583 std::make_pair(LocalBasePreprocessedEntityID,
2584 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2585 }
2586
2587 break;
2588 }
2589
2590 case DECL_UPDATE_OFFSETS: {
2591 if (Record.size() % 2 != 0) {
2592 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2593 return true;
2594 }
2595 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2596 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2597 .push_back(std::make_pair(&F, Record[I+1]));
2598 break;
2599 }
2600
2601 case DECL_REPLACEMENTS: {
2602 if (Record.size() % 3 != 0) {
2603 Error("invalid DECL_REPLACEMENTS block in AST file");
2604 return true;
2605 }
2606 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2607 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2608 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2609 break;
2610 }
2611
2612 case OBJC_CATEGORIES_MAP: {
2613 if (F.LocalNumObjCCategoriesInMap != 0) {
2614 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2615 return true;
2616 }
2617
2618 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002619 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 break;
2621 }
2622
2623 case OBJC_CATEGORIES:
2624 F.ObjCCategories.swap(Record);
2625 break;
2626
2627 case CXX_BASE_SPECIFIER_OFFSETS: {
2628 if (F.LocalNumCXXBaseSpecifiers != 0) {
2629 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2630 return true;
2631 }
2632
2633 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002634 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2636 break;
2637 }
2638
2639 case DIAG_PRAGMA_MAPPINGS:
2640 if (F.PragmaDiagMappings.empty())
2641 F.PragmaDiagMappings.swap(Record);
2642 else
2643 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2644 Record.begin(), Record.end());
2645 break;
2646
2647 case CUDA_SPECIAL_DECL_REFS:
2648 // Later tables overwrite earlier ones.
2649 // FIXME: Modules will have trouble with this.
2650 CUDASpecialDeclRefs.clear();
2651 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2652 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2653 break;
2654
2655 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 if (Record[0]) {
2659 F.HeaderFileInfoTable
2660 = HeaderFileInfoLookupTable::Create(
2661 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2662 (const unsigned char *)F.HeaderFileInfoTableData,
2663 HeaderFileInfoTrait(*this, F,
2664 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002665 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002666
2667 PP.getHeaderSearchInfo().SetExternalSource(this);
2668 if (!PP.getHeaderSearchInfo().getExternalLookup())
2669 PP.getHeaderSearchInfo().SetExternalLookup(this);
2670 }
2671 break;
2672 }
2673
2674 case FP_PRAGMA_OPTIONS:
2675 // Later tables overwrite earlier ones.
2676 FPPragmaOptions.swap(Record);
2677 break;
2678
2679 case OPENCL_EXTENSIONS:
2680 // Later tables overwrite earlier ones.
2681 OpenCLExtensions.swap(Record);
2682 break;
2683
2684 case TENTATIVE_DEFINITIONS:
2685 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2686 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2687 break;
2688
2689 case KNOWN_NAMESPACES:
2690 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2691 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2692 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002693
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002694 case UNDEFINED_BUT_USED:
2695 if (UndefinedButUsed.size() % 2 != 0) {
2696 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002697 return true;
2698 }
2699
2700 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002701 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00002702 return true;
2703 }
2704 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002705 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2706 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00002707 ReadSourceLocation(F, Record, I).getRawEncoding());
2708 }
2709 break;
2710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 case IMPORTED_MODULES: {
2712 if (F.Kind != MK_Module) {
2713 // If we aren't loading a module (which has its own exports), make
2714 // all of the imported modules visible.
2715 // FIXME: Deal with macros-only imports.
2716 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2717 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2718 ImportedModules.push_back(GlobalID);
2719 }
2720 }
2721 break;
2722 }
2723
2724 case LOCAL_REDECLARATIONS: {
2725 F.RedeclarationChains.swap(Record);
2726 break;
2727 }
2728
2729 case LOCAL_REDECLARATIONS_MAP: {
2730 if (F.LocalNumRedeclarationsInMap != 0) {
2731 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2732 return true;
2733 }
2734
2735 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002736 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 break;
2738 }
2739
2740 case MERGED_DECLARATIONS: {
2741 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2742 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2743 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2744 for (unsigned N = Record[Idx++]; N > 0; --N)
2745 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2746 }
2747 break;
2748 }
2749
2750 case MACRO_OFFSET: {
2751 if (F.LocalNumMacros != 0) {
2752 Error("duplicate MACRO_OFFSET record in AST file");
2753 return true;
2754 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002755 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 F.LocalNumMacros = Record[0];
2757 unsigned LocalBaseMacroID = Record[1];
2758 F.BaseMacroID = getTotalNumMacros();
2759
2760 if (F.LocalNumMacros > 0) {
2761 // Introduce the global -> local mapping for macros within this module.
2762 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2763
2764 // Introduce the local -> global mapping for macros within this module.
2765 F.MacroRemap.insertOrReplace(
2766 std::make_pair(LocalBaseMacroID,
2767 F.BaseMacroID - LocalBaseMacroID));
2768
2769 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2770 }
2771 break;
2772 }
2773
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002774 case MACRO_TABLE: {
2775 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 break;
2777 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00002778
2779 case LATE_PARSED_TEMPLATE: {
2780 LateParsedTemplates.append(Record.begin(), Record.end());
2781 break;
2782 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 }
2784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002785}
2786
Douglas Gregorc1489562013-02-12 23:36:21 +00002787/// \brief Move the given method to the back of the global list of methods.
2788static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2789 // Find the entry for this selector in the method pool.
2790 Sema::GlobalMethodPool::iterator Known
2791 = S.MethodPool.find(Method->getSelector());
2792 if (Known == S.MethodPool.end())
2793 return;
2794
2795 // Retrieve the appropriate method list.
2796 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2797 : Known->second.second;
2798 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002799 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00002800 if (!Found) {
2801 if (List->Method == Method) {
2802 Found = true;
2803 } else {
2804 // Keep searching.
2805 continue;
2806 }
2807 }
2808
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002809 if (List->getNext())
2810 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00002811 else
2812 List->Method = Method;
2813 }
2814}
2815
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00002816void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002817 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2818 switch (Names[I].getKind()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00002819 case HiddenName::Declaration: {
2820 Decl *D = Names[I].getDecl();
2821 bool wasHidden = D->Hidden;
2822 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00002823
Douglas Gregorc1489562013-02-12 23:36:21 +00002824 if (wasHidden && SemaObj) {
2825 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
2826 moveMethodToBackOfGlobalList(*SemaObj, Method);
2827 }
2828 }
2829 break;
2830 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 case HiddenName::MacroVisibility: {
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002832 std::pair<IdentifierInfo *, MacroDirective *> Macro = Names[I].getMacro();
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00002833 installImportedMacro(Macro.first, Macro.second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 break;
2835 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 }
2837 }
2838}
2839
2840void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00002841 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00002842 SourceLocation ImportLoc,
2843 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002845 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002846 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002848 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00002849
2850 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002851 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 // there is nothing more to do.
2853 continue;
2854 }
2855
2856 if (!Mod->isAvailable()) {
2857 // Modules that aren't available cannot be made visible.
2858 continue;
2859 }
2860
2861 // Update the module's name visibility.
2862 Mod->NameVisibility = NameVisibility;
2863
2864 // If we've already deserialized any names from this module,
2865 // mark them as visible.
2866 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2867 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00002868 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 HiddenNamesMap.erase(Hidden);
2870 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00002873 SmallVector<Module *, 16> Exports;
2874 Mod->getExportedModules(Exports);
2875 for (SmallVectorImpl<Module *>::iterator
2876 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
2877 Module *Exported = *I;
2878 if (Visited.insert(Exported))
2879 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 }
Douglas Gregorfb912652013-03-20 21:10:35 +00002881
2882 // Detect any conflicts.
2883 if (Complain) {
2884 assert(ImportLoc.isValid() && "Missing import location");
2885 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2886 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
2887 Diag(ImportLoc, diag::warn_module_conflict)
2888 << Mod->getFullModuleName()
2889 << Mod->Conflicts[I].Other->getFullModuleName()
2890 << Mod->Conflicts[I].Message;
2891 // FIXME: Need note where the other module was imported.
2892 }
2893 }
2894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 }
2896}
2897
Douglas Gregore060e572013-01-25 01:03:03 +00002898bool ASTReader::loadGlobalIndex() {
2899 if (GlobalIndex)
2900 return false;
2901
2902 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
2903 !Context.getLangOpts().Modules)
2904 return true;
2905
2906 // Try to load the global index.
2907 TriedLoadingGlobalIndex = true;
2908 StringRef ModuleCachePath
2909 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
2910 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00002911 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00002912 if (!Result.first)
2913 return true;
2914
2915 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00002916 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00002917 return false;
2918}
2919
2920bool ASTReader::isGlobalIndexUnavailable() const {
2921 return Context.getLangOpts().Modules && UseGlobalIndex &&
2922 !hasGlobalIndex() && TriedLoadingGlobalIndex;
2923}
2924
Guy Benyei11169dd2012-12-18 14:30:41 +00002925ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2926 ModuleKind Type,
2927 SourceLocation ImportLoc,
2928 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002929 llvm::SaveAndRestore<SourceLocation>
2930 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
2931
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 // Bump the generation number.
2933 unsigned PreviousGeneration = CurrentGeneration++;
2934
2935 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002936 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
2938 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002939 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 ClientLoadCapabilities)) {
2941 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00002942 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 case OutOfDate:
2944 case VersionMismatch:
2945 case ConfigurationMismatch:
2946 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00002947 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
2948 Context.getLangOpts().Modules
2949 ? &PP.getHeaderSearchInfo().getModuleMap()
2950 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00002951
2952 // If we find that any modules are unusable, the global index is going
2953 // to be out-of-date. Just remove it.
2954 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00002955 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 return ReadResult;
2957
2958 case Success:
2959 break;
2960 }
2961
2962 // Here comes stuff that we only do once the entire chain is loaded.
2963
2964 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002965 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2966 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 M != MEnd; ++M) {
2968 ModuleFile &F = *M->Mod;
2969
2970 // Read the AST block.
2971 if (ReadASTBlock(F))
2972 return Failure;
2973
2974 // Once read, set the ModuleFile bit base offset and update the size in
2975 // bits of all files we've seen.
2976 F.GlobalBitOffset = TotalModulesSizeInBits;
2977 TotalModulesSizeInBits += F.SizeInBits;
2978 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2979
2980 // Preload SLocEntries.
2981 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
2982 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2983 // Load it through the SourceManager and don't call ReadSLocEntry()
2984 // directly because the entry may have already been loaded in which case
2985 // calling ReadSLocEntry() directly would trigger an assertion in
2986 // SourceManager.
2987 SourceMgr.getLoadedSLocEntryByID(Index);
2988 }
2989 }
2990
Douglas Gregor603cd862013-03-22 18:50:14 +00002991 // Setup the import locations and notify the module manager that we've
2992 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002993 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
2994 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 M != MEnd; ++M) {
2996 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00002997
2998 ModuleMgr.moduleFileAccepted(&F);
2999
3000 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003001 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 if (!M->ImportedBy)
3003 F.ImportLoc = M->ImportLoc;
3004 else
3005 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3006 M->ImportLoc.getRawEncoding());
3007 }
3008
3009 // Mark all of the identifiers in the identifier table as being out of date,
3010 // so that various accessors know to check the loaded modules when the
3011 // identifier is used.
3012 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3013 IdEnd = PP.getIdentifierTable().end();
3014 Id != IdEnd; ++Id)
3015 Id->second->setOutOfDate(true);
3016
3017 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003018 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3019 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3021 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003022
3023 switch (Unresolved.Kind) {
3024 case UnresolvedModuleRef::Conflict:
3025 if (ResolvedMod) {
3026 Module::Conflict Conflict;
3027 Conflict.Other = ResolvedMod;
3028 Conflict.Message = Unresolved.String.str();
3029 Unresolved.Mod->Conflicts.push_back(Conflict);
3030 }
3031 continue;
3032
3033 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 if (ResolvedMod)
3035 Unresolved.Mod->Imports.push_back(ResolvedMod);
3036 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003037
Douglas Gregorfb912652013-03-20 21:10:35 +00003038 case UnresolvedModuleRef::Export:
3039 if (ResolvedMod || Unresolved.IsWildcard)
3040 Unresolved.Mod->Exports.push_back(
3041 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3042 continue;
3043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003045 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003046
3047 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3048 // Might be unnecessary as use declarations are only used to build the
3049 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003050
3051 InitializeContext();
3052
Richard Smith3d8e97e2013-10-18 06:54:39 +00003053 if (SemaObj)
3054 UpdateSema();
3055
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 if (DeserializationListener)
3057 DeserializationListener->ReaderInitialized(this);
3058
3059 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3060 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3061 PrimaryModule.OriginalSourceFileID
3062 = FileID::get(PrimaryModule.SLocEntryBaseID
3063 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3064
3065 // If this AST file is a precompiled preamble, then set the
3066 // preamble file ID of the source manager to the file source file
3067 // from which the preamble was built.
3068 if (Type == MK_Preamble) {
3069 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3070 } else if (Type == MK_MainFile) {
3071 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3072 }
3073 }
3074
3075 // For any Objective-C class definitions we have already loaded, make sure
3076 // that we load any additional categories.
3077 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3078 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3079 ObjCClassesLoaded[I],
3080 PreviousGeneration);
3081 }
Douglas Gregore060e572013-01-25 01:03:03 +00003082
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 return Success;
3084}
3085
3086ASTReader::ASTReadResult
3087ASTReader::ReadASTCore(StringRef FileName,
3088 ModuleKind Type,
3089 SourceLocation ImportLoc,
3090 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003091 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003092 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 unsigned ClientLoadCapabilities) {
3094 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003096 ModuleManager::AddModuleResult AddResult
3097 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3098 CurrentGeneration, ExpectedSize, ExpectedModTime,
3099 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003100
Douglas Gregor7029ce12013-03-19 00:28:20 +00003101 switch (AddResult) {
3102 case ModuleManager::AlreadyLoaded:
3103 return Success;
3104
3105 case ModuleManager::NewlyLoaded:
3106 // Load module file below.
3107 break;
3108
3109 case ModuleManager::Missing:
3110 // The module file was missing; if the client handle handle, that, return
3111 // it.
3112 if (ClientLoadCapabilities & ARR_Missing)
3113 return Missing;
3114
3115 // Otherwise, return an error.
3116 {
3117 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3118 + ErrorStr;
3119 Error(Msg);
3120 }
3121 return Failure;
3122
3123 case ModuleManager::OutOfDate:
3124 // We couldn't load the module file because it is out-of-date. If the
3125 // client can handle out-of-date, return it.
3126 if (ClientLoadCapabilities & ARR_OutOfDate)
3127 return OutOfDate;
3128
3129 // Otherwise, return an error.
3130 {
3131 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3132 + ErrorStr;
3133 Error(Msg);
3134 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 return Failure;
3136 }
3137
Douglas Gregor7029ce12013-03-19 00:28:20 +00003138 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003139
3140 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3141 // module?
3142 if (FileName != "-") {
3143 CurrentDir = llvm::sys::path::parent_path(FileName);
3144 if (CurrentDir.empty()) CurrentDir = ".";
3145 }
3146
3147 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003148 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 Stream.init(F.StreamFile);
3150 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3151
3152 // Sniff for the signature.
3153 if (Stream.Read(8) != 'C' ||
3154 Stream.Read(8) != 'P' ||
3155 Stream.Read(8) != 'C' ||
3156 Stream.Read(8) != 'H') {
3157 Diag(diag::err_not_a_pch_file) << FileName;
3158 return Failure;
3159 }
3160
3161 // This is used for compatibility with older PCH formats.
3162 bool HaveReadControlBlock = false;
3163
Chris Lattnerefa77172013-01-20 00:00:22 +00003164 while (1) {
3165 llvm::BitstreamEntry Entry = Stream.advance();
3166
3167 switch (Entry.Kind) {
3168 case llvm::BitstreamEntry::Error:
3169 case llvm::BitstreamEntry::EndBlock:
3170 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 Error("invalid record at top-level of AST file");
3172 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003173
3174 case llvm::BitstreamEntry::SubBlock:
3175 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 }
3177
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003179 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3181 if (Stream.ReadBlockInfoBlock()) {
3182 Error("malformed BlockInfoBlock in AST file");
3183 return Failure;
3184 }
3185 break;
3186 case CONTROL_BLOCK_ID:
3187 HaveReadControlBlock = true;
3188 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3189 case Success:
3190 break;
3191
3192 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003193 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 case OutOfDate: return OutOfDate;
3195 case VersionMismatch: return VersionMismatch;
3196 case ConfigurationMismatch: return ConfigurationMismatch;
3197 case HadErrors: return HadErrors;
3198 }
3199 break;
3200 case AST_BLOCK_ID:
3201 if (!HaveReadControlBlock) {
3202 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003203 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 return VersionMismatch;
3205 }
3206
3207 // Record that we've loaded this module.
3208 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3209 return Success;
3210
3211 default:
3212 if (Stream.SkipBlock()) {
3213 Error("malformed block record in AST file");
3214 return Failure;
3215 }
3216 break;
3217 }
3218 }
3219
3220 return Success;
3221}
3222
3223void ASTReader::InitializeContext() {
3224 // If there's a listener, notify them that we "read" the translation unit.
3225 if (DeserializationListener)
3226 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3227 Context.getTranslationUnitDecl());
3228
3229 // Make sure we load the declaration update records for the translation unit,
3230 // if there are any.
3231 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3232 Context.getTranslationUnitDecl());
3233
3234 // FIXME: Find a better way to deal with collisions between these
3235 // built-in types. Right now, we just ignore the problem.
3236
3237 // Load the special types.
3238 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3239 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3240 if (!Context.CFConstantStringTypeDecl)
3241 Context.setCFConstantStringType(GetType(String));
3242 }
3243
3244 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3245 QualType FileType = GetType(File);
3246 if (FileType.isNull()) {
3247 Error("FILE type is NULL");
3248 return;
3249 }
3250
3251 if (!Context.FILEDecl) {
3252 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3253 Context.setFILEDecl(Typedef->getDecl());
3254 else {
3255 const TagType *Tag = FileType->getAs<TagType>();
3256 if (!Tag) {
3257 Error("Invalid FILE type in AST file");
3258 return;
3259 }
3260 Context.setFILEDecl(Tag->getDecl());
3261 }
3262 }
3263 }
3264
3265 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3266 QualType Jmp_bufType = GetType(Jmp_buf);
3267 if (Jmp_bufType.isNull()) {
3268 Error("jmp_buf type is NULL");
3269 return;
3270 }
3271
3272 if (!Context.jmp_bufDecl) {
3273 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3274 Context.setjmp_bufDecl(Typedef->getDecl());
3275 else {
3276 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3277 if (!Tag) {
3278 Error("Invalid jmp_buf type in AST file");
3279 return;
3280 }
3281 Context.setjmp_bufDecl(Tag->getDecl());
3282 }
3283 }
3284 }
3285
3286 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3287 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3288 if (Sigjmp_bufType.isNull()) {
3289 Error("sigjmp_buf type is NULL");
3290 return;
3291 }
3292
3293 if (!Context.sigjmp_bufDecl) {
3294 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3295 Context.setsigjmp_bufDecl(Typedef->getDecl());
3296 else {
3297 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3298 assert(Tag && "Invalid sigjmp_buf type in AST file");
3299 Context.setsigjmp_bufDecl(Tag->getDecl());
3300 }
3301 }
3302 }
3303
3304 if (unsigned ObjCIdRedef
3305 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3306 if (Context.ObjCIdRedefinitionType.isNull())
3307 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3308 }
3309
3310 if (unsigned ObjCClassRedef
3311 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3312 if (Context.ObjCClassRedefinitionType.isNull())
3313 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3314 }
3315
3316 if (unsigned ObjCSelRedef
3317 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3318 if (Context.ObjCSelRedefinitionType.isNull())
3319 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3320 }
3321
3322 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3323 QualType Ucontext_tType = GetType(Ucontext_t);
3324 if (Ucontext_tType.isNull()) {
3325 Error("ucontext_t type is NULL");
3326 return;
3327 }
3328
3329 if (!Context.ucontext_tDecl) {
3330 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3331 Context.setucontext_tDecl(Typedef->getDecl());
3332 else {
3333 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3334 assert(Tag && "Invalid ucontext_t type in AST file");
3335 Context.setucontext_tDecl(Tag->getDecl());
3336 }
3337 }
3338 }
3339 }
3340
3341 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3342
3343 // If there were any CUDA special declarations, deserialize them.
3344 if (!CUDASpecialDeclRefs.empty()) {
3345 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3346 Context.setcudaConfigureCallDecl(
3347 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3348 }
3349
3350 // Re-export any modules that were imported by a non-module AST file.
3351 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3352 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003353 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003354 /*ImportLoc=*/SourceLocation(),
3355 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 }
3357 ImportedModules.clear();
3358}
3359
3360void ASTReader::finalizeForWriting() {
3361 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3362 HiddenEnd = HiddenNamesMap.end();
3363 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003364 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 }
3366 HiddenNamesMap.clear();
3367}
3368
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003369/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3370/// cursor into the start of the given block ID, returning false on success and
3371/// true on failure.
3372static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003373 while (1) {
3374 llvm::BitstreamEntry Entry = Cursor.advance();
3375 switch (Entry.Kind) {
3376 case llvm::BitstreamEntry::Error:
3377 case llvm::BitstreamEntry::EndBlock:
3378 return true;
3379
3380 case llvm::BitstreamEntry::Record:
3381 // Ignore top-level records.
3382 Cursor.skipRecord(Entry.ID);
3383 break;
3384
3385 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003386 if (Entry.ID == BlockID) {
3387 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003388 return true;
3389 // Found it!
3390 return false;
3391 }
3392
3393 if (Cursor.SkipBlock())
3394 return true;
3395 }
3396 }
3397}
3398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399/// \brief Retrieve the name of the original source file name
3400/// directly from the AST file, without actually loading the AST
3401/// file.
3402std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3403 FileManager &FileMgr,
3404 DiagnosticsEngine &Diags) {
3405 // Open the AST file.
3406 std::string ErrStr;
3407 OwningPtr<llvm::MemoryBuffer> Buffer;
3408 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3409 if (!Buffer) {
3410 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3411 return std::string();
3412 }
3413
3414 // Initialize the stream
3415 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003416 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3418 (const unsigned char *)Buffer->getBufferEnd());
3419 Stream.init(StreamFile);
3420
3421 // Sniff for the signature.
3422 if (Stream.Read(8) != 'C' ||
3423 Stream.Read(8) != 'P' ||
3424 Stream.Read(8) != 'C' ||
3425 Stream.Read(8) != 'H') {
3426 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3427 return std::string();
3428 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003429
Chris Lattnere7b154b2013-01-19 21:39:22 +00003430 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003431 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003432 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3433 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003434 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003435
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003436 // Scan for ORIGINAL_FILE inside the control block.
3437 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003438 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003439 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003440 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3441 return std::string();
3442
3443 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3444 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3445 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003447
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003449 StringRef Blob;
3450 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3451 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003453}
3454
3455namespace {
3456 class SimplePCHValidator : public ASTReaderListener {
3457 const LangOptions &ExistingLangOpts;
3458 const TargetOptions &ExistingTargetOpts;
3459 const PreprocessorOptions &ExistingPPOpts;
3460 FileManager &FileMgr;
3461
3462 public:
3463 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3464 const TargetOptions &ExistingTargetOpts,
3465 const PreprocessorOptions &ExistingPPOpts,
3466 FileManager &FileMgr)
3467 : ExistingLangOpts(ExistingLangOpts),
3468 ExistingTargetOpts(ExistingTargetOpts),
3469 ExistingPPOpts(ExistingPPOpts),
3470 FileMgr(FileMgr)
3471 {
3472 }
3473
3474 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3475 bool Complain) {
3476 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3477 }
3478 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3479 bool Complain) {
3480 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3481 }
3482 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3483 bool Complain,
3484 std::string &SuggestedPredefines) {
3485 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003486 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 }
3488 };
3489}
3490
3491bool ASTReader::readASTFileControlBlock(StringRef Filename,
3492 FileManager &FileMgr,
3493 ASTReaderListener &Listener) {
3494 // Open the AST file.
3495 std::string ErrStr;
3496 OwningPtr<llvm::MemoryBuffer> Buffer;
3497 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3498 if (!Buffer) {
3499 return true;
3500 }
3501
3502 // Initialize the stream
3503 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003504 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3506 (const unsigned char *)Buffer->getBufferEnd());
3507 Stream.init(StreamFile);
3508
3509 // Sniff for the signature.
3510 if (Stream.Read(8) != 'C' ||
3511 Stream.Read(8) != 'P' ||
3512 Stream.Read(8) != 'C' ||
3513 Stream.Read(8) != 'H') {
3514 return true;
3515 }
3516
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003517 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003518 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003519 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003520
3521 bool NeedsInputFiles = Listener.needsInputFileVisitation();
3522 BitstreamCursor InputFilesCursor;
3523 if (NeedsInputFiles) {
3524 InputFilesCursor = Stream;
3525 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3526 return true;
3527
3528 // Read the abbreviations
3529 while (true) {
3530 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3531 unsigned Code = InputFilesCursor.ReadCode();
3532
3533 // We expect all abbrevs to be at the start of the block.
3534 if (Code != llvm::bitc::DEFINE_ABBREV) {
3535 InputFilesCursor.JumpToBit(Offset);
3536 break;
3537 }
3538 InputFilesCursor.ReadAbbrevRecord();
3539 }
3540 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003541
3542 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003544 while (1) {
3545 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3546 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3547 return false;
3548
3549 if (Entry.Kind != llvm::BitstreamEntry::Record)
3550 return true;
3551
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003553 StringRef Blob;
3554 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003555 switch ((ControlRecordTypes)RecCode) {
3556 case METADATA: {
3557 if (Record[0] != VERSION_MAJOR)
3558 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003559
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003560 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003561 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003562
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003563 break;
3564 }
3565 case LANGUAGE_OPTIONS:
3566 if (ParseLanguageOptions(Record, false, Listener))
3567 return true;
3568 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003569
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003570 case TARGET_OPTIONS:
3571 if (ParseTargetOptions(Record, false, Listener))
3572 return true;
3573 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003574
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003575 case DIAGNOSTIC_OPTIONS:
3576 if (ParseDiagnosticOptions(Record, false, Listener))
3577 return true;
3578 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003579
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003580 case FILE_SYSTEM_OPTIONS:
3581 if (ParseFileSystemOptions(Record, false, Listener))
3582 return true;
3583 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003584
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003585 case HEADER_SEARCH_OPTIONS:
3586 if (ParseHeaderSearchOptions(Record, false, Listener))
3587 return true;
3588 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003589
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003590 case PREPROCESSOR_OPTIONS: {
3591 std::string IgnoredSuggestedPredefines;
3592 if (ParsePreprocessorOptions(Record, false, Listener,
3593 IgnoredSuggestedPredefines))
3594 return true;
3595 break;
3596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003597
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003598 case INPUT_FILE_OFFSETS: {
3599 if (!NeedsInputFiles)
3600 break;
3601
3602 unsigned NumInputFiles = Record[0];
3603 unsigned NumUserFiles = Record[1];
3604 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3605 for (unsigned I = 0; I != NumInputFiles; ++I) {
3606 // Go find this input file.
3607 bool isSystemFile = I >= NumUserFiles;
3608 BitstreamCursor &Cursor = InputFilesCursor;
3609 SavedStreamPosition SavedPosition(Cursor);
3610 Cursor.JumpToBit(InputFileOffs[I]);
3611
3612 unsigned Code = Cursor.ReadCode();
3613 RecordData Record;
3614 StringRef Blob;
3615 bool shouldContinue = false;
3616 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3617 case INPUT_FILE:
3618 shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3619 break;
3620 }
3621 if (!shouldContinue)
3622 break;
3623 }
3624 break;
3625 }
3626
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003627 default:
3628 // No other validation to perform.
3629 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 }
3631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003632}
3633
3634
3635bool ASTReader::isAcceptableASTFile(StringRef Filename,
3636 FileManager &FileMgr,
3637 const LangOptions &LangOpts,
3638 const TargetOptions &TargetOpts,
3639 const PreprocessorOptions &PPOpts) {
3640 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3641 return !readASTFileControlBlock(Filename, FileMgr, validator);
3642}
3643
3644bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3645 // Enter the submodule block.
3646 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3647 Error("malformed submodule block record in AST file");
3648 return true;
3649 }
3650
3651 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3652 bool First = true;
3653 Module *CurrentModule = 0;
3654 RecordData Record;
3655 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003656 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3657
3658 switch (Entry.Kind) {
3659 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3660 case llvm::BitstreamEntry::Error:
3661 Error("malformed block record in AST file");
3662 return true;
3663 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003664 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003665 case llvm::BitstreamEntry::Record:
3666 // The interesting case.
3667 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003669
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003671 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003672 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003673 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003674 default: // Default behavior: ignore.
3675 break;
3676
3677 case SUBMODULE_DEFINITION: {
3678 if (First) {
3679 Error("missing submodule metadata record at beginning of block");
3680 return true;
3681 }
3682
Douglas Gregor8d932422013-03-20 03:59:18 +00003683 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 Error("malformed module definition");
3685 return true;
3686 }
3687
Chris Lattner0e6c9402013-01-20 02:38:54 +00003688 StringRef Name = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3690 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3691 bool IsFramework = Record[2];
3692 bool IsExplicit = Record[3];
3693 bool IsSystem = Record[4];
3694 bool InferSubmodules = Record[5];
3695 bool InferExplicitSubmodules = Record[6];
3696 bool InferExportWildcard = Record[7];
Douglas Gregor8d932422013-03-20 03:59:18 +00003697 bool ConfigMacrosExhaustive = Record[8];
3698
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 Module *ParentModule = 0;
3700 if (Parent)
3701 ParentModule = getSubmodule(Parent);
3702
3703 // Retrieve this (sub)module from the module map, creating it if
3704 // necessary.
3705 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3706 IsFramework,
3707 IsExplicit).first;
3708 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3709 if (GlobalIndex >= SubmodulesLoaded.size() ||
3710 SubmodulesLoaded[GlobalIndex]) {
3711 Error("too many submodules");
3712 return true;
3713 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003714
Douglas Gregor7029ce12013-03-19 00:28:20 +00003715 if (!ParentModule) {
3716 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3717 if (CurFile != F.File) {
3718 if (!Diags.isDiagnosticInFlight()) {
3719 Diag(diag::err_module_file_conflict)
3720 << CurrentModule->getTopLevelModuleName()
3721 << CurFile->getName()
3722 << F.File->getName();
3723 }
3724 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003725 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003726 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003727
3728 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003729 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003730
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 CurrentModule->IsFromModuleFile = true;
3732 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3733 CurrentModule->InferSubmodules = InferSubmodules;
3734 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3735 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00003736 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 if (DeserializationListener)
3738 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3739
3740 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003741
Douglas Gregorfb912652013-03-20 21:10:35 +00003742 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003743 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00003744 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00003745 CurrentModule->UnresolvedConflicts.clear();
3746 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 break;
3748 }
3749
3750 case SUBMODULE_UMBRELLA_HEADER: {
3751 if (First) {
3752 Error("missing submodule metadata record at beginning of block");
3753 return true;
3754 }
3755
3756 if (!CurrentModule)
3757 break;
3758
Chris Lattner0e6c9402013-01-20 02:38:54 +00003759 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 if (!CurrentModule->getUmbrellaHeader())
3761 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3762 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3763 Error("mismatched umbrella headers in submodule");
3764 return true;
3765 }
3766 }
3767 break;
3768 }
3769
3770 case SUBMODULE_HEADER: {
3771 if (First) {
3772 Error("missing submodule metadata record at beginning of block");
3773 return true;
3774 }
3775
3776 if (!CurrentModule)
3777 break;
3778
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00003779 // We lazily associate headers with their modules via the HeaderInfoTable.
3780 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3781 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 break;
3783 }
3784
3785 case SUBMODULE_EXCLUDED_HEADER: {
3786 if (First) {
3787 Error("missing submodule metadata record at beginning of block");
3788 return true;
3789 }
3790
3791 if (!CurrentModule)
3792 break;
3793
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00003794 // We lazily associate headers with their modules via the HeaderInfoTable.
3795 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3796 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 break;
3798 }
3799
Lawrence Crowlb53e5482013-06-20 21:14:14 +00003800 case SUBMODULE_PRIVATE_HEADER: {
3801 if (First) {
3802 Error("missing submodule metadata record at beginning of block");
3803 return true;
3804 }
3805
3806 if (!CurrentModule)
3807 break;
3808
3809 // We lazily associate headers with their modules via the HeaderInfoTable.
3810 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3811 // of complete filenames or remove it entirely.
3812 break;
3813 }
3814
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 case SUBMODULE_TOPHEADER: {
3816 if (First) {
3817 Error("missing submodule metadata record at beginning of block");
3818 return true;
3819 }
3820
3821 if (!CurrentModule)
3822 break;
3823
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00003824 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 break;
3826 }
3827
3828 case SUBMODULE_UMBRELLA_DIR: {
3829 if (First) {
3830 Error("missing submodule metadata record at beginning of block");
3831 return true;
3832 }
3833
3834 if (!CurrentModule)
3835 break;
3836
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00003838 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 if (!CurrentModule->getUmbrellaDir())
3840 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3841 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3842 Error("mismatched umbrella directories in submodule");
3843 return true;
3844 }
3845 }
3846 break;
3847 }
3848
3849 case SUBMODULE_METADATA: {
3850 if (!First) {
3851 Error("submodule metadata record not at beginning of block");
3852 return true;
3853 }
3854 First = false;
3855
3856 F.BaseSubmoduleID = getTotalNumSubmodules();
3857 F.LocalNumSubmodules = Record[0];
3858 unsigned LocalBaseSubmoduleID = Record[1];
3859 if (F.LocalNumSubmodules > 0) {
3860 // Introduce the global -> local mapping for submodules within this
3861 // module.
3862 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3863
3864 // Introduce the local -> global mapping for submodules within this
3865 // module.
3866 F.SubmoduleRemap.insertOrReplace(
3867 std::make_pair(LocalBaseSubmoduleID,
3868 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3869
3870 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3871 }
3872 break;
3873 }
3874
3875 case SUBMODULE_IMPORTS: {
3876 if (First) {
3877 Error("missing submodule metadata record at beginning of block");
3878 return true;
3879 }
3880
3881 if (!CurrentModule)
3882 break;
3883
3884 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00003885 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 Unresolved.File = &F;
3887 Unresolved.Mod = CurrentModule;
3888 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00003889 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00003891 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 }
3893 break;
3894 }
3895
3896 case SUBMODULE_EXPORTS: {
3897 if (First) {
3898 Error("missing submodule metadata record at beginning of block");
3899 return true;
3900 }
3901
3902 if (!CurrentModule)
3903 break;
3904
3905 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00003906 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 Unresolved.File = &F;
3908 Unresolved.Mod = CurrentModule;
3909 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00003910 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00003912 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 }
3914
3915 // Once we've loaded the set of exports, there's no reason to keep
3916 // the parsed, unresolved exports around.
3917 CurrentModule->UnresolvedExports.clear();
3918 break;
3919 }
3920 case SUBMODULE_REQUIRES: {
3921 if (First) {
3922 Error("missing submodule metadata record at beginning of block");
3923 return true;
3924 }
3925
3926 if (!CurrentModule)
3927 break;
3928
Richard Smitha3feee22013-10-28 22:18:19 +00003929 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003930 Context.getTargetInfo());
3931 break;
3932 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003933
3934 case SUBMODULE_LINK_LIBRARY:
3935 if (First) {
3936 Error("missing submodule metadata record at beginning of block");
3937 return true;
3938 }
3939
3940 if (!CurrentModule)
3941 break;
3942
3943 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00003944 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003945 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00003946
3947 case SUBMODULE_CONFIG_MACRO:
3948 if (First) {
3949 Error("missing submodule metadata record at beginning of block");
3950 return true;
3951 }
3952
3953 if (!CurrentModule)
3954 break;
3955
3956 CurrentModule->ConfigMacros.push_back(Blob.str());
3957 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00003958
3959 case SUBMODULE_CONFLICT: {
3960 if (First) {
3961 Error("missing submodule metadata record at beginning of block");
3962 return true;
3963 }
3964
3965 if (!CurrentModule)
3966 break;
3967
3968 UnresolvedModuleRef Unresolved;
3969 Unresolved.File = &F;
3970 Unresolved.Mod = CurrentModule;
3971 Unresolved.ID = Record[0];
3972 Unresolved.Kind = UnresolvedModuleRef::Conflict;
3973 Unresolved.IsWildcard = false;
3974 Unresolved.String = Blob;
3975 UnresolvedModuleRefs.push_back(Unresolved);
3976 break;
3977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 }
3979 }
3980}
3981
3982/// \brief Parse the record that corresponds to a LangOptions data
3983/// structure.
3984///
3985/// This routine parses the language options from the AST file and then gives
3986/// them to the AST listener if one is set.
3987///
3988/// \returns true if the listener deems the file unacceptable, false otherwise.
3989bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3990 bool Complain,
3991 ASTReaderListener &Listener) {
3992 LangOptions LangOpts;
3993 unsigned Idx = 0;
3994#define LANGOPT(Name, Bits, Default, Description) \
3995 LangOpts.Name = Record[Idx++];
3996#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3997 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3998#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00003999#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4000#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004001
4002 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4003 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4004 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4005
4006 unsigned Length = Record[Idx++];
4007 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4008 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004009
4010 Idx += Length;
4011
4012 // Comment options.
4013 for (unsigned N = Record[Idx++]; N; --N) {
4014 LangOpts.CommentOpts.BlockCommandNames.push_back(
4015 ReadString(Record, Idx));
4016 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004017 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004018
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 return Listener.ReadLanguageOptions(LangOpts, Complain);
4020}
4021
4022bool ASTReader::ParseTargetOptions(const RecordData &Record,
4023 bool Complain,
4024 ASTReaderListener &Listener) {
4025 unsigned Idx = 0;
4026 TargetOptions TargetOpts;
4027 TargetOpts.Triple = ReadString(Record, Idx);
4028 TargetOpts.CPU = ReadString(Record, Idx);
4029 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4031 for (unsigned N = Record[Idx++]; N; --N) {
4032 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4033 }
4034 for (unsigned N = Record[Idx++]; N; --N) {
4035 TargetOpts.Features.push_back(ReadString(Record, Idx));
4036 }
4037
4038 return Listener.ReadTargetOptions(TargetOpts, Complain);
4039}
4040
4041bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4042 ASTReaderListener &Listener) {
4043 DiagnosticOptions DiagOpts;
4044 unsigned Idx = 0;
4045#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4046#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4047 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4048#include "clang/Basic/DiagnosticOptions.def"
4049
4050 for (unsigned N = Record[Idx++]; N; --N) {
4051 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4052 }
4053
4054 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4055}
4056
4057bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4058 ASTReaderListener &Listener) {
4059 FileSystemOptions FSOpts;
4060 unsigned Idx = 0;
4061 FSOpts.WorkingDir = ReadString(Record, Idx);
4062 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4063}
4064
4065bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4066 bool Complain,
4067 ASTReaderListener &Listener) {
4068 HeaderSearchOptions HSOpts;
4069 unsigned Idx = 0;
4070 HSOpts.Sysroot = ReadString(Record, Idx);
4071
4072 // Include entries.
4073 for (unsigned N = Record[Idx++]; N; --N) {
4074 std::string Path = ReadString(Record, Idx);
4075 frontend::IncludeDirGroup Group
4076 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 bool IsFramework = Record[Idx++];
4078 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004080 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 }
4082
4083 // System header prefixes.
4084 for (unsigned N = Record[Idx++]; N; --N) {
4085 std::string Prefix = ReadString(Record, Idx);
4086 bool IsSystemHeader = Record[Idx++];
4087 HSOpts.SystemHeaderPrefixes.push_back(
4088 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4089 }
4090
4091 HSOpts.ResourceDir = ReadString(Record, Idx);
4092 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4093 HSOpts.DisableModuleHash = Record[Idx++];
4094 HSOpts.UseBuiltinIncludes = Record[Idx++];
4095 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4096 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4097 HSOpts.UseLibcxx = Record[Idx++];
4098
4099 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4100}
4101
4102bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4103 bool Complain,
4104 ASTReaderListener &Listener,
4105 std::string &SuggestedPredefines) {
4106 PreprocessorOptions PPOpts;
4107 unsigned Idx = 0;
4108
4109 // Macro definitions/undefs
4110 for (unsigned N = Record[Idx++]; N; --N) {
4111 std::string Macro = ReadString(Record, Idx);
4112 bool IsUndef = Record[Idx++];
4113 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4114 }
4115
4116 // Includes
4117 for (unsigned N = Record[Idx++]; N; --N) {
4118 PPOpts.Includes.push_back(ReadString(Record, Idx));
4119 }
4120
4121 // Macro Includes
4122 for (unsigned N = Record[Idx++]; N; --N) {
4123 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4124 }
4125
4126 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004127 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004128 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4129 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4130 PPOpts.ObjCXXARCStandardLibrary =
4131 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4132 SuggestedPredefines.clear();
4133 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4134 SuggestedPredefines);
4135}
4136
4137std::pair<ModuleFile *, unsigned>
4138ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4139 GlobalPreprocessedEntityMapType::iterator
4140 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4141 assert(I != GlobalPreprocessedEntityMap.end() &&
4142 "Corrupted global preprocessed entity map");
4143 ModuleFile *M = I->second;
4144 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4145 return std::make_pair(M, LocalIndex);
4146}
4147
4148std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4149ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4150 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4151 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4152 Mod.NumPreprocessedEntities);
4153
4154 return std::make_pair(PreprocessingRecord::iterator(),
4155 PreprocessingRecord::iterator());
4156}
4157
4158std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4159ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4160 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4161 ModuleDeclIterator(this, &Mod,
4162 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4163}
4164
4165PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4166 PreprocessedEntityID PPID = Index+1;
4167 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4168 ModuleFile &M = *PPInfo.first;
4169 unsigned LocalIndex = PPInfo.second;
4170 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4171
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 if (!PP.getPreprocessingRecord()) {
4173 Error("no preprocessing record");
4174 return 0;
4175 }
4176
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004177 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4178 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4179
4180 llvm::BitstreamEntry Entry =
4181 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4182 if (Entry.Kind != llvm::BitstreamEntry::Record)
4183 return 0;
4184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 // Read the record.
4186 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4187 ReadSourceLocation(M, PPOffs.End));
4188 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004189 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 RecordData Record;
4191 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004192 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4193 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 switch (RecType) {
4195 case PPD_MACRO_EXPANSION: {
4196 bool isBuiltin = Record[0];
4197 IdentifierInfo *Name = 0;
4198 MacroDefinition *Def = 0;
4199 if (isBuiltin)
4200 Name = getLocalIdentifier(M, Record[1]);
4201 else {
4202 PreprocessedEntityID
4203 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4204 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4205 }
4206
4207 MacroExpansion *ME;
4208 if (isBuiltin)
4209 ME = new (PPRec) MacroExpansion(Name, Range);
4210 else
4211 ME = new (PPRec) MacroExpansion(Def, Range);
4212
4213 return ME;
4214 }
4215
4216 case PPD_MACRO_DEFINITION: {
4217 // Decode the identifier info and then check again; if the macro is
4218 // still defined and associated with the identifier,
4219 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4220 MacroDefinition *MD
4221 = new (PPRec) MacroDefinition(II, Range);
4222
4223 if (DeserializationListener)
4224 DeserializationListener->MacroDefinitionRead(PPID, MD);
4225
4226 return MD;
4227 }
4228
4229 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004230 const char *FullFileNameStart = Blob.data() + Record[0];
4231 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 const FileEntry *File = 0;
4233 if (!FullFileName.empty())
4234 File = PP.getFileManager().getFile(FullFileName);
4235
4236 // FIXME: Stable encoding
4237 InclusionDirective::InclusionKind Kind
4238 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4239 InclusionDirective *ID
4240 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004241 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 Record[1], Record[3],
4243 File,
4244 Range);
4245 return ID;
4246 }
4247 }
4248
4249 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4250}
4251
4252/// \brief \arg SLocMapI points at a chunk of a module that contains no
4253/// preprocessed entities or the entities it contains are not the ones we are
4254/// looking for. Find the next module that contains entities and return the ID
4255/// of the first entry.
4256PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4257 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4258 ++SLocMapI;
4259 for (GlobalSLocOffsetMapType::const_iterator
4260 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4261 ModuleFile &M = *SLocMapI->second;
4262 if (M.NumPreprocessedEntities)
4263 return M.BasePreprocessedEntityID;
4264 }
4265
4266 return getTotalNumPreprocessedEntities();
4267}
4268
4269namespace {
4270
4271template <unsigned PPEntityOffset::*PPLoc>
4272struct PPEntityComp {
4273 const ASTReader &Reader;
4274 ModuleFile &M;
4275
4276 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4277
4278 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4279 SourceLocation LHS = getLoc(L);
4280 SourceLocation RHS = getLoc(R);
4281 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4282 }
4283
4284 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4285 SourceLocation LHS = getLoc(L);
4286 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4287 }
4288
4289 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4290 SourceLocation RHS = getLoc(R);
4291 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4292 }
4293
4294 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4295 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4296 }
4297};
4298
4299}
4300
4301/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4302PreprocessedEntityID
4303ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4304 if (SourceMgr.isLocalSourceLocation(BLoc))
4305 return getTotalNumPreprocessedEntities();
4306
4307 GlobalSLocOffsetMapType::const_iterator
4308 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004309 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4311 "Corrupted global sloc offset map");
4312
4313 if (SLocMapI->second->NumPreprocessedEntities == 0)
4314 return findNextPreprocessedEntity(SLocMapI);
4315
4316 ModuleFile &M = *SLocMapI->second;
4317 typedef const PPEntityOffset *pp_iterator;
4318 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4319 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4320
4321 size_t Count = M.NumPreprocessedEntities;
4322 size_t Half;
4323 pp_iterator First = pp_begin;
4324 pp_iterator PPI;
4325
4326 // Do a binary search manually instead of using std::lower_bound because
4327 // The end locations of entities may be unordered (when a macro expansion
4328 // is inside another macro argument), but for this case it is not important
4329 // whether we get the first macro expansion or its containing macro.
4330 while (Count > 0) {
4331 Half = Count/2;
4332 PPI = First;
4333 std::advance(PPI, Half);
4334 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4335 BLoc)){
4336 First = PPI;
4337 ++First;
4338 Count = Count - Half - 1;
4339 } else
4340 Count = Half;
4341 }
4342
4343 if (PPI == pp_end)
4344 return findNextPreprocessedEntity(SLocMapI);
4345
4346 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4347}
4348
4349/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4350PreprocessedEntityID
4351ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4352 if (SourceMgr.isLocalSourceLocation(ELoc))
4353 return getTotalNumPreprocessedEntities();
4354
4355 GlobalSLocOffsetMapType::const_iterator
4356 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004357 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4359 "Corrupted global sloc offset map");
4360
4361 if (SLocMapI->second->NumPreprocessedEntities == 0)
4362 return findNextPreprocessedEntity(SLocMapI);
4363
4364 ModuleFile &M = *SLocMapI->second;
4365 typedef const PPEntityOffset *pp_iterator;
4366 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4367 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4368 pp_iterator PPI =
4369 std::upper_bound(pp_begin, pp_end, ELoc,
4370 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4371
4372 if (PPI == pp_end)
4373 return findNextPreprocessedEntity(SLocMapI);
4374
4375 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4376}
4377
4378/// \brief Returns a pair of [Begin, End) indices of preallocated
4379/// preprocessed entities that \arg Range encompasses.
4380std::pair<unsigned, unsigned>
4381 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4382 if (Range.isInvalid())
4383 return std::make_pair(0,0);
4384 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4385
4386 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4387 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4388 return std::make_pair(BeginID, EndID);
4389}
4390
4391/// \brief Optionally returns true or false if the preallocated preprocessed
4392/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004393Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 FileID FID) {
4395 if (FID.isInvalid())
4396 return false;
4397
4398 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4399 ModuleFile &M = *PPInfo.first;
4400 unsigned LocalIndex = PPInfo.second;
4401 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4402
4403 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4404 if (Loc.isInvalid())
4405 return false;
4406
4407 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4408 return true;
4409 else
4410 return false;
4411}
4412
4413namespace {
4414 /// \brief Visitor used to search for information about a header file.
4415 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 const FileEntry *FE;
4417
David Blaikie05785d12013-02-20 22:23:23 +00004418 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419
4420 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004421 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4422 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004423
4424 static bool visit(ModuleFile &M, void *UserData) {
4425 HeaderFileInfoVisitor *This
4426 = static_cast<HeaderFileInfoVisitor *>(UserData);
4427
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 HeaderFileInfoLookupTable *Table
4429 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4430 if (!Table)
4431 return false;
4432
4433 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004434 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 if (Pos == Table->end())
4436 return false;
4437
4438 This->HFI = *Pos;
4439 return true;
4440 }
4441
David Blaikie05785d12013-02-20 22:23:23 +00004442 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 };
4444}
4445
4446HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004447 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004449 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451
4452 return HeaderFileInfo();
4453}
4454
4455void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4456 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004457 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4459 ModuleFile &F = *(*I);
4460 unsigned Idx = 0;
4461 DiagStates.clear();
4462 assert(!Diag.DiagStates.empty());
4463 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4464 while (Idx < F.PragmaDiagMappings.size()) {
4465 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4466 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4467 if (DiagStateID != 0) {
4468 Diag.DiagStatePoints.push_back(
4469 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4470 FullSourceLoc(Loc, SourceMgr)));
4471 continue;
4472 }
4473
4474 assert(DiagStateID == 0);
4475 // A new DiagState was created here.
4476 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4477 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4478 DiagStates.push_back(NewState);
4479 Diag.DiagStatePoints.push_back(
4480 DiagnosticsEngine::DiagStatePoint(NewState,
4481 FullSourceLoc(Loc, SourceMgr)));
4482 while (1) {
4483 assert(Idx < F.PragmaDiagMappings.size() &&
4484 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4485 if (Idx >= F.PragmaDiagMappings.size()) {
4486 break; // Something is messed up but at least avoid infinite loop in
4487 // release build.
4488 }
4489 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4490 if (DiagID == (unsigned)-1) {
4491 break; // no more diag/map pairs for this location.
4492 }
4493 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4494 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4495 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4496 }
4497 }
4498 }
4499}
4500
4501/// \brief Get the correct cursor and offset for loading a type.
4502ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4503 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4504 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4505 ModuleFile *M = I->second;
4506 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4507}
4508
4509/// \brief Read and return the type with the given index..
4510///
4511/// The index is the type ID, shifted and minus the number of predefs. This
4512/// routine actually reads the record corresponding to the type at the given
4513/// location. It is a helper routine for GetType, which deals with reading type
4514/// IDs.
4515QualType ASTReader::readTypeRecord(unsigned Index) {
4516 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004517 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004518
4519 // Keep track of where we are in the stream, then jump back there
4520 // after reading this type.
4521 SavedStreamPosition SavedPosition(DeclsCursor);
4522
4523 ReadingKindTracker ReadingKind(Read_Type, *this);
4524
4525 // Note that we are loading a type record.
4526 Deserializing AType(this);
4527
4528 unsigned Idx = 0;
4529 DeclsCursor.JumpToBit(Loc.Offset);
4530 RecordData Record;
4531 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004532 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 case TYPE_EXT_QUAL: {
4534 if (Record.size() != 2) {
4535 Error("Incorrect encoding of extended qualifier type");
4536 return QualType();
4537 }
4538 QualType Base = readType(*Loc.F, Record, Idx);
4539 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4540 return Context.getQualifiedType(Base, Quals);
4541 }
4542
4543 case TYPE_COMPLEX: {
4544 if (Record.size() != 1) {
4545 Error("Incorrect encoding of complex type");
4546 return QualType();
4547 }
4548 QualType ElemType = readType(*Loc.F, Record, Idx);
4549 return Context.getComplexType(ElemType);
4550 }
4551
4552 case TYPE_POINTER: {
4553 if (Record.size() != 1) {
4554 Error("Incorrect encoding of pointer type");
4555 return QualType();
4556 }
4557 QualType PointeeType = readType(*Loc.F, Record, Idx);
4558 return Context.getPointerType(PointeeType);
4559 }
4560
Reid Kleckner8a365022013-06-24 17:51:48 +00004561 case TYPE_DECAYED: {
4562 if (Record.size() != 1) {
4563 Error("Incorrect encoding of decayed type");
4564 return QualType();
4565 }
4566 QualType OriginalType = readType(*Loc.F, Record, Idx);
4567 QualType DT = Context.getAdjustedParameterType(OriginalType);
4568 if (!isa<DecayedType>(DT))
4569 Error("Decayed type does not decay");
4570 return DT;
4571 }
4572
Reid Kleckner0503a872013-12-05 01:23:43 +00004573 case TYPE_ADJUSTED: {
4574 if (Record.size() != 2) {
4575 Error("Incorrect encoding of adjusted type");
4576 return QualType();
4577 }
4578 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4579 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4580 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4581 }
4582
Guy Benyei11169dd2012-12-18 14:30:41 +00004583 case TYPE_BLOCK_POINTER: {
4584 if (Record.size() != 1) {
4585 Error("Incorrect encoding of block pointer type");
4586 return QualType();
4587 }
4588 QualType PointeeType = readType(*Loc.F, Record, Idx);
4589 return Context.getBlockPointerType(PointeeType);
4590 }
4591
4592 case TYPE_LVALUE_REFERENCE: {
4593 if (Record.size() != 2) {
4594 Error("Incorrect encoding of lvalue reference type");
4595 return QualType();
4596 }
4597 QualType PointeeType = readType(*Loc.F, Record, Idx);
4598 return Context.getLValueReferenceType(PointeeType, Record[1]);
4599 }
4600
4601 case TYPE_RVALUE_REFERENCE: {
4602 if (Record.size() != 1) {
4603 Error("Incorrect encoding of rvalue reference type");
4604 return QualType();
4605 }
4606 QualType PointeeType = readType(*Loc.F, Record, Idx);
4607 return Context.getRValueReferenceType(PointeeType);
4608 }
4609
4610 case TYPE_MEMBER_POINTER: {
4611 if (Record.size() != 2) {
4612 Error("Incorrect encoding of member pointer type");
4613 return QualType();
4614 }
4615 QualType PointeeType = readType(*Loc.F, Record, Idx);
4616 QualType ClassType = readType(*Loc.F, Record, Idx);
4617 if (PointeeType.isNull() || ClassType.isNull())
4618 return QualType();
4619
4620 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4621 }
4622
4623 case TYPE_CONSTANT_ARRAY: {
4624 QualType ElementType = readType(*Loc.F, Record, Idx);
4625 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4626 unsigned IndexTypeQuals = Record[2];
4627 unsigned Idx = 3;
4628 llvm::APInt Size = ReadAPInt(Record, Idx);
4629 return Context.getConstantArrayType(ElementType, Size,
4630 ASM, IndexTypeQuals);
4631 }
4632
4633 case TYPE_INCOMPLETE_ARRAY: {
4634 QualType ElementType = readType(*Loc.F, Record, Idx);
4635 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4636 unsigned IndexTypeQuals = Record[2];
4637 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4638 }
4639
4640 case TYPE_VARIABLE_ARRAY: {
4641 QualType ElementType = readType(*Loc.F, Record, Idx);
4642 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4643 unsigned IndexTypeQuals = Record[2];
4644 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4645 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4646 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4647 ASM, IndexTypeQuals,
4648 SourceRange(LBLoc, RBLoc));
4649 }
4650
4651 case TYPE_VECTOR: {
4652 if (Record.size() != 3) {
4653 Error("incorrect encoding of vector type in AST file");
4654 return QualType();
4655 }
4656
4657 QualType ElementType = readType(*Loc.F, Record, Idx);
4658 unsigned NumElements = Record[1];
4659 unsigned VecKind = Record[2];
4660 return Context.getVectorType(ElementType, NumElements,
4661 (VectorType::VectorKind)VecKind);
4662 }
4663
4664 case TYPE_EXT_VECTOR: {
4665 if (Record.size() != 3) {
4666 Error("incorrect encoding of extended vector type in AST file");
4667 return QualType();
4668 }
4669
4670 QualType ElementType = readType(*Loc.F, Record, Idx);
4671 unsigned NumElements = Record[1];
4672 return Context.getExtVectorType(ElementType, NumElements);
4673 }
4674
4675 case TYPE_FUNCTION_NO_PROTO: {
4676 if (Record.size() != 6) {
4677 Error("incorrect encoding of no-proto function type");
4678 return QualType();
4679 }
4680 QualType ResultType = readType(*Loc.F, Record, Idx);
4681 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4682 (CallingConv)Record[4], Record[5]);
4683 return Context.getFunctionNoProtoType(ResultType, Info);
4684 }
4685
4686 case TYPE_FUNCTION_PROTO: {
4687 QualType ResultType = readType(*Loc.F, Record, Idx);
4688
4689 FunctionProtoType::ExtProtoInfo EPI;
4690 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4691 /*hasregparm*/ Record[2],
4692 /*regparm*/ Record[3],
4693 static_cast<CallingConv>(Record[4]),
4694 /*produces*/ Record[5]);
4695
4696 unsigned Idx = 6;
4697 unsigned NumParams = Record[Idx++];
4698 SmallVector<QualType, 16> ParamTypes;
4699 for (unsigned I = 0; I != NumParams; ++I)
4700 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4701
4702 EPI.Variadic = Record[Idx++];
4703 EPI.HasTrailingReturn = Record[Idx++];
4704 EPI.TypeQuals = Record[Idx++];
4705 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4706 ExceptionSpecificationType EST =
4707 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4708 EPI.ExceptionSpecType = EST;
4709 SmallVector<QualType, 2> Exceptions;
4710 if (EST == EST_Dynamic) {
4711 EPI.NumExceptions = Record[Idx++];
4712 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4713 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4714 EPI.Exceptions = Exceptions.data();
4715 } else if (EST == EST_ComputedNoexcept) {
4716 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4717 } else if (EST == EST_Uninstantiated) {
4718 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4719 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4720 } else if (EST == EST_Unevaluated) {
4721 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4722 }
Jordan Rose5c382722013-03-08 21:51:21 +00004723 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 }
4725
4726 case TYPE_UNRESOLVED_USING: {
4727 unsigned Idx = 0;
4728 return Context.getTypeDeclType(
4729 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4730 }
4731
4732 case TYPE_TYPEDEF: {
4733 if (Record.size() != 2) {
4734 Error("incorrect encoding of typedef type");
4735 return QualType();
4736 }
4737 unsigned Idx = 0;
4738 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4739 QualType Canonical = readType(*Loc.F, Record, Idx);
4740 if (!Canonical.isNull())
4741 Canonical = Context.getCanonicalType(Canonical);
4742 return Context.getTypedefType(Decl, Canonical);
4743 }
4744
4745 case TYPE_TYPEOF_EXPR:
4746 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4747
4748 case TYPE_TYPEOF: {
4749 if (Record.size() != 1) {
4750 Error("incorrect encoding of typeof(type) in AST file");
4751 return QualType();
4752 }
4753 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4754 return Context.getTypeOfType(UnderlyingType);
4755 }
4756
4757 case TYPE_DECLTYPE: {
4758 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4759 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4760 }
4761
4762 case TYPE_UNARY_TRANSFORM: {
4763 QualType BaseType = readType(*Loc.F, Record, Idx);
4764 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4765 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4766 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4767 }
4768
Richard Smith74aeef52013-04-26 16:15:35 +00004769 case TYPE_AUTO: {
4770 QualType Deduced = readType(*Loc.F, Record, Idx);
4771 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00004772 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004773 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00004774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004775
4776 case TYPE_RECORD: {
4777 if (Record.size() != 2) {
4778 Error("incorrect encoding of record type");
4779 return QualType();
4780 }
4781 unsigned Idx = 0;
4782 bool IsDependent = Record[Idx++];
4783 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4784 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4785 QualType T = Context.getRecordType(RD);
4786 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4787 return T;
4788 }
4789
4790 case TYPE_ENUM: {
4791 if (Record.size() != 2) {
4792 Error("incorrect encoding of enum type");
4793 return QualType();
4794 }
4795 unsigned Idx = 0;
4796 bool IsDependent = Record[Idx++];
4797 QualType T
4798 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4799 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4800 return T;
4801 }
4802
4803 case TYPE_ATTRIBUTED: {
4804 if (Record.size() != 3) {
4805 Error("incorrect encoding of attributed type");
4806 return QualType();
4807 }
4808 QualType modifiedType = readType(*Loc.F, Record, Idx);
4809 QualType equivalentType = readType(*Loc.F, Record, Idx);
4810 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4811 return Context.getAttributedType(kind, modifiedType, equivalentType);
4812 }
4813
4814 case TYPE_PAREN: {
4815 if (Record.size() != 1) {
4816 Error("incorrect encoding of paren type");
4817 return QualType();
4818 }
4819 QualType InnerType = readType(*Loc.F, Record, Idx);
4820 return Context.getParenType(InnerType);
4821 }
4822
4823 case TYPE_PACK_EXPANSION: {
4824 if (Record.size() != 2) {
4825 Error("incorrect encoding of pack expansion type");
4826 return QualType();
4827 }
4828 QualType Pattern = readType(*Loc.F, Record, Idx);
4829 if (Pattern.isNull())
4830 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00004831 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 if (Record[1])
4833 NumExpansions = Record[1] - 1;
4834 return Context.getPackExpansionType(Pattern, NumExpansions);
4835 }
4836
4837 case TYPE_ELABORATED: {
4838 unsigned Idx = 0;
4839 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4840 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4841 QualType NamedType = readType(*Loc.F, Record, Idx);
4842 return Context.getElaboratedType(Keyword, NNS, NamedType);
4843 }
4844
4845 case TYPE_OBJC_INTERFACE: {
4846 unsigned Idx = 0;
4847 ObjCInterfaceDecl *ItfD
4848 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4849 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4850 }
4851
4852 case TYPE_OBJC_OBJECT: {
4853 unsigned Idx = 0;
4854 QualType Base = readType(*Loc.F, Record, Idx);
4855 unsigned NumProtos = Record[Idx++];
4856 SmallVector<ObjCProtocolDecl*, 4> Protos;
4857 for (unsigned I = 0; I != NumProtos; ++I)
4858 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4859 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4860 }
4861
4862 case TYPE_OBJC_OBJECT_POINTER: {
4863 unsigned Idx = 0;
4864 QualType Pointee = readType(*Loc.F, Record, Idx);
4865 return Context.getObjCObjectPointerType(Pointee);
4866 }
4867
4868 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4869 unsigned Idx = 0;
4870 QualType Parm = readType(*Loc.F, Record, Idx);
4871 QualType Replacement = readType(*Loc.F, Record, Idx);
4872 return
4873 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4874 Replacement);
4875 }
4876
4877 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4878 unsigned Idx = 0;
4879 QualType Parm = readType(*Loc.F, Record, Idx);
4880 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4881 return Context.getSubstTemplateTypeParmPackType(
4882 cast<TemplateTypeParmType>(Parm),
4883 ArgPack);
4884 }
4885
4886 case TYPE_INJECTED_CLASS_NAME: {
4887 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4888 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4889 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4890 // for AST reading, too much interdependencies.
4891 return
4892 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4893 }
4894
4895 case TYPE_TEMPLATE_TYPE_PARM: {
4896 unsigned Idx = 0;
4897 unsigned Depth = Record[Idx++];
4898 unsigned Index = Record[Idx++];
4899 bool Pack = Record[Idx++];
4900 TemplateTypeParmDecl *D
4901 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4902 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4903 }
4904
4905 case TYPE_DEPENDENT_NAME: {
4906 unsigned Idx = 0;
4907 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4908 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4909 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4910 QualType Canon = readType(*Loc.F, Record, Idx);
4911 if (!Canon.isNull())
4912 Canon = Context.getCanonicalType(Canon);
4913 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4914 }
4915
4916 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4917 unsigned Idx = 0;
4918 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4919 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4920 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4921 unsigned NumArgs = Record[Idx++];
4922 SmallVector<TemplateArgument, 8> Args;
4923 Args.reserve(NumArgs);
4924 while (NumArgs--)
4925 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4926 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4927 Args.size(), Args.data());
4928 }
4929
4930 case TYPE_DEPENDENT_SIZED_ARRAY: {
4931 unsigned Idx = 0;
4932
4933 // ArrayType
4934 QualType ElementType = readType(*Loc.F, Record, Idx);
4935 ArrayType::ArraySizeModifier ASM
4936 = (ArrayType::ArraySizeModifier)Record[Idx++];
4937 unsigned IndexTypeQuals = Record[Idx++];
4938
4939 // DependentSizedArrayType
4940 Expr *NumElts = ReadExpr(*Loc.F);
4941 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4942
4943 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4944 IndexTypeQuals, Brackets);
4945 }
4946
4947 case TYPE_TEMPLATE_SPECIALIZATION: {
4948 unsigned Idx = 0;
4949 bool IsDependent = Record[Idx++];
4950 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4951 SmallVector<TemplateArgument, 8> Args;
4952 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4953 QualType Underlying = readType(*Loc.F, Record, Idx);
4954 QualType T;
4955 if (Underlying.isNull())
4956 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4957 Args.size());
4958 else
4959 T = Context.getTemplateSpecializationType(Name, Args.data(),
4960 Args.size(), Underlying);
4961 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4962 return T;
4963 }
4964
4965 case TYPE_ATOMIC: {
4966 if (Record.size() != 1) {
4967 Error("Incorrect encoding of atomic type");
4968 return QualType();
4969 }
4970 QualType ValueType = readType(*Loc.F, Record, Idx);
4971 return Context.getAtomicType(ValueType);
4972 }
4973 }
4974 llvm_unreachable("Invalid TypeCode!");
4975}
4976
4977class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4978 ASTReader &Reader;
4979 ModuleFile &F;
4980 const ASTReader::RecordData &Record;
4981 unsigned &Idx;
4982
4983 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4984 unsigned &I) {
4985 return Reader.ReadSourceLocation(F, R, I);
4986 }
4987
4988 template<typename T>
4989 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4990 return Reader.ReadDeclAs<T>(F, Record, Idx);
4991 }
4992
4993public:
4994 TypeLocReader(ASTReader &Reader, ModuleFile &F,
4995 const ASTReader::RecordData &Record, unsigned &Idx)
4996 : Reader(Reader), F(F), Record(Record), Idx(Idx)
4997 { }
4998
4999 // We want compile-time assurance that we've enumerated all of
5000 // these, so unfortunately we have to declare them first, then
5001 // define them out-of-line.
5002#define ABSTRACT_TYPELOC(CLASS, PARENT)
5003#define TYPELOC(CLASS, PARENT) \
5004 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5005#include "clang/AST/TypeLocNodes.def"
5006
5007 void VisitFunctionTypeLoc(FunctionTypeLoc);
5008 void VisitArrayTypeLoc(ArrayTypeLoc);
5009};
5010
5011void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5012 // nothing to do
5013}
5014void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5015 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5016 if (TL.needsExtraLocalData()) {
5017 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5018 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5019 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5020 TL.setModeAttr(Record[Idx++]);
5021 }
5022}
5023void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5024 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5025}
5026void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5027 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5028}
Reid Kleckner8a365022013-06-24 17:51:48 +00005029void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5030 // nothing to do
5031}
Reid Kleckner0503a872013-12-05 01:23:43 +00005032void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5033 // nothing to do
5034}
Guy Benyei11169dd2012-12-18 14:30:41 +00005035void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5036 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5037}
5038void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5039 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5040}
5041void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5042 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5043}
5044void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5045 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5046 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5047}
5048void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5049 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5050 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5051 if (Record[Idx++])
5052 TL.setSizeExpr(Reader.ReadExpr(F));
5053 else
5054 TL.setSizeExpr(0);
5055}
5056void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5057 VisitArrayTypeLoc(TL);
5058}
5059void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5060 VisitArrayTypeLoc(TL);
5061}
5062void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5063 VisitArrayTypeLoc(TL);
5064}
5065void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5066 DependentSizedArrayTypeLoc TL) {
5067 VisitArrayTypeLoc(TL);
5068}
5069void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5070 DependentSizedExtVectorTypeLoc TL) {
5071 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5072}
5073void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5074 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5075}
5076void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5077 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5078}
5079void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5080 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5081 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5082 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5083 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005084 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5085 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 }
5087}
5088void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5089 VisitFunctionTypeLoc(TL);
5090}
5091void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5092 VisitFunctionTypeLoc(TL);
5093}
5094void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5095 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5096}
5097void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5098 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5099}
5100void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5101 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5102 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5103 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5104}
5105void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5106 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5107 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5108 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5109 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5110}
5111void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5112 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5113}
5114void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5115 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5116 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5117 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5118 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5119}
5120void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5121 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5122}
5123void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5124 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5125}
5126void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5127 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5128}
5129void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5130 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5131 if (TL.hasAttrOperand()) {
5132 SourceRange range;
5133 range.setBegin(ReadSourceLocation(Record, Idx));
5134 range.setEnd(ReadSourceLocation(Record, Idx));
5135 TL.setAttrOperandParensRange(range);
5136 }
5137 if (TL.hasAttrExprOperand()) {
5138 if (Record[Idx++])
5139 TL.setAttrExprOperand(Reader.ReadExpr(F));
5140 else
5141 TL.setAttrExprOperand(0);
5142 } else if (TL.hasAttrEnumOperand())
5143 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5144}
5145void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5146 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5147}
5148void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5149 SubstTemplateTypeParmTypeLoc TL) {
5150 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5151}
5152void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5153 SubstTemplateTypeParmPackTypeLoc TL) {
5154 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5155}
5156void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5157 TemplateSpecializationTypeLoc TL) {
5158 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5159 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5160 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5161 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5162 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5163 TL.setArgLocInfo(i,
5164 Reader.GetTemplateArgumentLocInfo(F,
5165 TL.getTypePtr()->getArg(i).getKind(),
5166 Record, Idx));
5167}
5168void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5169 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5170 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5171}
5172void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5173 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5174 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5175}
5176void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5177 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5178}
5179void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5180 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5181 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5182 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5183}
5184void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5185 DependentTemplateSpecializationTypeLoc TL) {
5186 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5187 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5188 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5189 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5190 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5191 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5192 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5193 TL.setArgLocInfo(I,
5194 Reader.GetTemplateArgumentLocInfo(F,
5195 TL.getTypePtr()->getArg(I).getKind(),
5196 Record, Idx));
5197}
5198void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5199 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5200}
5201void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5202 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5203}
5204void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5205 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5206 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5207 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5208 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5209 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5210}
5211void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5212 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5213}
5214void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5215 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5216 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5217 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5218}
5219
5220TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5221 const RecordData &Record,
5222 unsigned &Idx) {
5223 QualType InfoTy = readType(F, Record, Idx);
5224 if (InfoTy.isNull())
5225 return 0;
5226
5227 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5228 TypeLocReader TLR(*this, F, Record, Idx);
5229 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5230 TLR.Visit(TL);
5231 return TInfo;
5232}
5233
5234QualType ASTReader::GetType(TypeID ID) {
5235 unsigned FastQuals = ID & Qualifiers::FastMask;
5236 unsigned Index = ID >> Qualifiers::FastWidth;
5237
5238 if (Index < NUM_PREDEF_TYPE_IDS) {
5239 QualType T;
5240 switch ((PredefinedTypeIDs)Index) {
5241 case PREDEF_TYPE_NULL_ID: return QualType();
5242 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5243 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5244
5245 case PREDEF_TYPE_CHAR_U_ID:
5246 case PREDEF_TYPE_CHAR_S_ID:
5247 // FIXME: Check that the signedness of CharTy is correct!
5248 T = Context.CharTy;
5249 break;
5250
5251 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5252 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5253 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5254 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5255 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5256 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5257 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5258 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5259 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5260 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5261 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5262 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5263 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5264 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5265 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5266 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5267 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5268 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5269 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5270 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5271 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5272 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5273 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5274 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5275 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5276 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5277 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5278 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005279 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5280 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5281 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5282 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5283 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5284 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005285 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005286 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5288
5289 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5290 T = Context.getAutoRRefDeductType();
5291 break;
5292
5293 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5294 T = Context.ARCUnbridgedCastTy;
5295 break;
5296
5297 case PREDEF_TYPE_VA_LIST_TAG:
5298 T = Context.getVaListTagType();
5299 break;
5300
5301 case PREDEF_TYPE_BUILTIN_FN:
5302 T = Context.BuiltinFnTy;
5303 break;
5304 }
5305
5306 assert(!T.isNull() && "Unknown predefined type");
5307 return T.withFastQualifiers(FastQuals);
5308 }
5309
5310 Index -= NUM_PREDEF_TYPE_IDS;
5311 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5312 if (TypesLoaded[Index].isNull()) {
5313 TypesLoaded[Index] = readTypeRecord(Index);
5314 if (TypesLoaded[Index].isNull())
5315 return QualType();
5316
5317 TypesLoaded[Index]->setFromAST();
5318 if (DeserializationListener)
5319 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5320 TypesLoaded[Index]);
5321 }
5322
5323 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5324}
5325
5326QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5327 return GetType(getGlobalTypeID(F, LocalID));
5328}
5329
5330serialization::TypeID
5331ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5332 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5333 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5334
5335 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5336 return LocalID;
5337
5338 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5339 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5340 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5341
5342 unsigned GlobalIndex = LocalIndex + I->second;
5343 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5344}
5345
5346TemplateArgumentLocInfo
5347ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5348 TemplateArgument::ArgKind Kind,
5349 const RecordData &Record,
5350 unsigned &Index) {
5351 switch (Kind) {
5352 case TemplateArgument::Expression:
5353 return ReadExpr(F);
5354 case TemplateArgument::Type:
5355 return GetTypeSourceInfo(F, Record, Index);
5356 case TemplateArgument::Template: {
5357 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5358 Index);
5359 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5360 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5361 SourceLocation());
5362 }
5363 case TemplateArgument::TemplateExpansion: {
5364 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5365 Index);
5366 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5367 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5368 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5369 EllipsisLoc);
5370 }
5371 case TemplateArgument::Null:
5372 case TemplateArgument::Integral:
5373 case TemplateArgument::Declaration:
5374 case TemplateArgument::NullPtr:
5375 case TemplateArgument::Pack:
5376 // FIXME: Is this right?
5377 return TemplateArgumentLocInfo();
5378 }
5379 llvm_unreachable("unexpected template argument loc");
5380}
5381
5382TemplateArgumentLoc
5383ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5384 const RecordData &Record, unsigned &Index) {
5385 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5386
5387 if (Arg.getKind() == TemplateArgument::Expression) {
5388 if (Record[Index++]) // bool InfoHasSameExpr.
5389 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5390 }
5391 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5392 Record, Index));
5393}
5394
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005395const ASTTemplateArgumentListInfo*
5396ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5397 const RecordData &Record,
5398 unsigned &Index) {
5399 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5400 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5401 unsigned NumArgsAsWritten = Record[Index++];
5402 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5403 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5404 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5405 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5406}
5407
Guy Benyei11169dd2012-12-18 14:30:41 +00005408Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5409 return GetDecl(ID);
5410}
5411
5412uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5413 unsigned &Idx){
5414 if (Idx >= Record.size())
5415 return 0;
5416
5417 unsigned LocalID = Record[Idx++];
5418 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5419}
5420
5421CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5422 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005423 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 SavedStreamPosition SavedPosition(Cursor);
5425 Cursor.JumpToBit(Loc.Offset);
5426 ReadingKindTracker ReadingKind(Read_Decl, *this);
5427 RecordData Record;
5428 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005429 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5431 Error("Malformed AST file: missing C++ base specifiers");
5432 return 0;
5433 }
5434
5435 unsigned Idx = 0;
5436 unsigned NumBases = Record[Idx++];
5437 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5438 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5439 for (unsigned I = 0; I != NumBases; ++I)
5440 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5441 return Bases;
5442}
5443
5444serialization::DeclID
5445ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5446 if (LocalID < NUM_PREDEF_DECL_IDS)
5447 return LocalID;
5448
5449 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5450 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5451 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5452
5453 return LocalID + I->second;
5454}
5455
5456bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5457 ModuleFile &M) const {
5458 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5459 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5460 return &M == I->second;
5461}
5462
Douglas Gregor9f782892013-01-21 15:25:38 +00005463ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 if (!D->isFromASTFile())
5465 return 0;
5466 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5467 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5468 return I->second;
5469}
5470
5471SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5472 if (ID < NUM_PREDEF_DECL_IDS)
5473 return SourceLocation();
5474
5475 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5476
5477 if (Index > DeclsLoaded.size()) {
5478 Error("declaration ID out-of-range for AST file");
5479 return SourceLocation();
5480 }
5481
5482 if (Decl *D = DeclsLoaded[Index])
5483 return D->getLocation();
5484
5485 unsigned RawLocation = 0;
5486 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5487 return ReadSourceLocation(*Rec.F, RawLocation);
5488}
5489
5490Decl *ASTReader::GetDecl(DeclID ID) {
5491 if (ID < NUM_PREDEF_DECL_IDS) {
5492 switch ((PredefinedDeclIDs)ID) {
5493 case PREDEF_DECL_NULL_ID:
5494 return 0;
5495
5496 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5497 return Context.getTranslationUnitDecl();
5498
5499 case PREDEF_DECL_OBJC_ID_ID:
5500 return Context.getObjCIdDecl();
5501
5502 case PREDEF_DECL_OBJC_SEL_ID:
5503 return Context.getObjCSelDecl();
5504
5505 case PREDEF_DECL_OBJC_CLASS_ID:
5506 return Context.getObjCClassDecl();
5507
5508 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5509 return Context.getObjCProtocolDecl();
5510
5511 case PREDEF_DECL_INT_128_ID:
5512 return Context.getInt128Decl();
5513
5514 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5515 return Context.getUInt128Decl();
5516
5517 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5518 return Context.getObjCInstanceTypeDecl();
5519
5520 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5521 return Context.getBuiltinVaListDecl();
5522 }
5523 }
5524
5525 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5526
5527 if (Index >= DeclsLoaded.size()) {
5528 assert(0 && "declaration ID out-of-range for AST file");
5529 Error("declaration ID out-of-range for AST file");
5530 return 0;
5531 }
5532
5533 if (!DeclsLoaded[Index]) {
5534 ReadDeclRecord(ID);
5535 if (DeserializationListener)
5536 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5537 }
5538
5539 return DeclsLoaded[Index];
5540}
5541
5542DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5543 DeclID GlobalID) {
5544 if (GlobalID < NUM_PREDEF_DECL_IDS)
5545 return GlobalID;
5546
5547 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5548 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5549 ModuleFile *Owner = I->second;
5550
5551 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5552 = M.GlobalToLocalDeclIDs.find(Owner);
5553 if (Pos == M.GlobalToLocalDeclIDs.end())
5554 return 0;
5555
5556 return GlobalID - Owner->BaseDeclID + Pos->second;
5557}
5558
5559serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5560 const RecordData &Record,
5561 unsigned &Idx) {
5562 if (Idx >= Record.size()) {
5563 Error("Corrupted AST file");
5564 return 0;
5565 }
5566
5567 return getGlobalDeclID(F, Record[Idx++]);
5568}
5569
5570/// \brief Resolve the offset of a statement into a statement.
5571///
5572/// This operation will read a new statement from the external
5573/// source each time it is called, and is meant to be used via a
5574/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5575Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5576 // Switch case IDs are per Decl.
5577 ClearSwitchCaseIDs();
5578
5579 // Offset here is a global offset across the entire chain.
5580 RecordLocation Loc = getLocalBitOffset(Offset);
5581 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5582 return ReadStmtFromStream(*Loc.F);
5583}
5584
5585namespace {
5586 class FindExternalLexicalDeclsVisitor {
5587 ASTReader &Reader;
5588 const DeclContext *DC;
5589 bool (*isKindWeWant)(Decl::Kind);
5590
5591 SmallVectorImpl<Decl*> &Decls;
5592 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5593
5594 public:
5595 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5596 bool (*isKindWeWant)(Decl::Kind),
5597 SmallVectorImpl<Decl*> &Decls)
5598 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5599 {
5600 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5601 PredefsVisited[I] = false;
5602 }
5603
5604 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5605 if (Preorder)
5606 return false;
5607
5608 FindExternalLexicalDeclsVisitor *This
5609 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5610
5611 ModuleFile::DeclContextInfosMap::iterator Info
5612 = M.DeclContextInfos.find(This->DC);
5613 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5614 return false;
5615
5616 // Load all of the declaration IDs
5617 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5618 *IDE = ID + Info->second.NumLexicalDecls;
5619 ID != IDE; ++ID) {
5620 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5621 continue;
5622
5623 // Don't add predefined declarations to the lexical context more
5624 // than once.
5625 if (ID->second < NUM_PREDEF_DECL_IDS) {
5626 if (This->PredefsVisited[ID->second])
5627 continue;
5628
5629 This->PredefsVisited[ID->second] = true;
5630 }
5631
5632 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5633 if (!This->DC->isDeclInLexicalTraversal(D))
5634 This->Decls.push_back(D);
5635 }
5636 }
5637
5638 return false;
5639 }
5640 };
5641}
5642
5643ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5644 bool (*isKindWeWant)(Decl::Kind),
5645 SmallVectorImpl<Decl*> &Decls) {
5646 // There might be lexical decls in multiple modules, for the TU at
5647 // least. Walk all of the modules in the order they were loaded.
5648 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5649 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5650 ++NumLexicalDeclContextsRead;
5651 return ELR_Success;
5652}
5653
5654namespace {
5655
5656class DeclIDComp {
5657 ASTReader &Reader;
5658 ModuleFile &Mod;
5659
5660public:
5661 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5662
5663 bool operator()(LocalDeclID L, LocalDeclID R) const {
5664 SourceLocation LHS = getLocation(L);
5665 SourceLocation RHS = getLocation(R);
5666 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5667 }
5668
5669 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5670 SourceLocation RHS = getLocation(R);
5671 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5672 }
5673
5674 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5675 SourceLocation LHS = getLocation(L);
5676 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5677 }
5678
5679 SourceLocation getLocation(LocalDeclID ID) const {
5680 return Reader.getSourceManager().getFileLoc(
5681 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5682 }
5683};
5684
5685}
5686
5687void ASTReader::FindFileRegionDecls(FileID File,
5688 unsigned Offset, unsigned Length,
5689 SmallVectorImpl<Decl *> &Decls) {
5690 SourceManager &SM = getSourceManager();
5691
5692 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5693 if (I == FileDeclIDs.end())
5694 return;
5695
5696 FileDeclsInfo &DInfo = I->second;
5697 if (DInfo.Decls.empty())
5698 return;
5699
5700 SourceLocation
5701 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5702 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5703
5704 DeclIDComp DIDComp(*this, *DInfo.Mod);
5705 ArrayRef<serialization::LocalDeclID>::iterator
5706 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5707 BeginLoc, DIDComp);
5708 if (BeginIt != DInfo.Decls.begin())
5709 --BeginIt;
5710
5711 // If we are pointing at a top-level decl inside an objc container, we need
5712 // to backtrack until we find it otherwise we will fail to report that the
5713 // region overlaps with an objc container.
5714 while (BeginIt != DInfo.Decls.begin() &&
5715 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5716 ->isTopLevelDeclInObjCContainer())
5717 --BeginIt;
5718
5719 ArrayRef<serialization::LocalDeclID>::iterator
5720 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5721 EndLoc, DIDComp);
5722 if (EndIt != DInfo.Decls.end())
5723 ++EndIt;
5724
5725 for (ArrayRef<serialization::LocalDeclID>::iterator
5726 DIt = BeginIt; DIt != EndIt; ++DIt)
5727 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5728}
5729
5730namespace {
5731 /// \brief ModuleFile visitor used to perform name lookup into a
5732 /// declaration context.
5733 class DeclContextNameLookupVisitor {
5734 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005735 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00005736 DeclarationName Name;
5737 SmallVectorImpl<NamedDecl *> &Decls;
5738
5739 public:
5740 DeclContextNameLookupVisitor(ASTReader &Reader,
5741 SmallVectorImpl<const DeclContext *> &Contexts,
5742 DeclarationName Name,
5743 SmallVectorImpl<NamedDecl *> &Decls)
5744 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5745
5746 static bool visit(ModuleFile &M, void *UserData) {
5747 DeclContextNameLookupVisitor *This
5748 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5749
5750 // Check whether we have any visible declaration information for
5751 // this context in this module.
5752 ModuleFile::DeclContextInfosMap::iterator Info;
5753 bool FoundInfo = false;
5754 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5755 Info = M.DeclContextInfos.find(This->Contexts[I]);
5756 if (Info != M.DeclContextInfos.end() &&
5757 Info->second.NameLookupTableData) {
5758 FoundInfo = true;
5759 break;
5760 }
5761 }
5762
5763 if (!FoundInfo)
5764 return false;
5765
5766 // Look for this name within this module.
5767 ASTDeclContextNameLookupTable *LookupTable =
5768 Info->second.NameLookupTableData;
5769 ASTDeclContextNameLookupTable::iterator Pos
5770 = LookupTable->find(This->Name);
5771 if (Pos == LookupTable->end())
5772 return false;
5773
5774 bool FoundAnything = false;
5775 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5776 for (; Data.first != Data.second; ++Data.first) {
5777 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5778 if (!ND)
5779 continue;
5780
5781 if (ND->getDeclName() != This->Name) {
5782 // A name might be null because the decl's redeclarable part is
5783 // currently read before reading its name. The lookup is triggered by
5784 // building that decl (likely indirectly), and so it is later in the
5785 // sense of "already existing" and can be ignored here.
5786 continue;
5787 }
5788
5789 // Record this declaration.
5790 FoundAnything = true;
5791 This->Decls.push_back(ND);
5792 }
5793
5794 return FoundAnything;
5795 }
5796 };
5797}
5798
Douglas Gregor9f782892013-01-21 15:25:38 +00005799/// \brief Retrieve the "definitive" module file for the definition of the
5800/// given declaration context, if there is one.
5801///
5802/// The "definitive" module file is the only place where we need to look to
5803/// find information about the declarations within the given declaration
5804/// context. For example, C++ and Objective-C classes, C structs/unions, and
5805/// Objective-C protocols, categories, and extensions are all defined in a
5806/// single place in the source code, so they have definitive module files
5807/// associated with them. C++ namespaces, on the other hand, can have
5808/// definitions in multiple different module files.
5809///
5810/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
5811/// NDEBUG checking.
5812static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
5813 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00005814 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
5815 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00005816
5817 return 0;
5818}
5819
Richard Smith9ce12e32013-02-07 03:30:24 +00005820bool
Guy Benyei11169dd2012-12-18 14:30:41 +00005821ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5822 DeclarationName Name) {
5823 assert(DC->hasExternalVisibleStorage() &&
5824 "DeclContext has no visible decls in storage");
5825 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00005826 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005827
5828 SmallVector<NamedDecl *, 64> Decls;
5829
5830 // Compute the declaration contexts we need to look into. Multiple such
5831 // declaration contexts occur when two declaration contexts from disjoint
5832 // modules get merged, e.g., when two namespaces with the same name are
5833 // independently defined in separate modules.
5834 SmallVector<const DeclContext *, 2> Contexts;
5835 Contexts.push_back(DC);
5836
5837 if (DC->isNamespace()) {
5838 MergedDeclsMap::iterator Merged
5839 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5840 if (Merged != MergedDecls.end()) {
5841 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5842 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5843 }
5844 }
5845
5846 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00005847
5848 // If we can definitively determine which module file to look into,
5849 // only look there. Otherwise, look in all module files.
5850 ModuleFile *Definitive;
5851 if (Contexts.size() == 1 &&
5852 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
5853 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
5854 } else {
5855 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5856 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005857 ++NumVisibleDeclContextsRead;
5858 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00005859 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00005860}
5861
5862namespace {
5863 /// \brief ModuleFile visitor used to retrieve all visible names in a
5864 /// declaration context.
5865 class DeclContextAllNamesVisitor {
5866 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005867 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00005868 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00005869 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00005870
5871 public:
5872 DeclContextAllNamesVisitor(ASTReader &Reader,
5873 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00005874 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00005875 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005876
5877 static bool visit(ModuleFile &M, void *UserData) {
5878 DeclContextAllNamesVisitor *This
5879 = static_cast<DeclContextAllNamesVisitor *>(UserData);
5880
5881 // Check whether we have any visible declaration information for
5882 // this context in this module.
5883 ModuleFile::DeclContextInfosMap::iterator Info;
5884 bool FoundInfo = false;
5885 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5886 Info = M.DeclContextInfos.find(This->Contexts[I]);
5887 if (Info != M.DeclContextInfos.end() &&
5888 Info->second.NameLookupTableData) {
5889 FoundInfo = true;
5890 break;
5891 }
5892 }
5893
5894 if (!FoundInfo)
5895 return false;
5896
5897 ASTDeclContextNameLookupTable *LookupTable =
5898 Info->second.NameLookupTableData;
5899 bool FoundAnything = false;
5900 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00005901 I = LookupTable->data_begin(), E = LookupTable->data_end();
5902 I != E;
5903 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 ASTDeclContextNameLookupTrait::data_type Data = *I;
5905 for (; Data.first != Data.second; ++Data.first) {
5906 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5907 *Data.first);
5908 if (!ND)
5909 continue;
5910
5911 // Record this declaration.
5912 FoundAnything = true;
5913 This->Decls[ND->getDeclName()].push_back(ND);
5914 }
5915 }
5916
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00005917 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 }
5919 };
5920}
5921
5922void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5923 if (!DC->hasExternalVisibleStorage())
5924 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00005925 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00005926
5927 // Compute the declaration contexts we need to look into. Multiple such
5928 // declaration contexts occur when two declaration contexts from disjoint
5929 // modules get merged, e.g., when two namespaces with the same name are
5930 // independently defined in separate modules.
5931 SmallVector<const DeclContext *, 2> Contexts;
5932 Contexts.push_back(DC);
5933
5934 if (DC->isNamespace()) {
5935 MergedDeclsMap::iterator Merged
5936 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5937 if (Merged != MergedDecls.end()) {
5938 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5939 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5940 }
5941 }
5942
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00005943 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
5944 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00005945 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5946 ++NumVisibleDeclContextsRead;
5947
Craig Topper79be4cd2013-07-05 04:33:53 +00005948 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005949 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5950 }
5951 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5952}
5953
5954/// \brief Under non-PCH compilation the consumer receives the objc methods
5955/// before receiving the implementation, and codegen depends on this.
5956/// We simulate this by deserializing and passing to consumer the methods of the
5957/// implementation before passing the deserialized implementation decl.
5958static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5959 ASTConsumer *Consumer) {
5960 assert(ImplD && Consumer);
5961
5962 for (ObjCImplDecl::method_iterator
5963 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5964 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5965
5966 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5967}
5968
5969void ASTReader::PassInterestingDeclsToConsumer() {
5970 assert(Consumer);
5971 while (!InterestingDecls.empty()) {
5972 Decl *D = InterestingDecls.front();
5973 InterestingDecls.pop_front();
5974
5975 PassInterestingDeclToConsumer(D);
5976 }
5977}
5978
5979void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5980 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5981 PassObjCImplDeclToConsumer(ImplD, Consumer);
5982 else
5983 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5984}
5985
5986void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5987 this->Consumer = Consumer;
5988
5989 if (!Consumer)
5990 return;
5991
Ben Langmuir332aafe2014-01-31 01:06:56 +00005992 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005993 // Force deserialization of this decl, which will cause it to be queued for
5994 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00005995 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005996 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00005997 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005998
5999 PassInterestingDeclsToConsumer();
6000}
6001
6002void ASTReader::PrintStats() {
6003 std::fprintf(stderr, "*** AST File Statistics:\n");
6004
6005 unsigned NumTypesLoaded
6006 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6007 QualType());
6008 unsigned NumDeclsLoaded
6009 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6010 (Decl *)0);
6011 unsigned NumIdentifiersLoaded
6012 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6013 IdentifiersLoaded.end(),
6014 (IdentifierInfo *)0);
6015 unsigned NumMacrosLoaded
6016 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6017 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006018 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 unsigned NumSelectorsLoaded
6020 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6021 SelectorsLoaded.end(),
6022 Selector());
6023
6024 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6025 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6026 NumSLocEntriesRead, TotalNumSLocEntries,
6027 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6028 if (!TypesLoaded.empty())
6029 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6030 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6031 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6032 if (!DeclsLoaded.empty())
6033 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6034 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6035 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6036 if (!IdentifiersLoaded.empty())
6037 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6038 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6039 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6040 if (!MacrosLoaded.empty())
6041 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6042 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6043 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6044 if (!SelectorsLoaded.empty())
6045 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6046 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6047 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6048 if (TotalNumStatements)
6049 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6050 NumStatementsRead, TotalNumStatements,
6051 ((float)NumStatementsRead/TotalNumStatements * 100));
6052 if (TotalNumMacros)
6053 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6054 NumMacrosRead, TotalNumMacros,
6055 ((float)NumMacrosRead/TotalNumMacros * 100));
6056 if (TotalLexicalDeclContexts)
6057 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6058 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6059 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6060 * 100));
6061 if (TotalVisibleDeclContexts)
6062 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6063 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6064 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6065 * 100));
6066 if (TotalNumMethodPoolEntries) {
6067 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6068 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6069 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6070 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006072 if (NumMethodPoolLookups) {
6073 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6074 NumMethodPoolHits, NumMethodPoolLookups,
6075 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6076 }
6077 if (NumMethodPoolTableLookups) {
6078 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6079 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6080 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6081 * 100.0));
6082 }
6083
Douglas Gregor00a50f72013-01-25 00:38:33 +00006084 if (NumIdentifierLookupHits) {
6085 std::fprintf(stderr,
6086 " %u / %u identifier table lookups succeeded (%f%%)\n",
6087 NumIdentifierLookupHits, NumIdentifierLookups,
6088 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6089 }
6090
Douglas Gregore060e572013-01-25 01:03:03 +00006091 if (GlobalIndex) {
6092 std::fprintf(stderr, "\n");
6093 GlobalIndex->printStats();
6094 }
6095
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 std::fprintf(stderr, "\n");
6097 dump();
6098 std::fprintf(stderr, "\n");
6099}
6100
6101template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6102static void
6103dumpModuleIDMap(StringRef Name,
6104 const ContinuousRangeMap<Key, ModuleFile *,
6105 InitialCapacity> &Map) {
6106 if (Map.begin() == Map.end())
6107 return;
6108
6109 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6110 llvm::errs() << Name << ":\n";
6111 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6112 I != IEnd; ++I) {
6113 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6114 << "\n";
6115 }
6116}
6117
6118void ASTReader::dump() {
6119 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6120 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6121 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6122 dumpModuleIDMap("Global type map", GlobalTypeMap);
6123 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6124 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6125 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6126 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6127 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6128 dumpModuleIDMap("Global preprocessed entity map",
6129 GlobalPreprocessedEntityMap);
6130
6131 llvm::errs() << "\n*** PCH/Modules Loaded:";
6132 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6133 MEnd = ModuleMgr.end();
6134 M != MEnd; ++M)
6135 (*M)->dump();
6136}
6137
6138/// Return the amount of memory used by memory buffers, breaking down
6139/// by heap-backed versus mmap'ed memory.
6140void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6141 for (ModuleConstIterator I = ModuleMgr.begin(),
6142 E = ModuleMgr.end(); I != E; ++I) {
6143 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6144 size_t bytes = buf->getBufferSize();
6145 switch (buf->getBufferKind()) {
6146 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6147 sizes.malloc_bytes += bytes;
6148 break;
6149 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6150 sizes.mmap_bytes += bytes;
6151 break;
6152 }
6153 }
6154 }
6155}
6156
6157void ASTReader::InitializeSema(Sema &S) {
6158 SemaObj = &S;
6159 S.addExternalSource(this);
6160
6161 // Makes sure any declarations that were deserialized "too early"
6162 // still get added to the identifier's declaration chains.
6163 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006164 pushExternalDeclIntoScope(PreloadedDecls[I],
6165 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 }
6167 PreloadedDecls.clear();
6168
Richard Smith3d8e97e2013-10-18 06:54:39 +00006169 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (!FPPragmaOptions.empty()) {
6171 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6172 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6173 }
6174
Richard Smith3d8e97e2013-10-18 06:54:39 +00006175 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 if (!OpenCLExtensions.empty()) {
6177 unsigned I = 0;
6178#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6179#include "clang/Basic/OpenCLExtensions.def"
6180
6181 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6182 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006183
6184 UpdateSema();
6185}
6186
6187void ASTReader::UpdateSema() {
6188 assert(SemaObj && "no Sema to update");
6189
6190 // Load the offsets of the declarations that Sema references.
6191 // They will be lazily deserialized when needed.
6192 if (!SemaDeclRefs.empty()) {
6193 assert(SemaDeclRefs.size() % 2 == 0);
6194 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6195 if (!SemaObj->StdNamespace)
6196 SemaObj->StdNamespace = SemaDeclRefs[I];
6197 if (!SemaObj->StdBadAlloc)
6198 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6199 }
6200 SemaDeclRefs.clear();
6201 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006202}
6203
6204IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6205 // Note that we are loading an identifier.
6206 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006207 StringRef Name(NameStart, NameEnd - NameStart);
6208
6209 // If there is a global index, look there first to determine which modules
6210 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006211 GlobalModuleIndex::HitSet Hits;
6212 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006213 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006214 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6215 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006216 }
6217 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006218 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006219 NumIdentifierLookups,
6220 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006221 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006222 IdentifierInfo *II = Visitor.getIdentifierInfo();
6223 markIdentifierUpToDate(II);
6224 return II;
6225}
6226
6227namespace clang {
6228 /// \brief An identifier-lookup iterator that enumerates all of the
6229 /// identifiers stored within a set of AST files.
6230 class ASTIdentifierIterator : public IdentifierIterator {
6231 /// \brief The AST reader whose identifiers are being enumerated.
6232 const ASTReader &Reader;
6233
6234 /// \brief The current index into the chain of AST files stored in
6235 /// the AST reader.
6236 unsigned Index;
6237
6238 /// \brief The current position within the identifier lookup table
6239 /// of the current AST file.
6240 ASTIdentifierLookupTable::key_iterator Current;
6241
6242 /// \brief The end position within the identifier lookup table of
6243 /// the current AST file.
6244 ASTIdentifierLookupTable::key_iterator End;
6245
6246 public:
6247 explicit ASTIdentifierIterator(const ASTReader &Reader);
6248
6249 virtual StringRef Next();
6250 };
6251}
6252
6253ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6254 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6255 ASTIdentifierLookupTable *IdTable
6256 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6257 Current = IdTable->key_begin();
6258 End = IdTable->key_end();
6259}
6260
6261StringRef ASTIdentifierIterator::Next() {
6262 while (Current == End) {
6263 // If we have exhausted all of our AST files, we're done.
6264 if (Index == 0)
6265 return StringRef();
6266
6267 --Index;
6268 ASTIdentifierLookupTable *IdTable
6269 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6270 IdentifierLookupTable;
6271 Current = IdTable->key_begin();
6272 End = IdTable->key_end();
6273 }
6274
6275 // We have any identifiers remaining in the current AST file; return
6276 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006277 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006278 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006279 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006280}
6281
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006282IdentifierIterator *ASTReader::getIdentifiers() {
6283 if (!loadGlobalIndex())
6284 return GlobalIndex->createIdentifierIterator();
6285
Guy Benyei11169dd2012-12-18 14:30:41 +00006286 return new ASTIdentifierIterator(*this);
6287}
6288
6289namespace clang { namespace serialization {
6290 class ReadMethodPoolVisitor {
6291 ASTReader &Reader;
6292 Selector Sel;
6293 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006294 unsigned InstanceBits;
6295 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006296 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6297 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006298
6299 public:
6300 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6301 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006302 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6303 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006304
6305 static bool visit(ModuleFile &M, void *UserData) {
6306 ReadMethodPoolVisitor *This
6307 = static_cast<ReadMethodPoolVisitor *>(UserData);
6308
6309 if (!M.SelectorLookupTable)
6310 return false;
6311
6312 // If we've already searched this module file, skip it now.
6313 if (M.Generation <= This->PriorGeneration)
6314 return true;
6315
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006316 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006317 ASTSelectorLookupTable *PoolTable
6318 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6319 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6320 if (Pos == PoolTable->end())
6321 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006322
6323 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 ++This->Reader.NumSelectorsRead;
6325 // FIXME: Not quite happy with the statistics here. We probably should
6326 // disable this tracking when called via LoadSelector.
6327 // Also, should entries without methods count as misses?
6328 ++This->Reader.NumMethodPoolEntriesRead;
6329 ASTSelectorLookupTrait::data_type Data = *Pos;
6330 if (This->Reader.DeserializationListener)
6331 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6332 This->Sel);
6333
6334 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6335 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006336 This->InstanceBits = Data.InstanceBits;
6337 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006338 return true;
6339 }
6340
6341 /// \brief Retrieve the instance methods found by this visitor.
6342 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6343 return InstanceMethods;
6344 }
6345
6346 /// \brief Retrieve the instance methods found by this visitor.
6347 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6348 return FactoryMethods;
6349 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006350
6351 unsigned getInstanceBits() const { return InstanceBits; }
6352 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 };
6354} } // end namespace clang::serialization
6355
6356/// \brief Add the given set of methods to the method list.
6357static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6358 ObjCMethodList &List) {
6359 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6360 S.addMethodToGlobalList(&List, Methods[I]);
6361 }
6362}
6363
6364void ASTReader::ReadMethodPool(Selector Sel) {
6365 // Get the selector generation and update it to the current generation.
6366 unsigned &Generation = SelectorGeneration[Sel];
6367 unsigned PriorGeneration = Generation;
6368 Generation = CurrentGeneration;
6369
6370 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006371 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6373 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6374
6375 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006376 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006378
6379 ++NumMethodPoolHits;
6380
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 if (!getSema())
6382 return;
6383
6384 Sema &S = *getSema();
6385 Sema::GlobalMethodPool::iterator Pos
6386 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6387
6388 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6389 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006390 Pos->second.first.setBits(Visitor.getInstanceBits());
6391 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006392}
6393
6394void ASTReader::ReadKnownNamespaces(
6395 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6396 Namespaces.clear();
6397
6398 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6399 if (NamespaceDecl *Namespace
6400 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6401 Namespaces.push_back(Namespace);
6402 }
6403}
6404
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006405void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006406 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006407 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6408 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006409 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006410 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006411 Undefined.insert(std::make_pair(D, Loc));
6412 }
6413}
Nick Lewycky8334af82013-01-26 00:35:08 +00006414
Guy Benyei11169dd2012-12-18 14:30:41 +00006415void ASTReader::ReadTentativeDefinitions(
6416 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6417 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6418 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6419 if (Var)
6420 TentativeDefs.push_back(Var);
6421 }
6422 TentativeDefinitions.clear();
6423}
6424
6425void ASTReader::ReadUnusedFileScopedDecls(
6426 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6427 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6428 DeclaratorDecl *D
6429 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6430 if (D)
6431 Decls.push_back(D);
6432 }
6433 UnusedFileScopedDecls.clear();
6434}
6435
6436void ASTReader::ReadDelegatingConstructors(
6437 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6438 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6439 CXXConstructorDecl *D
6440 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6441 if (D)
6442 Decls.push_back(D);
6443 }
6444 DelegatingCtorDecls.clear();
6445}
6446
6447void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6448 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6449 TypedefNameDecl *D
6450 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6451 if (D)
6452 Decls.push_back(D);
6453 }
6454 ExtVectorDecls.clear();
6455}
6456
6457void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6458 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6459 CXXRecordDecl *D
6460 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6461 if (D)
6462 Decls.push_back(D);
6463 }
6464 DynamicClasses.clear();
6465}
6466
6467void
Richard Smith78165b52013-01-10 23:43:47 +00006468ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6469 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6470 NamedDecl *D
6471 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 if (D)
6473 Decls.push_back(D);
6474 }
Richard Smith78165b52013-01-10 23:43:47 +00006475 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006476}
6477
6478void ASTReader::ReadReferencedSelectors(
6479 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6480 if (ReferencedSelectorsData.empty())
6481 return;
6482
6483 // If there are @selector references added them to its pool. This is for
6484 // implementation of -Wselector.
6485 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6486 unsigned I = 0;
6487 while (I < DataSize) {
6488 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6489 SourceLocation SelLoc
6490 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6491 Sels.push_back(std::make_pair(Sel, SelLoc));
6492 }
6493 ReferencedSelectorsData.clear();
6494}
6495
6496void ASTReader::ReadWeakUndeclaredIdentifiers(
6497 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6498 if (WeakUndeclaredIdentifiers.empty())
6499 return;
6500
6501 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6502 IdentifierInfo *WeakId
6503 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6504 IdentifierInfo *AliasId
6505 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6506 SourceLocation Loc
6507 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6508 bool Used = WeakUndeclaredIdentifiers[I++];
6509 WeakInfo WI(AliasId, Loc);
6510 WI.setUsed(Used);
6511 WeakIDs.push_back(std::make_pair(WeakId, WI));
6512 }
6513 WeakUndeclaredIdentifiers.clear();
6514}
6515
6516void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6517 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6518 ExternalVTableUse VT;
6519 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6520 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6521 VT.DefinitionRequired = VTableUses[Idx++];
6522 VTables.push_back(VT);
6523 }
6524
6525 VTableUses.clear();
6526}
6527
6528void ASTReader::ReadPendingInstantiations(
6529 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6530 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6531 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6532 SourceLocation Loc
6533 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6534
6535 Pending.push_back(std::make_pair(D, Loc));
6536 }
6537 PendingInstantiations.clear();
6538}
6539
Richard Smithe40f2ba2013-08-07 21:41:30 +00006540void ASTReader::ReadLateParsedTemplates(
6541 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6542 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6543 /* In loop */) {
6544 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6545
6546 LateParsedTemplate *LT = new LateParsedTemplate;
6547 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6548
6549 ModuleFile *F = getOwningModuleFile(LT->D);
6550 assert(F && "No module");
6551
6552 unsigned TokN = LateParsedTemplates[Idx++];
6553 LT->Toks.reserve(TokN);
6554 for (unsigned T = 0; T < TokN; ++T)
6555 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6556
6557 LPTMap[FD] = LT;
6558 }
6559
6560 LateParsedTemplates.clear();
6561}
6562
Guy Benyei11169dd2012-12-18 14:30:41 +00006563void ASTReader::LoadSelector(Selector Sel) {
6564 // It would be complicated to avoid reading the methods anyway. So don't.
6565 ReadMethodPool(Sel);
6566}
6567
6568void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6569 assert(ID && "Non-zero identifier ID required");
6570 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6571 IdentifiersLoaded[ID - 1] = II;
6572 if (DeserializationListener)
6573 DeserializationListener->IdentifierRead(ID, II);
6574}
6575
6576/// \brief Set the globally-visible declarations associated with the given
6577/// identifier.
6578///
6579/// If the AST reader is currently in a state where the given declaration IDs
6580/// cannot safely be resolved, they are queued until it is safe to resolve
6581/// them.
6582///
6583/// \param II an IdentifierInfo that refers to one or more globally-visible
6584/// declarations.
6585///
6586/// \param DeclIDs the set of declaration IDs with the name @p II that are
6587/// visible at global scope.
6588///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006589/// \param Decls if non-null, this vector will be populated with the set of
6590/// deserialized declarations. These declarations will not be pushed into
6591/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006592void
6593ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6594 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006595 SmallVectorImpl<Decl *> *Decls) {
6596 if (NumCurrentElementsDeserializing && !Decls) {
6597 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 return;
6599 }
6600
6601 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6602 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6603 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006604 // If we're simply supposed to record the declarations, do so now.
6605 if (Decls) {
6606 Decls->push_back(D);
6607 continue;
6608 }
6609
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 // Introduce this declaration into the translation-unit scope
6611 // and add it to the declaration chain for this identifier, so
6612 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006613 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 } else {
6615 // Queue this declaration so that it will be added to the
6616 // translation unit scope and identifier's declaration chain
6617 // once a Sema object is known.
6618 PreloadedDecls.push_back(D);
6619 }
6620 }
6621}
6622
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006623IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 if (ID == 0)
6625 return 0;
6626
6627 if (IdentifiersLoaded.empty()) {
6628 Error("no identifier table in AST file");
6629 return 0;
6630 }
6631
6632 ID -= 1;
6633 if (!IdentifiersLoaded[ID]) {
6634 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6635 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6636 ModuleFile *M = I->second;
6637 unsigned Index = ID - M->BaseIdentifierID;
6638 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6639
6640 // All of the strings in the AST file are preceded by a 16-bit length.
6641 // Extract that 16-bit length to avoid having to execute strlen().
6642 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6643 // unsigned integers. This is important to avoid integer overflow when
6644 // we cast them to 'unsigned'.
6645 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6646 unsigned StrLen = (((unsigned) StrLenPtr[0])
6647 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006648 IdentifiersLoaded[ID]
6649 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 if (DeserializationListener)
6651 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6652 }
6653
6654 return IdentifiersLoaded[ID];
6655}
6656
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006657IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6658 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
6660
6661IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6662 if (LocalID < NUM_PREDEF_IDENT_IDS)
6663 return LocalID;
6664
6665 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6666 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6667 assert(I != M.IdentifierRemap.end()
6668 && "Invalid index into identifier index remap");
6669
6670 return LocalID + I->second;
6671}
6672
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006673MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 if (ID == 0)
6675 return 0;
6676
6677 if (MacrosLoaded.empty()) {
6678 Error("no macro table in AST file");
6679 return 0;
6680 }
6681
6682 ID -= NUM_PREDEF_MACRO_IDS;
6683 if (!MacrosLoaded[ID]) {
6684 GlobalMacroMapType::iterator I
6685 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6686 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6687 ModuleFile *M = I->second;
6688 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006689 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6690
6691 if (DeserializationListener)
6692 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6693 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 }
6695
6696 return MacrosLoaded[ID];
6697}
6698
6699MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6700 if (LocalID < NUM_PREDEF_MACRO_IDS)
6701 return LocalID;
6702
6703 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6704 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6705 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6706
6707 return LocalID + I->second;
6708}
6709
6710serialization::SubmoduleID
6711ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6712 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6713 return LocalID;
6714
6715 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6716 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6717 assert(I != M.SubmoduleRemap.end()
6718 && "Invalid index into submodule index remap");
6719
6720 return LocalID + I->second;
6721}
6722
6723Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6724 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6725 assert(GlobalID == 0 && "Unhandled global submodule ID");
6726 return 0;
6727 }
6728
6729 if (GlobalID > SubmodulesLoaded.size()) {
6730 Error("submodule ID out of range in AST file");
6731 return 0;
6732 }
6733
6734 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6735}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00006736
6737Module *ASTReader::getModule(unsigned ID) {
6738 return getSubmodule(ID);
6739}
6740
Guy Benyei11169dd2012-12-18 14:30:41 +00006741Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6742 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6743}
6744
6745Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6746 if (ID == 0)
6747 return Selector();
6748
6749 if (ID > SelectorsLoaded.size()) {
6750 Error("selector ID out of range in AST file");
6751 return Selector();
6752 }
6753
6754 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6755 // Load this selector from the selector table.
6756 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6757 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6758 ModuleFile &M = *I->second;
6759 ASTSelectorLookupTrait Trait(*this, M);
6760 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6761 SelectorsLoaded[ID - 1] =
6762 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6763 if (DeserializationListener)
6764 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6765 }
6766
6767 return SelectorsLoaded[ID - 1];
6768}
6769
6770Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6771 return DecodeSelector(ID);
6772}
6773
6774uint32_t ASTReader::GetNumExternalSelectors() {
6775 // ID 0 (the null selector) is considered an external selector.
6776 return getTotalNumSelectors() + 1;
6777}
6778
6779serialization::SelectorID
6780ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6781 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6782 return LocalID;
6783
6784 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6785 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6786 assert(I != M.SelectorRemap.end()
6787 && "Invalid index into selector index remap");
6788
6789 return LocalID + I->second;
6790}
6791
6792DeclarationName
6793ASTReader::ReadDeclarationName(ModuleFile &F,
6794 const RecordData &Record, unsigned &Idx) {
6795 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6796 switch (Kind) {
6797 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006798 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006799
6800 case DeclarationName::ObjCZeroArgSelector:
6801 case DeclarationName::ObjCOneArgSelector:
6802 case DeclarationName::ObjCMultiArgSelector:
6803 return DeclarationName(ReadSelector(F, Record, Idx));
6804
6805 case DeclarationName::CXXConstructorName:
6806 return Context.DeclarationNames.getCXXConstructorName(
6807 Context.getCanonicalType(readType(F, Record, Idx)));
6808
6809 case DeclarationName::CXXDestructorName:
6810 return Context.DeclarationNames.getCXXDestructorName(
6811 Context.getCanonicalType(readType(F, Record, Idx)));
6812
6813 case DeclarationName::CXXConversionFunctionName:
6814 return Context.DeclarationNames.getCXXConversionFunctionName(
6815 Context.getCanonicalType(readType(F, Record, Idx)));
6816
6817 case DeclarationName::CXXOperatorName:
6818 return Context.DeclarationNames.getCXXOperatorName(
6819 (OverloadedOperatorKind)Record[Idx++]);
6820
6821 case DeclarationName::CXXLiteralOperatorName:
6822 return Context.DeclarationNames.getCXXLiteralOperatorName(
6823 GetIdentifierInfo(F, Record, Idx));
6824
6825 case DeclarationName::CXXUsingDirective:
6826 return DeclarationName::getUsingDirectiveName();
6827 }
6828
6829 llvm_unreachable("Invalid NameKind!");
6830}
6831
6832void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6833 DeclarationNameLoc &DNLoc,
6834 DeclarationName Name,
6835 const RecordData &Record, unsigned &Idx) {
6836 switch (Name.getNameKind()) {
6837 case DeclarationName::CXXConstructorName:
6838 case DeclarationName::CXXDestructorName:
6839 case DeclarationName::CXXConversionFunctionName:
6840 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6841 break;
6842
6843 case DeclarationName::CXXOperatorName:
6844 DNLoc.CXXOperatorName.BeginOpNameLoc
6845 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6846 DNLoc.CXXOperatorName.EndOpNameLoc
6847 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6848 break;
6849
6850 case DeclarationName::CXXLiteralOperatorName:
6851 DNLoc.CXXLiteralOperatorName.OpNameLoc
6852 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6853 break;
6854
6855 case DeclarationName::Identifier:
6856 case DeclarationName::ObjCZeroArgSelector:
6857 case DeclarationName::ObjCOneArgSelector:
6858 case DeclarationName::ObjCMultiArgSelector:
6859 case DeclarationName::CXXUsingDirective:
6860 break;
6861 }
6862}
6863
6864void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6865 DeclarationNameInfo &NameInfo,
6866 const RecordData &Record, unsigned &Idx) {
6867 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6868 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6869 DeclarationNameLoc DNLoc;
6870 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6871 NameInfo.setInfo(DNLoc);
6872}
6873
6874void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6875 const RecordData &Record, unsigned &Idx) {
6876 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6877 unsigned NumTPLists = Record[Idx++];
6878 Info.NumTemplParamLists = NumTPLists;
6879 if (NumTPLists) {
6880 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6881 for (unsigned i=0; i != NumTPLists; ++i)
6882 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6883 }
6884}
6885
6886TemplateName
6887ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6888 unsigned &Idx) {
6889 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6890 switch (Kind) {
6891 case TemplateName::Template:
6892 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6893
6894 case TemplateName::OverloadedTemplate: {
6895 unsigned size = Record[Idx++];
6896 UnresolvedSet<8> Decls;
6897 while (size--)
6898 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6899
6900 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6901 }
6902
6903 case TemplateName::QualifiedTemplate: {
6904 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6905 bool hasTemplKeyword = Record[Idx++];
6906 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6907 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6908 }
6909
6910 case TemplateName::DependentTemplate: {
6911 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6912 if (Record[Idx++]) // isIdentifier
6913 return Context.getDependentTemplateName(NNS,
6914 GetIdentifierInfo(F, Record,
6915 Idx));
6916 return Context.getDependentTemplateName(NNS,
6917 (OverloadedOperatorKind)Record[Idx++]);
6918 }
6919
6920 case TemplateName::SubstTemplateTemplateParm: {
6921 TemplateTemplateParmDecl *param
6922 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6923 if (!param) return TemplateName();
6924 TemplateName replacement = ReadTemplateName(F, Record, Idx);
6925 return Context.getSubstTemplateTemplateParm(param, replacement);
6926 }
6927
6928 case TemplateName::SubstTemplateTemplateParmPack: {
6929 TemplateTemplateParmDecl *Param
6930 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6931 if (!Param)
6932 return TemplateName();
6933
6934 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6935 if (ArgPack.getKind() != TemplateArgument::Pack)
6936 return TemplateName();
6937
6938 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6939 }
6940 }
6941
6942 llvm_unreachable("Unhandled template name kind!");
6943}
6944
6945TemplateArgument
6946ASTReader::ReadTemplateArgument(ModuleFile &F,
6947 const RecordData &Record, unsigned &Idx) {
6948 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6949 switch (Kind) {
6950 case TemplateArgument::Null:
6951 return TemplateArgument();
6952 case TemplateArgument::Type:
6953 return TemplateArgument(readType(F, Record, Idx));
6954 case TemplateArgument::Declaration: {
6955 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6956 bool ForReferenceParam = Record[Idx++];
6957 return TemplateArgument(D, ForReferenceParam);
6958 }
6959 case TemplateArgument::NullPtr:
6960 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6961 case TemplateArgument::Integral: {
6962 llvm::APSInt Value = ReadAPSInt(Record, Idx);
6963 QualType T = readType(F, Record, Idx);
6964 return TemplateArgument(Context, Value, T);
6965 }
6966 case TemplateArgument::Template:
6967 return TemplateArgument(ReadTemplateName(F, Record, Idx));
6968 case TemplateArgument::TemplateExpansion: {
6969 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00006970 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 if (unsigned NumExpansions = Record[Idx++])
6972 NumTemplateExpansions = NumExpansions - 1;
6973 return TemplateArgument(Name, NumTemplateExpansions);
6974 }
6975 case TemplateArgument::Expression:
6976 return TemplateArgument(ReadExpr(F));
6977 case TemplateArgument::Pack: {
6978 unsigned NumArgs = Record[Idx++];
6979 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6980 for (unsigned I = 0; I != NumArgs; ++I)
6981 Args[I] = ReadTemplateArgument(F, Record, Idx);
6982 return TemplateArgument(Args, NumArgs);
6983 }
6984 }
6985
6986 llvm_unreachable("Unhandled template argument kind!");
6987}
6988
6989TemplateParameterList *
6990ASTReader::ReadTemplateParameterList(ModuleFile &F,
6991 const RecordData &Record, unsigned &Idx) {
6992 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6993 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6994 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6995
6996 unsigned NumParams = Record[Idx++];
6997 SmallVector<NamedDecl *, 16> Params;
6998 Params.reserve(NumParams);
6999 while (NumParams--)
7000 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7001
7002 TemplateParameterList* TemplateParams =
7003 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7004 Params.data(), Params.size(), RAngleLoc);
7005 return TemplateParams;
7006}
7007
7008void
7009ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007010ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 ModuleFile &F, const RecordData &Record,
7012 unsigned &Idx) {
7013 unsigned NumTemplateArgs = Record[Idx++];
7014 TemplArgs.reserve(NumTemplateArgs);
7015 while (NumTemplateArgs--)
7016 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7017}
7018
7019/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007020void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 const RecordData &Record, unsigned &Idx) {
7022 unsigned NumDecls = Record[Idx++];
7023 Set.reserve(Context, NumDecls);
7024 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007025 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007027 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 }
7029}
7030
7031CXXBaseSpecifier
7032ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7033 const RecordData &Record, unsigned &Idx) {
7034 bool isVirtual = static_cast<bool>(Record[Idx++]);
7035 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7036 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7037 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7038 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7039 SourceRange Range = ReadSourceRange(F, Record, Idx);
7040 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7041 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7042 EllipsisLoc);
7043 Result.setInheritConstructors(inheritConstructors);
7044 return Result;
7045}
7046
7047std::pair<CXXCtorInitializer **, unsigned>
7048ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7049 unsigned &Idx) {
7050 CXXCtorInitializer **CtorInitializers = 0;
7051 unsigned NumInitializers = Record[Idx++];
7052 if (NumInitializers) {
7053 CtorInitializers
7054 = new (Context) CXXCtorInitializer*[NumInitializers];
7055 for (unsigned i=0; i != NumInitializers; ++i) {
7056 TypeSourceInfo *TInfo = 0;
7057 bool IsBaseVirtual = false;
7058 FieldDecl *Member = 0;
7059 IndirectFieldDecl *IndirectMember = 0;
7060
7061 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7062 switch (Type) {
7063 case CTOR_INITIALIZER_BASE:
7064 TInfo = GetTypeSourceInfo(F, Record, Idx);
7065 IsBaseVirtual = Record[Idx++];
7066 break;
7067
7068 case CTOR_INITIALIZER_DELEGATING:
7069 TInfo = GetTypeSourceInfo(F, Record, Idx);
7070 break;
7071
7072 case CTOR_INITIALIZER_MEMBER:
7073 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7074 break;
7075
7076 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7077 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7078 break;
7079 }
7080
7081 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7082 Expr *Init = ReadExpr(F);
7083 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7084 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7085 bool IsWritten = Record[Idx++];
7086 unsigned SourceOrderOrNumArrayIndices;
7087 SmallVector<VarDecl *, 8> Indices;
7088 if (IsWritten) {
7089 SourceOrderOrNumArrayIndices = Record[Idx++];
7090 } else {
7091 SourceOrderOrNumArrayIndices = Record[Idx++];
7092 Indices.reserve(SourceOrderOrNumArrayIndices);
7093 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7094 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7095 }
7096
7097 CXXCtorInitializer *BOMInit;
7098 if (Type == CTOR_INITIALIZER_BASE) {
7099 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7100 LParenLoc, Init, RParenLoc,
7101 MemberOrEllipsisLoc);
7102 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7103 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7104 Init, RParenLoc);
7105 } else if (IsWritten) {
7106 if (Member)
7107 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7108 LParenLoc, Init, RParenLoc);
7109 else
7110 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7111 MemberOrEllipsisLoc, LParenLoc,
7112 Init, RParenLoc);
7113 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007114 if (IndirectMember) {
7115 assert(Indices.empty() && "Indirect field improperly initialized");
7116 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7117 MemberOrEllipsisLoc, LParenLoc,
7118 Init, RParenLoc);
7119 } else {
7120 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7121 LParenLoc, Init, RParenLoc,
7122 Indices.data(), Indices.size());
7123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 }
7125
7126 if (IsWritten)
7127 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7128 CtorInitializers[i] = BOMInit;
7129 }
7130 }
7131
7132 return std::make_pair(CtorInitializers, NumInitializers);
7133}
7134
7135NestedNameSpecifier *
7136ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7137 const RecordData &Record, unsigned &Idx) {
7138 unsigned N = Record[Idx++];
7139 NestedNameSpecifier *NNS = 0, *Prev = 0;
7140 for (unsigned I = 0; I != N; ++I) {
7141 NestedNameSpecifier::SpecifierKind Kind
7142 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7143 switch (Kind) {
7144 case NestedNameSpecifier::Identifier: {
7145 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7146 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7147 break;
7148 }
7149
7150 case NestedNameSpecifier::Namespace: {
7151 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7152 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7153 break;
7154 }
7155
7156 case NestedNameSpecifier::NamespaceAlias: {
7157 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7158 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7159 break;
7160 }
7161
7162 case NestedNameSpecifier::TypeSpec:
7163 case NestedNameSpecifier::TypeSpecWithTemplate: {
7164 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7165 if (!T)
7166 return 0;
7167
7168 bool Template = Record[Idx++];
7169 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7170 break;
7171 }
7172
7173 case NestedNameSpecifier::Global: {
7174 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7175 // No associated value, and there can't be a prefix.
7176 break;
7177 }
7178 }
7179 Prev = NNS;
7180 }
7181 return NNS;
7182}
7183
7184NestedNameSpecifierLoc
7185ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7186 unsigned &Idx) {
7187 unsigned N = Record[Idx++];
7188 NestedNameSpecifierLocBuilder Builder;
7189 for (unsigned I = 0; I != N; ++I) {
7190 NestedNameSpecifier::SpecifierKind Kind
7191 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7192 switch (Kind) {
7193 case NestedNameSpecifier::Identifier: {
7194 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7195 SourceRange Range = ReadSourceRange(F, Record, Idx);
7196 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7197 break;
7198 }
7199
7200 case NestedNameSpecifier::Namespace: {
7201 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7202 SourceRange Range = ReadSourceRange(F, Record, Idx);
7203 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7204 break;
7205 }
7206
7207 case NestedNameSpecifier::NamespaceAlias: {
7208 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7209 SourceRange Range = ReadSourceRange(F, Record, Idx);
7210 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7211 break;
7212 }
7213
7214 case NestedNameSpecifier::TypeSpec:
7215 case NestedNameSpecifier::TypeSpecWithTemplate: {
7216 bool Template = Record[Idx++];
7217 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7218 if (!T)
7219 return NestedNameSpecifierLoc();
7220 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7221
7222 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7223 Builder.Extend(Context,
7224 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7225 T->getTypeLoc(), ColonColonLoc);
7226 break;
7227 }
7228
7229 case NestedNameSpecifier::Global: {
7230 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7231 Builder.MakeGlobal(Context, ColonColonLoc);
7232 break;
7233 }
7234 }
7235 }
7236
7237 return Builder.getWithLocInContext(Context);
7238}
7239
7240SourceRange
7241ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7242 unsigned &Idx) {
7243 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7244 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7245 return SourceRange(beg, end);
7246}
7247
7248/// \brief Read an integral value
7249llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7250 unsigned BitWidth = Record[Idx++];
7251 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7252 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7253 Idx += NumWords;
7254 return Result;
7255}
7256
7257/// \brief Read a signed integral value
7258llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7259 bool isUnsigned = Record[Idx++];
7260 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7261}
7262
7263/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007264llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7265 const llvm::fltSemantics &Sem,
7266 unsigned &Idx) {
7267 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007268}
7269
7270// \brief Read a string
7271std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7272 unsigned Len = Record[Idx++];
7273 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7274 Idx += Len;
7275 return Result;
7276}
7277
7278VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7279 unsigned &Idx) {
7280 unsigned Major = Record[Idx++];
7281 unsigned Minor = Record[Idx++];
7282 unsigned Subminor = Record[Idx++];
7283 if (Minor == 0)
7284 return VersionTuple(Major);
7285 if (Subminor == 0)
7286 return VersionTuple(Major, Minor - 1);
7287 return VersionTuple(Major, Minor - 1, Subminor - 1);
7288}
7289
7290CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7291 const RecordData &Record,
7292 unsigned &Idx) {
7293 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7294 return CXXTemporary::Create(Context, Decl);
7295}
7296
7297DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007298 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007299}
7300
7301DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7302 return Diags.Report(Loc, DiagID);
7303}
7304
7305/// \brief Retrieve the identifier table associated with the
7306/// preprocessor.
7307IdentifierTable &ASTReader::getIdentifierTable() {
7308 return PP.getIdentifierTable();
7309}
7310
7311/// \brief Record that the given ID maps to the given switch-case
7312/// statement.
7313void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7314 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7315 "Already have a SwitchCase with this ID");
7316 (*CurrSwitchCaseStmts)[ID] = SC;
7317}
7318
7319/// \brief Retrieve the switch-case statement with the given ID.
7320SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7321 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7322 return (*CurrSwitchCaseStmts)[ID];
7323}
7324
7325void ASTReader::ClearSwitchCaseIDs() {
7326 CurrSwitchCaseStmts->clear();
7327}
7328
7329void ASTReader::ReadComments() {
7330 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007331 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 serialization::ModuleFile *> >::iterator
7333 I = CommentsCursors.begin(),
7334 E = CommentsCursors.end();
7335 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007336 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007337 serialization::ModuleFile &F = *I->second;
7338 SavedStreamPosition SavedPosition(Cursor);
7339
7340 RecordData Record;
7341 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007342 llvm::BitstreamEntry Entry =
7343 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7344
7345 switch (Entry.Kind) {
7346 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7347 case llvm::BitstreamEntry::Error:
7348 Error("malformed block record in AST file");
7349 return;
7350 case llvm::BitstreamEntry::EndBlock:
7351 goto NextCursor;
7352 case llvm::BitstreamEntry::Record:
7353 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 }
7356
7357 // Read a record.
7358 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007359 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 case COMMENTS_RAW_COMMENT: {
7361 unsigned Idx = 0;
7362 SourceRange SR = ReadSourceRange(F, Record, Idx);
7363 RawComment::CommentKind Kind =
7364 (RawComment::CommentKind) Record[Idx++];
7365 bool IsTrailingComment = Record[Idx++];
7366 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007367 Comments.push_back(new (Context) RawComment(
7368 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7369 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007370 break;
7371 }
7372 }
7373 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007374 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 }
7376 Context.Comments.addCommentsToFront(Comments);
7377}
7378
7379void ASTReader::finishPendingActions() {
7380 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007381 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7382 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 // If any identifiers with corresponding top-level declarations have
7384 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007385 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7386 TopLevelDeclsMap;
7387 TopLevelDeclsMap TopLevelDecls;
7388
Guy Benyei11169dd2012-12-18 14:30:41 +00007389 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007390 // FIXME: std::move
7391 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7392 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007393 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007394
7395 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007396 }
7397
7398 // Load pending declaration chains.
7399 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7400 loadPendingDeclChain(PendingDeclChains[I]);
7401 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7402 }
7403 PendingDeclChains.clear();
7404
Douglas Gregor6168bd22013-02-18 15:53:43 +00007405 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007406 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7407 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007408 IdentifierInfo *II = TLD->first;
7409 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007410 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007411 }
7412 }
7413
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 // Load any pending macro definitions.
7415 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007416 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7417 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7418 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7419 // Initialize the macro history from chained-PCHs ahead of module imports.
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007420 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7421 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007422 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7423 if (Info.M->Kind != MK_Module)
7424 resolvePendingMacro(II, Info);
7425 }
7426 // Handle module imports.
7427 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7428 ++IDIdx) {
7429 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7430 if (Info.M->Kind == MK_Module)
7431 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 }
7433 }
7434 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007435
7436 // Wire up the DeclContexts for Decls that we delayed setting until
7437 // recursive loading is completed.
7438 while (!PendingDeclContextInfos.empty()) {
7439 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7440 PendingDeclContextInfos.pop_front();
7441 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7442 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7443 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7444 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007445
7446 // For each declaration from a merged context, check that the canonical
7447 // definition of that context also contains a declaration of the same
7448 // entity.
7449 while (!PendingOdrMergeChecks.empty()) {
7450 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7451
7452 // FIXME: Skip over implicit declarations for now. This matters for things
7453 // like implicitly-declared special member functions. This isn't entirely
7454 // correct; we can end up with multiple unmerged declarations of the same
7455 // implicit entity.
7456 if (D->isImplicit())
7457 continue;
7458
7459 DeclContext *CanonDef = D->getDeclContext();
7460 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7461
7462 bool Found = false;
7463 const Decl *DCanon = D->getCanonicalDecl();
7464
7465 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7466 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7467 !Found && I != E; ++I) {
7468 for (Decl::redecl_iterator RI = (*I)->redecls_begin(),
7469 RE = (*I)->redecls_end();
7470 RI != RE; ++RI) {
7471 if ((*RI)->getLexicalDeclContext() == CanonDef) {
7472 // This declaration is present in the canonical definition. If it's
7473 // in the same redecl chain, it's the one we're looking for.
7474 if ((*RI)->getCanonicalDecl() == DCanon)
7475 Found = true;
7476 else
7477 Candidates.push_back(cast<NamedDecl>(*RI));
7478 break;
7479 }
7480 }
7481 }
7482
7483 if (!Found) {
7484 D->setInvalidDecl();
7485
7486 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7487 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7488 << D << D->getOwningModule()->getFullModuleName()
7489 << CanonDef << !CanonDefModule
7490 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7491
7492 if (Candidates.empty())
7493 Diag(cast<Decl>(CanonDef)->getLocation(),
7494 diag::note_module_odr_violation_no_possible_decls) << D;
7495 else {
7496 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7497 Diag(Candidates[I]->getLocation(),
7498 diag::note_module_odr_violation_possible_decl)
7499 << Candidates[I];
7500 }
7501 }
7502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 }
7504
7505 // If we deserialized any C++ or Objective-C class definitions, any
7506 // Objective-C protocol definitions, or any redeclarable templates, make sure
7507 // that all redeclarations point to the definitions. Note that this can only
7508 // happen now, after the redeclaration chains have been fully wired.
7509 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7510 DEnd = PendingDefinitions.end();
7511 D != DEnd; ++D) {
7512 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7513 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7514 // Make sure that the TagType points at the definition.
7515 const_cast<TagType*>(TagT)->decl = TD;
7516 }
7517
7518 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7519 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7520 REnd = RD->redecls_end();
7521 R != REnd; ++R)
7522 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7523
7524 }
7525
7526 continue;
7527 }
7528
7529 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7530 // Make sure that the ObjCInterfaceType points at the definition.
7531 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7532 ->Decl = ID;
7533
7534 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7535 REnd = ID->redecls_end();
7536 R != REnd; ++R)
7537 R->Data = ID->Data;
7538
7539 continue;
7540 }
7541
7542 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7543 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7544 REnd = PD->redecls_end();
7545 R != REnd; ++R)
7546 R->Data = PD->Data;
7547
7548 continue;
7549 }
7550
7551 RedeclarableTemplateDecl *RTD
7552 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7553 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7554 REnd = RTD->redecls_end();
7555 R != REnd; ++R)
7556 R->Common = RTD->Common;
7557 }
7558 PendingDefinitions.clear();
7559
7560 // Load the bodies of any functions or methods we've encountered. We do
7561 // this now (delayed) so that we can be sure that the declaration chains
7562 // have been fully wired up.
7563 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7564 PBEnd = PendingBodies.end();
7565 PB != PBEnd; ++PB) {
7566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7567 // FIXME: Check for =delete/=default?
7568 // FIXME: Complain about ODR violations here?
7569 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7570 FD->setLazyBody(PB->second);
7571 continue;
7572 }
7573
7574 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7575 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7576 MD->setLazyBody(PB->second);
7577 }
7578 PendingBodies.clear();
7579}
7580
7581void ASTReader::FinishedDeserializing() {
7582 assert(NumCurrentElementsDeserializing &&
7583 "FinishedDeserializing not paired with StartedDeserializing");
7584 if (NumCurrentElementsDeserializing == 1) {
7585 // We decrease NumCurrentElementsDeserializing only after pending actions
7586 // are finished, to avoid recursively re-calling finishPendingActions().
7587 finishPendingActions();
7588 }
7589 --NumCurrentElementsDeserializing;
7590
7591 if (NumCurrentElementsDeserializing == 0 &&
7592 Consumer && !PassingDeclsToConsumer) {
7593 // Guard variable to avoid recursively redoing the process of passing
7594 // decls to consumer.
7595 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7596 true);
7597
7598 while (!InterestingDecls.empty()) {
7599 // We are not in recursive loading, so it's safe to pass the "interesting"
7600 // decls to the consumer.
7601 Decl *D = InterestingDecls.front();
7602 InterestingDecls.pop_front();
7603 PassInterestingDeclToConsumer(D);
7604 }
7605 }
7606}
7607
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007608void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007609 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007610
7611 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7612 SemaObj->TUScope->AddDecl(D);
7613 } else if (SemaObj->TUScope) {
7614 // Adding the decl to IdResolver may have failed because it was already in
7615 // (even though it was not added in scope). If it is already in, make sure
7616 // it gets in the scope as well.
7617 if (std::find(SemaObj->IdResolver.begin(Name),
7618 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7619 SemaObj->TUScope->AddDecl(D);
7620 }
7621}
7622
Guy Benyei11169dd2012-12-18 14:30:41 +00007623ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7624 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007625 bool AllowASTWithCompilerErrors,
7626 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007627 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007628 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7630 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7631 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7632 Consumer(0), ModuleMgr(PP.getFileManager()),
7633 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007634 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007635 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007636 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007637 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007638 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7639 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007640 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7641 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7642 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007643 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7644 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7645 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7647 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7648 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7649 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007650 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007651{
7652 SourceMgr.setExternalSLocEntrySource(this);
7653}
7654
7655ASTReader::~ASTReader() {
7656 for (DeclContextVisibleUpdatesPending::iterator
7657 I = PendingVisibleUpdates.begin(),
7658 E = PendingVisibleUpdates.end();
7659 I != E; ++I) {
7660 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7661 F = I->second.end();
7662 J != F; ++J)
7663 delete J->first;
7664 }
7665}