blob: cc218a2807bf3195c7bf0d550d45fd0f36f5dadd [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"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000052#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "llvm/Support/system_error.h"
54#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000055#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <iterator>
57
58using namespace clang;
59using namespace clang::serialization;
60using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000061using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000062
63//===----------------------------------------------------------------------===//
64// PCH validator implementation
65//===----------------------------------------------------------------------===//
66
67ASTReaderListener::~ASTReaderListener() {}
68
69/// \brief Compare the given set of language options against an existing set of
70/// language options.
71///
72/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
73///
74/// \returns true if the languagae options mis-match, false otherwise.
75static bool checkLanguageOptions(const LangOptions &LangOpts,
76 const LangOptions &ExistingLangOpts,
77 DiagnosticsEngine *Diags) {
78#define LANGOPT(Name, Bits, Default, Description) \
79 if (ExistingLangOpts.Name != LangOpts.Name) { \
80 if (Diags) \
81 Diags->Report(diag::err_pch_langopt_mismatch) \
82 << Description << LangOpts.Name << ExistingLangOpts.Name; \
83 return true; \
84 }
85
86#define VALUE_LANGOPT(Name, Bits, Default, Description) \
87 if (ExistingLangOpts.Name != LangOpts.Name) { \
88 if (Diags) \
89 Diags->Report(diag::err_pch_langopt_value_mismatch) \
90 << Description; \
91 return true; \
92 }
93
94#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
95 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
96 if (Diags) \
97 Diags->Report(diag::err_pch_langopt_value_mismatch) \
98 << Description; \
99 return true; \
100 }
101
102#define BENIGN_LANGOPT(Name, Bits, Default, Description)
103#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
104#include "clang/Basic/LangOptions.def"
105
106 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
107 if (Diags)
108 Diags->Report(diag::err_pch_langopt_value_mismatch)
109 << "target Objective-C runtime";
110 return true;
111 }
112
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000113 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
114 LangOpts.CommentOpts.BlockCommandNames) {
115 if (Diags)
116 Diags->Report(diag::err_pch_langopt_value_mismatch)
117 << "block command names";
118 return true;
119 }
120
Guy Benyei11169dd2012-12-18 14:30:41 +0000121 return false;
122}
123
124/// \brief Compare the given set of target options against an existing set of
125/// target options.
126///
127/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
128///
129/// \returns true if the target options mis-match, false otherwise.
130static bool checkTargetOptions(const TargetOptions &TargetOpts,
131 const TargetOptions &ExistingTargetOpts,
132 DiagnosticsEngine *Diags) {
133#define CHECK_TARGET_OPT(Field, Name) \
134 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
135 if (Diags) \
136 Diags->Report(diag::err_pch_targetopt_mismatch) \
137 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
138 return true; \
139 }
140
141 CHECK_TARGET_OPT(Triple, "target");
142 CHECK_TARGET_OPT(CPU, "target CPU");
143 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000144 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
145#undef CHECK_TARGET_OPT
146
147 // Compare feature sets.
148 SmallVector<StringRef, 4> ExistingFeatures(
149 ExistingTargetOpts.FeaturesAsWritten.begin(),
150 ExistingTargetOpts.FeaturesAsWritten.end());
151 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
152 TargetOpts.FeaturesAsWritten.end());
153 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
154 std::sort(ReadFeatures.begin(), ReadFeatures.end());
155
156 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
157 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
158 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
159 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
160 ++ExistingIdx;
161 ++ReadIdx;
162 continue;
163 }
164
165 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
166 if (Diags)
167 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
168 << false << ReadFeatures[ReadIdx];
169 return true;
170 }
171
172 if (Diags)
173 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
174 << true << ExistingFeatures[ExistingIdx];
175 return true;
176 }
177
178 if (ExistingIdx < ExistingN) {
179 if (Diags)
180 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
181 << true << ExistingFeatures[ExistingIdx];
182 return true;
183 }
184
185 if (ReadIdx < ReadN) {
186 if (Diags)
187 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
188 << false << ReadFeatures[ReadIdx];
189 return true;
190 }
191
192 return false;
193}
194
195bool
196PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
197 bool Complain) {
198 const LangOptions &ExistingLangOpts = PP.getLangOpts();
199 return checkLanguageOptions(LangOpts, ExistingLangOpts,
200 Complain? &Reader.Diags : 0);
201}
202
203bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
204 bool Complain) {
205 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
206 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
207 Complain? &Reader.Diags : 0);
208}
209
210namespace {
211 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
212 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000213 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
214 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000215}
216
217/// \brief Collect the macro definitions provided by the given preprocessor
218/// options.
219static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
220 MacroDefinitionsMap &Macros,
221 SmallVectorImpl<StringRef> *MacroNames = 0){
222 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
223 StringRef Macro = PPOpts.Macros[I].first;
224 bool IsUndef = PPOpts.Macros[I].second;
225
226 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
227 StringRef MacroName = MacroPair.first;
228 StringRef MacroBody = MacroPair.second;
229
230 // For an #undef'd macro, we only care about the name.
231 if (IsUndef) {
232 if (MacroNames && !Macros.count(MacroName))
233 MacroNames->push_back(MacroName);
234
235 Macros[MacroName] = std::make_pair("", true);
236 continue;
237 }
238
239 // For a #define'd macro, figure out the actual definition.
240 if (MacroName.size() == Macro.size())
241 MacroBody = "1";
242 else {
243 // Note: GCC drops anything following an end-of-line character.
244 StringRef::size_type End = MacroBody.find_first_of("\n\r");
245 MacroBody = MacroBody.substr(0, End);
246 }
247
248 if (MacroNames && !Macros.count(MacroName))
249 MacroNames->push_back(MacroName);
250 Macros[MacroName] = std::make_pair(MacroBody, false);
251 }
252}
253
254/// \brief Check the preprocessor options deserialized from the control block
255/// against the preprocessor options in an existing preprocessor.
256///
257/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
258static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
259 const PreprocessorOptions &ExistingPPOpts,
260 DiagnosticsEngine *Diags,
261 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000262 std::string &SuggestedPredefines,
263 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000264 // Check macro definitions.
265 MacroDefinitionsMap ASTFileMacros;
266 collectMacroDefinitions(PPOpts, ASTFileMacros);
267 MacroDefinitionsMap ExistingMacros;
268 SmallVector<StringRef, 4> ExistingMacroNames;
269 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
270
271 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
272 // Dig out the macro definition in the existing preprocessor options.
273 StringRef MacroName = ExistingMacroNames[I];
274 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
275
276 // Check whether we know anything about this macro name or not.
277 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
278 = ASTFileMacros.find(MacroName);
279 if (Known == ASTFileMacros.end()) {
280 // FIXME: Check whether this identifier was referenced anywhere in the
281 // AST file. If so, we should reject the AST file. Unfortunately, this
282 // information isn't in the control block. What shall we do about it?
283
284 if (Existing.second) {
285 SuggestedPredefines += "#undef ";
286 SuggestedPredefines += MacroName.str();
287 SuggestedPredefines += '\n';
288 } else {
289 SuggestedPredefines += "#define ";
290 SuggestedPredefines += MacroName.str();
291 SuggestedPredefines += ' ';
292 SuggestedPredefines += Existing.first.str();
293 SuggestedPredefines += '\n';
294 }
295 continue;
296 }
297
298 // If the macro was defined in one but undef'd in the other, we have a
299 // conflict.
300 if (Existing.second != Known->second.second) {
301 if (Diags) {
302 Diags->Report(diag::err_pch_macro_def_undef)
303 << MacroName << Known->second.second;
304 }
305 return true;
306 }
307
308 // If the macro was #undef'd in both, or if the macro bodies are identical,
309 // it's fine.
310 if (Existing.second || Existing.first == Known->second.first)
311 continue;
312
313 // The macro bodies differ; complain.
314 if (Diags) {
315 Diags->Report(diag::err_pch_macro_def_conflict)
316 << MacroName << Known->second.first << Existing.first;
317 }
318 return true;
319 }
320
321 // Check whether we're using predefines.
322 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
323 if (Diags) {
324 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
325 }
326 return true;
327 }
328
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000329 // Detailed record is important since it is used for the module cache hash.
330 if (LangOpts.Modules &&
331 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
332 if (Diags) {
333 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
334 }
335 return true;
336 }
337
Guy Benyei11169dd2012-12-18 14:30:41 +0000338 // Compute the #include and #include_macros lines we need.
339 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
340 StringRef File = ExistingPPOpts.Includes[I];
341 if (File == ExistingPPOpts.ImplicitPCHInclude)
342 continue;
343
344 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
345 != PPOpts.Includes.end())
346 continue;
347
348 SuggestedPredefines += "#include \"";
349 SuggestedPredefines +=
350 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
351 SuggestedPredefines += "\"\n";
352 }
353
354 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
355 StringRef File = ExistingPPOpts.MacroIncludes[I];
356 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
357 File)
358 != PPOpts.MacroIncludes.end())
359 continue;
360
361 SuggestedPredefines += "#__include_macros \"";
362 SuggestedPredefines +=
363 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
364 SuggestedPredefines += "\"\n##\n";
365 }
366
367 return false;
368}
369
370bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
371 bool Complain,
372 std::string &SuggestedPredefines) {
373 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
374
375 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
376 Complain? &Reader.Diags : 0,
377 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000378 SuggestedPredefines,
379 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000380}
381
Guy Benyei11169dd2012-12-18 14:30:41 +0000382void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
383 PP.setCounterValue(Value);
384}
385
386//===----------------------------------------------------------------------===//
387// AST reader implementation
388//===----------------------------------------------------------------------===//
389
390void
391ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
392 DeserializationListener = Listener;
393}
394
395
396
397unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
398 return serialization::ComputeHash(Sel);
399}
400
401
402std::pair<unsigned, unsigned>
403ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
404 using namespace clang::io;
405 unsigned KeyLen = ReadUnalignedLE16(d);
406 unsigned DataLen = ReadUnalignedLE16(d);
407 return std::make_pair(KeyLen, DataLen);
408}
409
410ASTSelectorLookupTrait::internal_key_type
411ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
412 using namespace clang::io;
413 SelectorTable &SelTable = Reader.getContext().Selectors;
414 unsigned N = ReadUnalignedLE16(d);
415 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000416 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 if (N == 0)
418 return SelTable.getNullarySelector(FirstII);
419 else if (N == 1)
420 return SelTable.getUnarySelector(FirstII);
421
422 SmallVector<IdentifierInfo *, 16> Args;
423 Args.push_back(FirstII);
424 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000425 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000426
427 return SelTable.getSelector(N, Args.data());
428}
429
430ASTSelectorLookupTrait::data_type
431ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
432 unsigned DataLen) {
433 using namespace clang::io;
434
435 data_type Result;
436
437 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000438 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
439 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
440 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
441 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
442 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
443 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000444
445 // Load instance methods
446 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
447 if (ObjCMethodDecl *Method
448 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
449 Result.Instance.push_back(Method);
450 }
451
452 // Load factory methods
453 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
454 if (ObjCMethodDecl *Method
455 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
456 Result.Factory.push_back(Method);
457 }
458
459 return Result;
460}
461
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000462unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
463 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000464}
465
466std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000467ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 using namespace clang::io;
469 unsigned DataLen = ReadUnalignedLE16(d);
470 unsigned KeyLen = ReadUnalignedLE16(d);
471 return std::make_pair(KeyLen, DataLen);
472}
473
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000474ASTIdentifierLookupTraitBase::internal_key_type
475ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000476 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000477 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000478}
479
Douglas Gregordcf25082013-02-11 18:16:18 +0000480/// \brief Whether the given identifier is "interesting".
481static bool isInterestingIdentifier(IdentifierInfo &II) {
482 return II.isPoisoned() ||
483 II.isExtensionToken() ||
484 II.getObjCOrBuiltinID() ||
485 II.hasRevertedTokenIDToIdentifier() ||
486 II.hadMacroDefinition() ||
487 II.getFETokenInfo<void>();
488}
489
Guy Benyei11169dd2012-12-18 14:30:41 +0000490IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
491 const unsigned char* d,
492 unsigned DataLen) {
493 using namespace clang::io;
494 unsigned RawID = ReadUnalignedLE32(d);
495 bool IsInteresting = RawID & 0x01;
496
497 // Wipe out the "is interesting" bit.
498 RawID = RawID >> 1;
499
500 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
501 if (!IsInteresting) {
502 // For uninteresting identifiers, just build the IdentifierInfo
503 // and associate it with the persistent ID.
504 IdentifierInfo *II = KnownII;
505 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000506 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 KnownII = II;
508 }
509 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000510 if (!II->isFromAST()) {
511 bool WasInteresting = isInterestingIdentifier(*II);
512 II->setIsFromAST();
513 if (WasInteresting)
514 II->setChangedSinceDeserialization();
515 }
516 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 return II;
518 }
519
520 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
521 unsigned Bits = ReadUnalignedLE16(d);
522 bool CPlusPlusOperatorKeyword = Bits & 0x01;
523 Bits >>= 1;
524 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
525 Bits >>= 1;
526 bool Poisoned = Bits & 0x01;
527 Bits >>= 1;
528 bool ExtensionToken = Bits & 0x01;
529 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000530 bool hasSubmoduleMacros = Bits & 0x01;
531 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 bool hadMacroDefinition = Bits & 0x01;
533 Bits >>= 1;
534
535 assert(Bits == 0 && "Extra bits in the identifier?");
536 DataLen -= 8;
537
538 // Build the IdentifierInfo itself and link the identifier ID with
539 // the new IdentifierInfo.
540 IdentifierInfo *II = KnownII;
541 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000542 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000543 KnownII = II;
544 }
545 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000546 if (!II->isFromAST()) {
547 bool WasInteresting = isInterestingIdentifier(*II);
548 II->setIsFromAST();
549 if (WasInteresting)
550 II->setChangedSinceDeserialization();
551 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000552
553 // Set or check the various bits in the IdentifierInfo structure.
554 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000555 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 II->RevertTokenIDToIdentifier();
557 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
558 assert(II->isExtensionToken() == ExtensionToken &&
559 "Incorrect extension token flag");
560 (void)ExtensionToken;
561 if (Poisoned)
562 II->setIsPoisoned(true);
563 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
564 "Incorrect C++ operator keyword flag");
565 (void)CPlusPlusOperatorKeyword;
566
567 // If this identifier is a macro, deserialize the macro
568 // definition.
569 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000570 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
571 DataLen -= 4;
572 SmallVector<uint32_t, 8> LocalMacroIDs;
573 if (hasSubmoduleMacros) {
574 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
575 DataLen -= 4;
576 LocalMacroIDs.push_back(LocalMacroID);
577 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000578 DataLen -= 4;
579 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000580
581 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000582 // Macro definitions are stored from newest to oldest, so reverse them
583 // before registering them.
584 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000585 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000586 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
587 unsigned Size = 1;
588
589 static const uint32_t HasOverridesFlag = 0x80000000U;
590 if (I + 1 != E && (I[1] & HasOverridesFlag))
591 Size += 1 + (I[1] & ~HasOverridesFlag);
592
593 MacroSizes.push_back(Size);
594 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000595 }
Richard Smith49f906a2014-03-01 00:08:04 +0000596
597 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
598 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
599 SE = MacroSizes.rend();
600 SI != SE; ++SI) {
601 I -= *SI;
602
603 uint32_t LocalMacroID = *I;
604 llvm::ArrayRef<uint32_t> Overrides;
605 if (*SI != 1)
606 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
607 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
608 }
609 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000610 } else {
611 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
612 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 }
614
615 Reader.SetIdentifierInfo(ID, II);
616
617 // Read all of the declarations visible at global scope with this
618 // name.
619 if (DataLen > 0) {
620 SmallVector<uint32_t, 4> DeclIDs;
621 for (; DataLen > 0; DataLen -= 4)
622 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
623 Reader.SetGloballyVisibleDecls(II, DeclIDs);
624 }
625
626 return II;
627}
628
629unsigned
630ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
631 llvm::FoldingSetNodeID ID;
632 ID.AddInteger(Key.Kind);
633
634 switch (Key.Kind) {
635 case DeclarationName::Identifier:
636 case DeclarationName::CXXLiteralOperatorName:
637 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
638 break;
639 case DeclarationName::ObjCZeroArgSelector:
640 case DeclarationName::ObjCOneArgSelector:
641 case DeclarationName::ObjCMultiArgSelector:
642 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
643 break;
644 case DeclarationName::CXXOperatorName:
645 ID.AddInteger((OverloadedOperatorKind)Key.Data);
646 break;
647 case DeclarationName::CXXConstructorName:
648 case DeclarationName::CXXDestructorName:
649 case DeclarationName::CXXConversionFunctionName:
650 case DeclarationName::CXXUsingDirective:
651 break;
652 }
653
654 return ID.ComputeHash();
655}
656
657ASTDeclContextNameLookupTrait::internal_key_type
658ASTDeclContextNameLookupTrait::GetInternalKey(
659 const external_key_type& Name) const {
660 DeclNameKey Key;
661 Key.Kind = Name.getNameKind();
662 switch (Name.getNameKind()) {
663 case DeclarationName::Identifier:
664 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
665 break;
666 case DeclarationName::ObjCZeroArgSelector:
667 case DeclarationName::ObjCOneArgSelector:
668 case DeclarationName::ObjCMultiArgSelector:
669 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
670 break;
671 case DeclarationName::CXXOperatorName:
672 Key.Data = Name.getCXXOverloadedOperator();
673 break;
674 case DeclarationName::CXXLiteralOperatorName:
675 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
676 break;
677 case DeclarationName::CXXConstructorName:
678 case DeclarationName::CXXDestructorName:
679 case DeclarationName::CXXConversionFunctionName:
680 case DeclarationName::CXXUsingDirective:
681 Key.Data = 0;
682 break;
683 }
684
685 return Key;
686}
687
688std::pair<unsigned, unsigned>
689ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
690 using namespace clang::io;
691 unsigned KeyLen = ReadUnalignedLE16(d);
692 unsigned DataLen = ReadUnalignedLE16(d);
693 return std::make_pair(KeyLen, DataLen);
694}
695
696ASTDeclContextNameLookupTrait::internal_key_type
697ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
698 using namespace clang::io;
699
700 DeclNameKey Key;
701 Key.Kind = (DeclarationName::NameKind)*d++;
702 switch (Key.Kind) {
703 case DeclarationName::Identifier:
704 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
705 break;
706 case DeclarationName::ObjCZeroArgSelector:
707 case DeclarationName::ObjCOneArgSelector:
708 case DeclarationName::ObjCMultiArgSelector:
709 Key.Data =
710 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
711 .getAsOpaquePtr();
712 break;
713 case DeclarationName::CXXOperatorName:
714 Key.Data = *d++; // OverloadedOperatorKind
715 break;
716 case DeclarationName::CXXLiteralOperatorName:
717 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
718 break;
719 case DeclarationName::CXXConstructorName:
720 case DeclarationName::CXXDestructorName:
721 case DeclarationName::CXXConversionFunctionName:
722 case DeclarationName::CXXUsingDirective:
723 Key.Data = 0;
724 break;
725 }
726
727 return Key;
728}
729
730ASTDeclContextNameLookupTrait::data_type
731ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
732 const unsigned char* d,
733 unsigned DataLen) {
734 using namespace clang::io;
735 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000736 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
737 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 return std::make_pair(Start, Start + NumDecls);
739}
740
741bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000742 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 const std::pair<uint64_t, uint64_t> &Offsets,
744 DeclContextInfo &Info) {
745 SavedStreamPosition SavedPosition(Cursor);
746 // First the lexical decls.
747 if (Offsets.first != 0) {
748 Cursor.JumpToBit(Offsets.first);
749
750 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000751 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000753 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 if (RecCode != DECL_CONTEXT_LEXICAL) {
755 Error("Expected lexical block");
756 return true;
757 }
758
Chris Lattner0e6c9402013-01-20 02:38:54 +0000759 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
760 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000761 }
762
763 // Now the lookup table.
764 if (Offsets.second != 0) {
765 Cursor.JumpToBit(Offsets.second);
766
767 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000768 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000769 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000770 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 if (RecCode != DECL_CONTEXT_VISIBLE) {
772 Error("Expected visible lookup table block");
773 return true;
774 }
775 Info.NameLookupTableData
776 = ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +0000777 (const unsigned char *)Blob.data() + Record[0],
778 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000779 ASTDeclContextNameLookupTrait(*this, M));
780 }
781
782 return false;
783}
784
785void ASTReader::Error(StringRef Msg) {
786 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000787 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
788 Diag(diag::note_module_cache_path)
789 << PP.getHeaderSearchInfo().getModuleCachePath();
790 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000791}
792
793void ASTReader::Error(unsigned DiagID,
794 StringRef Arg1, StringRef Arg2) {
795 if (Diags.isDiagnosticInFlight())
796 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
797 else
798 Diag(DiagID) << Arg1 << Arg2;
799}
800
801//===----------------------------------------------------------------------===//
802// Source Manager Deserialization
803//===----------------------------------------------------------------------===//
804
805/// \brief Read the line table in the source manager block.
806/// \returns true if there was an error.
807bool ASTReader::ParseLineTable(ModuleFile &F,
808 SmallVectorImpl<uint64_t> &Record) {
809 unsigned Idx = 0;
810 LineTableInfo &LineTable = SourceMgr.getLineTable();
811
812 // Parse the file names
813 std::map<int, int> FileIDs;
814 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
815 // Extract the file name
816 unsigned FilenameLen = Record[Idx++];
817 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
818 Idx += FilenameLen;
819 MaybeAddSystemRootToFilename(F, Filename);
820 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
821 }
822
823 // Parse the line entries
824 std::vector<LineEntry> Entries;
825 while (Idx < Record.size()) {
826 int FID = Record[Idx++];
827 assert(FID >= 0 && "Serialized line entries for non-local file.");
828 // Remap FileID from 1-based old view.
829 FID += F.SLocEntryBaseID - 1;
830
831 // Extract the line entries
832 unsigned NumEntries = Record[Idx++];
833 assert(NumEntries && "Numentries is 00000");
834 Entries.clear();
835 Entries.reserve(NumEntries);
836 for (unsigned I = 0; I != NumEntries; ++I) {
837 unsigned FileOffset = Record[Idx++];
838 unsigned LineNo = Record[Idx++];
839 int FilenameID = FileIDs[Record[Idx++]];
840 SrcMgr::CharacteristicKind FileKind
841 = (SrcMgr::CharacteristicKind)Record[Idx++];
842 unsigned IncludeOffset = Record[Idx++];
843 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
844 FileKind, IncludeOffset));
845 }
846 LineTable.AddEntry(FileID::get(FID), Entries);
847 }
848
849 return false;
850}
851
852/// \brief Read a source manager block
853bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
854 using namespace SrcMgr;
855
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000856 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000857
858 // Set the source-location entry cursor to the current position in
859 // the stream. This cursor will be used to read the contents of the
860 // source manager block initially, and then lazily read
861 // source-location entries as needed.
862 SLocEntryCursor = F.Stream;
863
864 // The stream itself is going to skip over the source manager block.
865 if (F.Stream.SkipBlock()) {
866 Error("malformed block record in AST file");
867 return true;
868 }
869
870 // Enter the source manager block.
871 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
872 Error("malformed source manager block record in AST file");
873 return true;
874 }
875
876 RecordData Record;
877 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000878 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
879
880 switch (E.Kind) {
881 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
882 case llvm::BitstreamEntry::Error:
883 Error("malformed block record in AST file");
884 return true;
885 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000886 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000887 case llvm::BitstreamEntry::Record:
888 // The interesting case.
889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000891
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000894 StringRef Blob;
895 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 default: // Default behavior: ignore.
897 break;
898
899 case SM_SLOC_FILE_ENTRY:
900 case SM_SLOC_BUFFER_ENTRY:
901 case SM_SLOC_EXPANSION_ENTRY:
902 // Once we hit one of the source location entries, we're done.
903 return false;
904 }
905 }
906}
907
908/// \brief If a header file is not found at the path that we expect it to be
909/// and the PCH file was moved from its original location, try to resolve the
910/// file by assuming that header+PCH were moved together and the header is in
911/// the same place relative to the PCH.
912static std::string
913resolveFileRelativeToOriginalDir(const std::string &Filename,
914 const std::string &OriginalDir,
915 const std::string &CurrDir) {
916 assert(OriginalDir != CurrDir &&
917 "No point trying to resolve the file if the PCH dir didn't change");
918 using namespace llvm::sys;
919 SmallString<128> filePath(Filename);
920 fs::make_absolute(filePath);
921 assert(path::is_absolute(OriginalDir));
922 SmallString<128> currPCHPath(CurrDir);
923
924 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
925 fileDirE = path::end(path::parent_path(filePath));
926 path::const_iterator origDirI = path::begin(OriginalDir),
927 origDirE = path::end(OriginalDir);
928 // Skip the common path components from filePath and OriginalDir.
929 while (fileDirI != fileDirE && origDirI != origDirE &&
930 *fileDirI == *origDirI) {
931 ++fileDirI;
932 ++origDirI;
933 }
934 for (; origDirI != origDirE; ++origDirI)
935 path::append(currPCHPath, "..");
936 path::append(currPCHPath, fileDirI, fileDirE);
937 path::append(currPCHPath, path::filename(Filename));
938 return currPCHPath.str();
939}
940
941bool ASTReader::ReadSLocEntry(int ID) {
942 if (ID == 0)
943 return false;
944
945 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
946 Error("source location entry ID out-of-range for AST file");
947 return true;
948 }
949
950 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
951 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000952 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 unsigned BaseOffset = F->SLocEntryBaseOffset;
954
955 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000956 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
957 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 Error("incorrectly-formatted source location entry in AST file");
959 return true;
960 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000961
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000963 StringRef Blob;
964 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 default:
966 Error("incorrectly-formatted source location entry in AST file");
967 return true;
968
969 case SM_SLOC_FILE_ENTRY: {
970 // We will detect whether a file changed and return 'Failure' for it, but
971 // we will also try to fail gracefully by setting up the SLocEntry.
972 unsigned InputID = Record[4];
973 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000974 const FileEntry *File = IF.getFile();
975 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +0000977 // Note that we only check if a File was returned. If it was out-of-date
978 // we have complained but we will continue creating a FileID to recover
979 // gracefully.
980 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 return true;
982
983 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
984 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
985 // This is the module's main file.
986 IncludeLoc = getImportLocation(F);
987 }
988 SrcMgr::CharacteristicKind
989 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
990 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
991 ID, BaseOffset + Record[0]);
992 SrcMgr::FileInfo &FileInfo =
993 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
994 FileInfo.NumCreatedFIDs = Record[5];
995 if (Record[3])
996 FileInfo.setHasLineDirectives();
997
998 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
999 unsigned NumFileDecls = Record[7];
1000 if (NumFileDecls) {
1001 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1002 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1003 NumFileDecls));
1004 }
1005
1006 const SrcMgr::ContentCache *ContentCache
1007 = SourceMgr.getOrCreateContentCache(File,
1008 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1009 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1010 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1011 unsigned Code = SLocEntryCursor.ReadCode();
1012 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001013 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001014
1015 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1016 Error("AST record has invalid code");
1017 return true;
1018 }
1019
1020 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001021 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 SourceMgr.overrideFileContents(File, Buffer);
1023 }
1024
1025 break;
1026 }
1027
1028 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001029 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 unsigned Offset = Record[0];
1031 SrcMgr::CharacteristicKind
1032 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1033 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1034 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1035 IncludeLoc = getImportLocation(F);
1036 }
1037 unsigned Code = SLocEntryCursor.ReadCode();
1038 Record.clear();
1039 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001040 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041
1042 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1043 Error("AST record has invalid code");
1044 return true;
1045 }
1046
1047 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001048 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1050 BaseOffset + Offset, IncludeLoc);
1051 break;
1052 }
1053
1054 case SM_SLOC_EXPANSION_ENTRY: {
1055 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1056 SourceMgr.createExpansionLoc(SpellingLoc,
1057 ReadSourceLocation(*F, Record[2]),
1058 ReadSourceLocation(*F, Record[3]),
1059 Record[4],
1060 ID,
1061 BaseOffset + Record[0]);
1062 break;
1063 }
1064 }
1065
1066 return false;
1067}
1068
1069std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1070 if (ID == 0)
1071 return std::make_pair(SourceLocation(), "");
1072
1073 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1074 Error("source location entry ID out-of-range for AST file");
1075 return std::make_pair(SourceLocation(), "");
1076 }
1077
1078 // Find which module file this entry lands in.
1079 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1080 if (M->Kind != MK_Module)
1081 return std::make_pair(SourceLocation(), "");
1082
1083 // FIXME: Can we map this down to a particular submodule? That would be
1084 // ideal.
1085 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1086}
1087
1088/// \brief Find the location where the module F is imported.
1089SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1090 if (F->ImportLoc.isValid())
1091 return F->ImportLoc;
1092
1093 // Otherwise we have a PCH. It's considered to be "imported" at the first
1094 // location of its includer.
1095 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1096 // Main file is the importer. We assume that it is the first entry in the
1097 // entry table. We can't ask the manager, because at the time of PCH loading
1098 // the main file entry doesn't exist yet.
1099 // The very first entry is the invalid instantiation loc, which takes up
1100 // offsets 0 and 1.
1101 return SourceLocation::getFromRawEncoding(2U);
1102 }
1103 //return F->Loaders[0]->FirstLoc;
1104 return F->ImportedBy[0]->FirstLoc;
1105}
1106
1107/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1108/// specified cursor. Read the abbreviations that are at the top of the block
1109/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001110bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 if (Cursor.EnterSubBlock(BlockID)) {
1112 Error("malformed block record in AST file");
1113 return Failure;
1114 }
1115
1116 while (true) {
1117 uint64_t Offset = Cursor.GetCurrentBitNo();
1118 unsigned Code = Cursor.ReadCode();
1119
1120 // We expect all abbrevs to be at the start of the block.
1121 if (Code != llvm::bitc::DEFINE_ABBREV) {
1122 Cursor.JumpToBit(Offset);
1123 return false;
1124 }
1125 Cursor.ReadAbbrevRecord();
1126 }
1127}
1128
Richard Smithe40f2ba2013-08-07 21:41:30 +00001129Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001130 unsigned &Idx) {
1131 Token Tok;
1132 Tok.startToken();
1133 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1134 Tok.setLength(Record[Idx++]);
1135 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1136 Tok.setIdentifierInfo(II);
1137 Tok.setKind((tok::TokenKind)Record[Idx++]);
1138 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1139 return Tok;
1140}
1141
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001142MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001143 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144
1145 // Keep track of where we are in the stream, then jump back there
1146 // after reading this macro.
1147 SavedStreamPosition SavedPosition(Stream);
1148
1149 Stream.JumpToBit(Offset);
1150 RecordData Record;
1151 SmallVector<IdentifierInfo*, 16> MacroArgs;
1152 MacroInfo *Macro = 0;
1153
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001155 // Advance to the next record, but if we get to the end of the block, don't
1156 // pop it (removing all the abbreviations from the cursor) since we want to
1157 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001158 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001159 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1160
1161 switch (Entry.Kind) {
1162 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1163 case llvm::BitstreamEntry::Error:
1164 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001165 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001166 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001167 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001168 case llvm::BitstreamEntry::Record:
1169 // The interesting case.
1170 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 }
1172
1173 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 Record.clear();
1175 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001176 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001178 case PP_MACRO_DIRECTIVE_HISTORY:
1179 return Macro;
1180
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 case PP_MACRO_OBJECT_LIKE:
1182 case PP_MACRO_FUNCTION_LIKE: {
1183 // If we already have a macro, that means that we've hit the end
1184 // of the definition of the macro we were looking for. We're
1185 // done.
1186 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001187 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001188
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001189 unsigned NextIndex = 1; // Skip identifier ID.
1190 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001192 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001193 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001195
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1197 // Decode function-like macro info.
1198 bool isC99VarArgs = Record[NextIndex++];
1199 bool isGNUVarArgs = Record[NextIndex++];
1200 bool hasCommaPasting = Record[NextIndex++];
1201 MacroArgs.clear();
1202 unsigned NumArgs = Record[NextIndex++];
1203 for (unsigned i = 0; i != NumArgs; ++i)
1204 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1205
1206 // Install function-like macro info.
1207 MI->setIsFunctionLike();
1208 if (isC99VarArgs) MI->setIsC99Varargs();
1209 if (isGNUVarArgs) MI->setIsGNUVarargs();
1210 if (hasCommaPasting) MI->setHasCommaPasting();
1211 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1212 PP.getPreprocessorAllocator());
1213 }
1214
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 // Remember that we saw this macro last so that we add the tokens that
1216 // form its body to it.
1217 Macro = MI;
1218
1219 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1220 Record[NextIndex]) {
1221 // We have a macro definition. Register the association
1222 PreprocessedEntityID
1223 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1224 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001225 PreprocessingRecord::PPEntityID
1226 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1227 MacroDefinition *PPDef =
1228 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1229 if (PPDef)
1230 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 }
1232
1233 ++NumMacrosRead;
1234 break;
1235 }
1236
1237 case PP_TOKEN: {
1238 // If we see a TOKEN before a PP_MACRO_*, then the file is
1239 // erroneous, just pretend we didn't see this.
1240 if (Macro == 0) break;
1241
John McCallf413f5e2013-05-03 00:10:13 +00001242 unsigned Idx = 0;
1243 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 Macro->AddTokenToBody(Tok);
1245 break;
1246 }
1247 }
1248 }
1249}
1250
1251PreprocessedEntityID
1252ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1253 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1254 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1255 assert(I != M.PreprocessedEntityRemap.end()
1256 && "Invalid index into preprocessed entity index remap");
1257
1258 return LocalID + I->second;
1259}
1260
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001261unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1262 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263}
1264
1265HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001266HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1267 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1268 FE->getName() };
1269 return ikey;
1270}
Guy Benyei11169dd2012-12-18 14:30:41 +00001271
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001272bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1273 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001274 return false;
1275
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001276 if (strcmp(a.Filename, b.Filename) == 0)
1277 return true;
1278
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001280 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001281 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1282 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001283 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001284}
1285
1286std::pair<unsigned, unsigned>
1287HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1288 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1289 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001290 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001291}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001292
1293HeaderFileInfoTrait::internal_key_type
1294HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1295 internal_key_type ikey;
1296 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1297 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1298 ikey.Filename = (const char *)d;
1299 return ikey;
1300}
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001303HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 unsigned DataLen) {
1305 const unsigned char *End = d + DataLen;
1306 using namespace clang::io;
1307 HeaderFileInfo HFI;
1308 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001309 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1310 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 HFI.isImport = (Flags >> 5) & 0x01;
1312 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1313 HFI.DirInfo = (Flags >> 2) & 0x03;
1314 HFI.Resolved = (Flags >> 1) & 0x01;
1315 HFI.IndexHeaderMapHeader = Flags & 0x01;
1316 HFI.NumIncludes = ReadUnalignedLE16(d);
1317 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1318 ReadUnalignedLE32(d));
1319 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1320 // The framework offset is 1 greater than the actual offset,
1321 // since 0 is used as an indicator for "no framework name".
1322 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1323 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1324 }
1325
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001326 if (d != End) {
1327 uint32_t LocalSMID = ReadUnalignedLE32(d);
1328 if (LocalSMID) {
1329 // This header is part of a module. Associate it with the module to enable
1330 // implicit module import.
1331 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1332 Module *Mod = Reader.getSubmodule(GlobalSMID);
1333 HFI.isModuleHeader = true;
1334 FileManager &FileMgr = Reader.getFileManager();
1335 ModuleMap &ModMap =
1336 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001337 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001338 }
1339 }
1340
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1342 (void)End;
1343
1344 // This HeaderFileInfo was externally loaded.
1345 HFI.External = true;
1346 return HFI;
1347}
1348
Richard Smith49f906a2014-03-01 00:08:04 +00001349void
1350ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1351 GlobalMacroID GMacID,
1352 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001354 SubmoduleID *OverrideData = 0;
1355 if (!Overrides.empty()) {
1356 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1357 OverrideData[0] = Overrides.size();
1358 for (unsigned I = 0; I != Overrides.size(); ++I)
1359 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1360 }
1361 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001362}
1363
1364void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1365 ModuleFile *M,
1366 uint64_t MacroDirectivesOffset) {
1367 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1368 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001369}
1370
1371void ASTReader::ReadDefinedMacros() {
1372 // Note that we are loading defined macros.
1373 Deserializing Macros(this);
1374
1375 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1376 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001377 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001378
1379 // If there was no preprocessor block, skip this file.
1380 if (!MacroCursor.getBitStreamReader())
1381 continue;
1382
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001383 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 Cursor.JumpToBit((*I)->MacroStartOffset);
1385
1386 RecordData Record;
1387 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001388 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1389
1390 switch (E.Kind) {
1391 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392 case llvm::BitstreamEntry::Error:
1393 Error("malformed block record in AST file");
1394 return;
1395 case llvm::BitstreamEntry::EndBlock:
1396 goto NextCursor;
1397
1398 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001399 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001400 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001401 default: // Default behavior: ignore.
1402 break;
1403
1404 case PP_MACRO_OBJECT_LIKE:
1405 case PP_MACRO_FUNCTION_LIKE:
1406 getLocalIdentifier(**I, Record[0]);
1407 break;
1408
1409 case PP_TOKEN:
1410 // Ignore tokens.
1411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 break;
1414 }
1415 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001416 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 }
1418}
1419
1420namespace {
1421 /// \brief Visitor class used to look up identifirs in an AST file.
1422 class IdentifierLookupVisitor {
1423 StringRef Name;
1424 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001425 unsigned &NumIdentifierLookups;
1426 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001428
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001430 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1431 unsigned &NumIdentifierLookups,
1432 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001433 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001434 NumIdentifierLookups(NumIdentifierLookups),
1435 NumIdentifierLookupHits(NumIdentifierLookupHits),
1436 Found()
1437 {
1438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001439
1440 static bool visit(ModuleFile &M, void *UserData) {
1441 IdentifierLookupVisitor *This
1442 = static_cast<IdentifierLookupVisitor *>(UserData);
1443
1444 // If we've already searched this module file, skip it now.
1445 if (M.Generation <= This->PriorGeneration)
1446 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 ASTIdentifierLookupTable *IdTable
1449 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1450 if (!IdTable)
1451 return false;
1452
1453 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1454 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001455 ++This->NumIdentifierLookups;
1456 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 if (Pos == IdTable->end())
1458 return false;
1459
1460 // Dereferencing the iterator has the effect of building the
1461 // IdentifierInfo node and populating it with the various
1462 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001463 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001464 This->Found = *Pos;
1465 return true;
1466 }
1467
1468 // \brief Retrieve the identifier info found within the module
1469 // files.
1470 IdentifierInfo *getIdentifierInfo() const { return Found; }
1471 };
1472}
1473
1474void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1475 // Note that we are loading an identifier.
1476 Deserializing AnIdentifier(this);
1477
1478 unsigned PriorGeneration = 0;
1479 if (getContext().getLangOpts().Modules)
1480 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001481
1482 // If there is a global index, look there first to determine which modules
1483 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001484 GlobalModuleIndex::HitSet Hits;
1485 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001486 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001487 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1488 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001489 }
1490 }
1491
Douglas Gregor7211ac12013-01-25 23:32:03 +00001492 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001493 NumIdentifierLookups,
1494 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001495 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 markIdentifierUpToDate(&II);
1497}
1498
1499void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1500 if (!II)
1501 return;
1502
1503 II->setOutOfDate(false);
1504
1505 // Update the generation for this identifier.
1506 if (getContext().getLangOpts().Modules)
1507 IdentifierGeneration[II] = CurrentGeneration;
1508}
1509
Richard Smith49f906a2014-03-01 00:08:04 +00001510struct ASTReader::ModuleMacroInfo {
1511 SubmoduleID SubModID;
1512 MacroInfo *MI;
1513 SubmoduleID *Overrides;
1514 // FIXME: Remove this.
1515 ModuleFile *F;
1516
1517 bool isDefine() const { return MI; }
1518
1519 SubmoduleID getSubmoduleID() const { return SubModID; }
1520
1521 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1522 if (!Overrides)
1523 return llvm::ArrayRef<SubmoduleID>();
1524 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1525 }
1526
1527 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1528 if (!MI)
1529 return 0;
1530 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1531 }
1532};
1533
1534ASTReader::ModuleMacroInfo *
1535ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1536 ModuleMacroInfo Info;
1537
1538 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1539 if (ID & 1) {
1540 // Macro undefinition.
1541 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1542 Info.MI = 0;
1543 } else {
1544 // Macro definition.
1545 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1546 assert(GMacID);
1547
1548 // If this macro has already been loaded, don't do so again.
1549 // FIXME: This is highly dubious. Multiple macro definitions can have the
1550 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1551 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1552 return 0;
1553
1554 Info.MI = getMacro(GMacID);
1555 Info.SubModID = Info.MI->getOwningModuleID();
1556 }
1557 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1558 Info.F = PMInfo.M;
1559
1560 return new (Context) ModuleMacroInfo(Info);
1561}
1562
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001563void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1564 const PendingMacroInfo &PMInfo) {
1565 assert(II);
1566
1567 if (PMInfo.M->Kind != MK_Module) {
1568 installPCHMacroDirectives(II, *PMInfo.M,
1569 PMInfo.PCHMacroData.MacroDirectivesOffset);
1570 return;
1571 }
Richard Smith49f906a2014-03-01 00:08:04 +00001572
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001573 // Module Macro.
1574
Richard Smith49f906a2014-03-01 00:08:04 +00001575 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1576 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001577 return;
1578
Richard Smith49f906a2014-03-01 00:08:04 +00001579 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1580 if (Owner && Owner->NameVisibility == Module::Hidden) {
1581 // Macros in the owning module are hidden. Just remember this macro to
1582 // install if we make this module visible.
1583 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1584 } else {
1585 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001586 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001587}
1588
1589void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1590 ModuleFile &M, uint64_t Offset) {
1591 assert(M.Kind != MK_Module);
1592
1593 BitstreamCursor &Cursor = M.MacroCursor;
1594 SavedStreamPosition SavedPosition(Cursor);
1595 Cursor.JumpToBit(Offset);
1596
1597 llvm::BitstreamEntry Entry =
1598 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1599 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1600 Error("malformed block record in AST file");
1601 return;
1602 }
1603
1604 RecordData Record;
1605 PreprocessorRecordTypes RecType =
1606 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1607 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1608 Error("malformed block record in AST file");
1609 return;
1610 }
1611
1612 // Deserialize the macro directives history in reverse source-order.
1613 MacroDirective *Latest = 0, *Earliest = 0;
1614 unsigned Idx = 0, N = Record.size();
1615 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001616 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001617 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001618 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1619 switch (K) {
1620 case MacroDirective::MD_Define: {
1621 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1622 MacroInfo *MI = getMacro(GMacID);
1623 bool isImported = Record[Idx++];
1624 bool isAmbiguous = Record[Idx++];
1625 DefMacroDirective *DefMD =
1626 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1627 DefMD->setAmbiguous(isAmbiguous);
1628 MD = DefMD;
1629 break;
1630 }
1631 case MacroDirective::MD_Undefine:
1632 MD = PP.AllocateUndefMacroDirective(Loc);
1633 break;
1634 case MacroDirective::MD_Visibility: {
1635 bool isPublic = Record[Idx++];
1636 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1637 break;
1638 }
1639 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001640
1641 if (!Latest)
1642 Latest = MD;
1643 if (Earliest)
1644 Earliest->setPrevious(MD);
1645 Earliest = MD;
1646 }
1647
1648 PP.setLoadedMacroDirective(II, Latest);
1649}
1650
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001651/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001652/// modules.
1653static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001654 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001655 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001656 Module *PrevOwner = 0;
1657 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1658 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001659 SourceManager &SrcMgr = Reader.getSourceManager();
1660 bool PrevInSystem
1661 = PrevOwner? PrevOwner->IsSystem
1662 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1663 bool NewInSystem
1664 = NewOwner? NewOwner->IsSystem
1665 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1666 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001667 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001668 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001669}
1670
Richard Smith49f906a2014-03-01 00:08:04 +00001671void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1672 AmbiguousMacros &Ambig,
1673 llvm::ArrayRef<SubmoduleID> Overrides) {
1674 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1675 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001676
Richard Smith49f906a2014-03-01 00:08:04 +00001677 // If this macro is not yet visible, remove it from the hidden names list.
1678 Module *Owner = getSubmodule(OwnerID);
1679 HiddenNames &Hidden = HiddenNamesMap[Owner];
1680 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1681 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001682 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001683 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001684 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001685 }
1686
1687 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001688 Ambig.erase(
1689 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1690 return MD->getInfo()->getOwningModuleID() == OwnerID;
1691 }),
1692 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001693 }
1694}
1695
1696ASTReader::AmbiguousMacros *
1697ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1698 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001699 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001700 if (!Prev && Overrides.empty())
1701 return 0;
1702
1703 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1704 if (PrevDef && PrevDef->isAmbiguous()) {
1705 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1706 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1707 Ambig.push_back(PrevDef);
1708
1709 removeOverriddenMacros(II, Ambig, Overrides);
1710
1711 if (!Ambig.empty())
1712 return &Ambig;
1713
1714 AmbiguousMacroDefs.erase(II);
1715 } else {
1716 // There's no ambiguity yet. Maybe we're introducing one.
1717 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1718 if (PrevDef)
1719 Ambig.push_back(PrevDef);
1720
1721 removeOverriddenMacros(II, Ambig, Overrides);
1722
1723 if (!Ambig.empty()) {
1724 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1725 Result.swap(Ambig);
1726 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001727 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001728 }
Richard Smith49f906a2014-03-01 00:08:04 +00001729
1730 // We ended up with no ambiguity.
1731 return 0;
1732}
1733
1734void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1735 Module *Owner) {
1736 assert(II && Owner);
1737
1738 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1739 if (ImportLoc.isInvalid()) {
1740 // FIXME: If we made macros from this module visible but didn't provide a
1741 // source location for the import, we don't have a location for the macro.
1742 // Use the location at which the containing module file was first imported
1743 // for now.
1744 ImportLoc = MMI->F->DirectImportLoc;
1745 }
1746
1747 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1748 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1749
1750
1751 // Create a synthetic macro definition corresponding to the import (or null
1752 // if this was an undefinition of the macro).
1753 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1754
1755 // If there's no ambiguity, just install the macro.
1756 if (!Prev) {
1757 if (MD)
1758 PP.appendMacroDirective(II, MD);
1759 else
1760 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1761 return;
1762 }
1763 assert(!Prev->empty());
1764
1765 if (!MD) {
1766 // We imported a #undef that didn't remove all prior definitions. The most
1767 // recent prior definition remains, and we install it in the place of the
1768 // imported directive.
1769 MacroInfo *NewMI = Prev->back()->getInfo();
1770 Prev->pop_back();
1771 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1772 }
1773
1774 // We're introducing a macro definition that creates or adds to an ambiguity.
1775 // We can resolve that ambiguity if this macro is token-for-token identical to
1776 // all of the existing definitions.
1777 MacroInfo *NewMI = MD->getInfo();
1778 assert(NewMI && "macro definition with no MacroInfo?");
1779 while (!Prev->empty()) {
1780 MacroInfo *PrevMI = Prev->back()->getInfo();
1781 assert(PrevMI && "macro definition with no MacroInfo?");
1782
1783 // Before marking the macros as ambiguous, check if this is a case where
1784 // both macros are in system headers. If so, we trust that the system
1785 // did not get it wrong. This also handles cases where Clang's own
1786 // headers have a different spelling of certain system macros:
1787 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1788 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1789 //
1790 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1791 // overrides the system limits.h's macros, so there's no conflict here.
1792 if (NewMI != PrevMI &&
1793 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1794 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1795 break;
1796
1797 // The previous definition is the same as this one (or both are defined in
1798 // system modules so we can assume they're equivalent); we don't need to
1799 // track it any more.
1800 Prev->pop_back();
1801 }
1802
1803 if (!Prev->empty())
1804 MD->setAmbiguous(true);
1805
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001806 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807}
1808
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001809InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 // If this ID is bogus, just return an empty input file.
1811 if (ID == 0 || ID > F.InputFilesLoaded.size())
1812 return InputFile();
1813
1814 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001815 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 return F.InputFilesLoaded[ID-1];
1817
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001818 if (F.InputFilesLoaded[ID-1].isNotFound())
1819 return InputFile();
1820
Guy Benyei11169dd2012-12-18 14:30:41 +00001821 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001822 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 SavedStreamPosition SavedPosition(Cursor);
1824 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1825
1826 unsigned Code = Cursor.ReadCode();
1827 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001828 StringRef Blob;
1829 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 case INPUT_FILE: {
1831 unsigned StoredID = Record[0];
1832 assert(ID == StoredID && "Bogus stored ID or offset");
1833 (void)StoredID;
1834 off_t StoredSize = (off_t)Record[1];
1835 time_t StoredTime = (time_t)Record[2];
1836 bool Overridden = (bool)Record[3];
1837
1838 // Get the file entry for this input file.
Chris Lattner0e6c9402013-01-20 02:38:54 +00001839 StringRef OrigFilename = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 std::string Filename = OrigFilename;
1841 MaybeAddSystemRootToFilename(F, Filename);
1842 const FileEntry *File
1843 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1844 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1845
1846 // If we didn't find the file, resolve it relative to the
1847 // original directory from which this AST file was created.
1848 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1849 F.OriginalDir != CurrentDir) {
1850 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1851 F.OriginalDir,
1852 CurrentDir);
1853 if (!Resolved.empty())
1854 File = FileMgr.getFile(Resolved);
1855 }
1856
1857 // For an overridden file, create a virtual file with the stored
1858 // size/timestamp.
1859 if (Overridden && File == 0) {
1860 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1861 }
1862
1863 if (File == 0) {
1864 if (Complain) {
1865 std::string ErrorStr = "could not find file '";
1866 ErrorStr += Filename;
1867 ErrorStr += "' referenced by AST file";
1868 Error(ErrorStr.c_str());
1869 }
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001870 // Record that we didn't find the file.
1871 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
Guy Benyei11169dd2012-12-18 14:30:41 +00001872 return InputFile();
1873 }
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001874
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 // Check if there was a request to override the contents of the file
1876 // that was part of the precompiled header. Overridding such a file
1877 // can lead to problems when lexing using the source locations from the
1878 // PCH.
1879 SourceManager &SM = getSourceManager();
1880 if (!Overridden && SM.isFileOverridden(File)) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001881 if (Complain)
1882 Error(diag::err_fe_pch_file_overridden, Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 // After emitting the diagnostic, recover by disabling the override so
1884 // that the original file will be used.
1885 SM.disableFileContentsOverride(File);
1886 // The FileEntry is a virtual file entry with the size of the contents
1887 // that would override the original contents. Set it to the original's
1888 // size/time.
1889 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1890 StoredSize, StoredTime);
1891 }
1892
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001893 bool IsOutOfDate = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00001894
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001895 // For an overridden file, there is nothing to validate.
1896 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001897#if !defined(LLVM_ON_WIN32)
1898 // In our regression testing, the Windows file system seems to
1899 // have inconsistent modification times that sometimes
1900 // erroneously trigger this error-handling path.
1901 || StoredTime != File->getModificationTime()
1902#endif
1903 )) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00001904 if (Complain) {
Ben Langmuire82630d2014-01-17 00:19:09 +00001905 // Build a list of the PCH imports that got us here (in reverse).
1906 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1907 while (ImportStack.back()->ImportedBy.size() > 0)
1908 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1909
1910 // The top-level PCH is stale.
1911 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1912 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1913
1914 // Print the import stack.
1915 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1916 Diag(diag::note_pch_required_by)
1917 << Filename << ImportStack[0]->FileName;
1918 for (unsigned I = 1; I < ImportStack.size(); ++I)
1919 Diag(diag::note_pch_required_by)
1920 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor940e8052013-05-10 22:15:13 +00001921 }
Ben Langmuire82630d2014-01-17 00:19:09 +00001922
1923 if (!Diags.isDiagnosticInFlight())
1924 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001925 }
1926
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001927 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 }
1929
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001930 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1931
1932 // Note that we've loaded this input file.
1933 F.InputFilesLoaded[ID-1] = IF;
1934 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 }
1936 }
1937
1938 return InputFile();
1939}
1940
1941const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1942 ModuleFile &M = ModuleMgr.getPrimaryModule();
1943 std::string Filename = filenameStrRef;
1944 MaybeAddSystemRootToFilename(M, Filename);
1945 const FileEntry *File = FileMgr.getFile(Filename);
1946 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1947 M.OriginalDir != CurrentDir) {
1948 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1949 M.OriginalDir,
1950 CurrentDir);
1951 if (!resolved.empty())
1952 File = FileMgr.getFile(resolved);
1953 }
1954
1955 return File;
1956}
1957
1958/// \brief If we are loading a relocatable PCH file, and the filename is
1959/// not an absolute path, add the system root to the beginning of the file
1960/// name.
1961void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1962 std::string &Filename) {
1963 // If this is not a relocatable PCH file, there's nothing to do.
1964 if (!M.RelocatablePCH)
1965 return;
1966
1967 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1968 return;
1969
1970 if (isysroot.empty()) {
1971 // If no system root was given, default to '/'
1972 Filename.insert(Filename.begin(), '/');
1973 return;
1974 }
1975
1976 unsigned Length = isysroot.size();
1977 if (isysroot[Length - 1] != '/')
1978 Filename.insert(Filename.begin(), '/');
1979
1980 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1981}
1982
1983ASTReader::ASTReadResult
1984ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001985 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00001986 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001987 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00001988
1989 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1990 Error("malformed block record in AST file");
1991 return Failure;
1992 }
1993
1994 // Read all of the records and blocks in the control block.
1995 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001996 while (1) {
1997 llvm::BitstreamEntry Entry = Stream.advance();
1998
1999 switch (Entry.Kind) {
2000 case llvm::BitstreamEntry::Error:
2001 Error("malformed block record in AST file");
2002 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002003 case llvm::BitstreamEntry::EndBlock: {
2004 // Validate input files.
2005 const HeaderSearchOptions &HSOpts =
2006 PP.getHeaderSearchInfo().getHeaderSearchOpts();
2007 if (!DisableValidation &&
2008 (!HSOpts.ModulesValidateOncePerBuildSession ||
2009 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002011 // All user input files reside at the index range [0, Record[1]), and
2012 // system input files reside at [Record[1], Record[0]).
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00002013 // Record is the one from INPUT_FILE_OFFSETS.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002014 //
2015 // If we are reading a module, we will create a verification timestamp,
2016 // so we verify all input files. Otherwise, verify only user input
2017 // files.
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002018 unsigned NumInputs = Record[0];
2019 unsigned NumUserInputs = Record[1];
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002020 unsigned N = ValidateSystemInputs ||
2021 (HSOpts.ModulesValidateOncePerBuildSession &&
2022 F.Kind == MK_Module)
2023 ? NumInputs
2024 : NumUserInputs;
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002025 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002026 InputFile IF = getInputFile(F, I+1, Complain);
2027 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002032 }
2033
Chris Lattnere7b154b2013-01-19 21:39:22 +00002034 case llvm::BitstreamEntry::SubBlock:
2035 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 case INPUT_FILES_BLOCK_ID:
2037 F.InputFilesCursor = Stream;
2038 if (Stream.SkipBlock() || // Skip with the main cursor
2039 // Read the abbreviations
2040 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2041 Error("malformed block record in AST file");
2042 return Failure;
2043 }
2044 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002045
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002047 if (Stream.SkipBlock()) {
2048 Error("malformed block record in AST file");
2049 return Failure;
2050 }
2051 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002052 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002053
2054 case llvm::BitstreamEntry::Record:
2055 // The interesting case.
2056 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 }
2058
2059 // Read and process a record.
2060 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002061 StringRef Blob;
2062 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 case METADATA: {
2064 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2065 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002066 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2067 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 return VersionMismatch;
2069 }
2070
2071 bool hasErrors = Record[5];
2072 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2073 Diag(diag::err_pch_with_compiler_errors);
2074 return HadErrors;
2075 }
2076
2077 F.RelocatablePCH = Record[4];
2078
2079 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002080 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2082 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002083 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 return VersionMismatch;
2085 }
2086 break;
2087 }
2088
2089 case IMPORTS: {
2090 // Load each of the imported PCH files.
2091 unsigned Idx = 0, N = Record.size();
2092 while (Idx < N) {
2093 // Read information about the AST file.
2094 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2095 // The import location will be the local one for now; we will adjust
2096 // all import locations of module imports after the global source
2097 // location info are setup.
2098 SourceLocation ImportLoc =
2099 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002100 off_t StoredSize = (off_t)Record[Idx++];
2101 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 unsigned Length = Record[Idx++];
2103 SmallString<128> ImportedFile(Record.begin() + Idx,
2104 Record.begin() + Idx + Length);
2105 Idx += Length;
2106
2107 // Load the AST file.
2108 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002109 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 ClientLoadCapabilities)) {
2111 case Failure: return Failure;
2112 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002113 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 case OutOfDate: return OutOfDate;
2115 case VersionMismatch: return VersionMismatch;
2116 case ConfigurationMismatch: return ConfigurationMismatch;
2117 case HadErrors: return HadErrors;
2118 case Success: break;
2119 }
2120 }
2121 break;
2122 }
2123
2124 case LANGUAGE_OPTIONS: {
2125 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2126 if (Listener && &F == *ModuleMgr.begin() &&
2127 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002128 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 return ConfigurationMismatch;
2130 break;
2131 }
2132
2133 case TARGET_OPTIONS: {
2134 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2135 if (Listener && &F == *ModuleMgr.begin() &&
2136 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002137 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002138 return ConfigurationMismatch;
2139 break;
2140 }
2141
2142 case DIAGNOSTIC_OPTIONS: {
2143 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2144 if (Listener && &F == *ModuleMgr.begin() &&
2145 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002146 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 return ConfigurationMismatch;
2148 break;
2149 }
2150
2151 case FILE_SYSTEM_OPTIONS: {
2152 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2153 if (Listener && &F == *ModuleMgr.begin() &&
2154 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002155 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 return ConfigurationMismatch;
2157 break;
2158 }
2159
2160 case HEADER_SEARCH_OPTIONS: {
2161 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2162 if (Listener && &F == *ModuleMgr.begin() &&
2163 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002164 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002165 return ConfigurationMismatch;
2166 break;
2167 }
2168
2169 case PREPROCESSOR_OPTIONS: {
2170 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2171 if (Listener && &F == *ModuleMgr.begin() &&
2172 ParsePreprocessorOptions(Record, Complain, *Listener,
2173 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002174 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 return ConfigurationMismatch;
2176 break;
2177 }
2178
2179 case ORIGINAL_FILE:
2180 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002181 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002182 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2183 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2184 break;
2185
2186 case ORIGINAL_FILE_ID:
2187 F.OriginalSourceFileID = FileID::get(Record[0]);
2188 break;
2189
2190 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002191 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 break;
2193
2194 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002195 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 F.InputFilesLoaded.resize(Record[0]);
2197 break;
2198 }
2199 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002200}
2201
2202bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002203 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
2205 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2206 Error("malformed block record in AST file");
2207 return true;
2208 }
2209
2210 // Read all of the records and blocks for the AST file.
2211 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002212 while (1) {
2213 llvm::BitstreamEntry Entry = Stream.advance();
2214
2215 switch (Entry.Kind) {
2216 case llvm::BitstreamEntry::Error:
2217 Error("error at end of module block in AST file");
2218 return true;
2219 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002220 // Outside of C++, we do not store a lookup map for the translation unit.
2221 // Instead, mark it as needing a lookup map to be built if this module
2222 // contains any declarations lexically within it (which it always does!).
2223 // This usually has no cost, since we very rarely need the lookup map for
2224 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002225 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002226 if (DC->hasExternalLexicalStorage() &&
2227 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002229
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 return false;
2231 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002232 case llvm::BitstreamEntry::SubBlock:
2233 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 case DECLTYPES_BLOCK_ID:
2235 // We lazily load the decls block, but we want to set up the
2236 // DeclsCursor cursor to point into it. Clone our current bitcode
2237 // cursor to it, enter the block and read the abbrevs in that block.
2238 // With the main cursor, we just skip over it.
2239 F.DeclsCursor = Stream;
2240 if (Stream.SkipBlock() || // Skip with the main cursor.
2241 // Read the abbrevs.
2242 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2243 Error("malformed block record in AST file");
2244 return true;
2245 }
2246 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002247
Guy Benyei11169dd2012-12-18 14:30:41 +00002248 case DECL_UPDATES_BLOCK_ID:
2249 if (Stream.SkipBlock()) {
2250 Error("malformed block record in AST file");
2251 return true;
2252 }
2253 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002254
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 case PREPROCESSOR_BLOCK_ID:
2256 F.MacroCursor = Stream;
2257 if (!PP.getExternalSource())
2258 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002259
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 if (Stream.SkipBlock() ||
2261 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2262 Error("malformed block record in AST file");
2263 return true;
2264 }
2265 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2266 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002267
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 case PREPROCESSOR_DETAIL_BLOCK_ID:
2269 F.PreprocessorDetailCursor = Stream;
2270 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002271 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002273 Error("malformed preprocessor detail record in AST file");
2274 return true;
2275 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002277 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2278
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 if (!PP.getPreprocessingRecord())
2280 PP.createPreprocessingRecord();
2281 if (!PP.getPreprocessingRecord()->getExternalSource())
2282 PP.getPreprocessingRecord()->SetExternalSource(*this);
2283 break;
2284
2285 case SOURCE_MANAGER_BLOCK_ID:
2286 if (ReadSourceManagerBlock(F))
2287 return true;
2288 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002289
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 case SUBMODULE_BLOCK_ID:
2291 if (ReadSubmoduleBlock(F))
2292 return true;
2293 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002294
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002296 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 if (Stream.SkipBlock() ||
2298 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2299 Error("malformed comments block in AST file");
2300 return true;
2301 }
2302 CommentsCursors.push_back(std::make_pair(C, &F));
2303 break;
2304 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002305
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002307 if (Stream.SkipBlock()) {
2308 Error("malformed block record in AST file");
2309 return true;
2310 }
2311 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 }
2313 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002314
2315 case llvm::BitstreamEntry::Record:
2316 // The interesting case.
2317 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 }
2319
2320 // Read and process a record.
2321 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002322 StringRef Blob;
2323 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 default: // Default behavior: ignore.
2325 break;
2326
2327 case TYPE_OFFSET: {
2328 if (F.LocalNumTypes != 0) {
2329 Error("duplicate TYPE_OFFSET record in AST file");
2330 return true;
2331 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002332 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 F.LocalNumTypes = Record[0];
2334 unsigned LocalBaseTypeIndex = Record[1];
2335 F.BaseTypeIndex = getTotalNumTypes();
2336
2337 if (F.LocalNumTypes > 0) {
2338 // Introduce the global -> local mapping for types within this module.
2339 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2340
2341 // Introduce the local -> global mapping for types within this module.
2342 F.TypeRemap.insertOrReplace(
2343 std::make_pair(LocalBaseTypeIndex,
2344 F.BaseTypeIndex - LocalBaseTypeIndex));
2345
2346 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2347 }
2348 break;
2349 }
2350
2351 case DECL_OFFSET: {
2352 if (F.LocalNumDecls != 0) {
2353 Error("duplicate DECL_OFFSET record in AST file");
2354 return true;
2355 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002356 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 F.LocalNumDecls = Record[0];
2358 unsigned LocalBaseDeclID = Record[1];
2359 F.BaseDeclID = getTotalNumDecls();
2360
2361 if (F.LocalNumDecls > 0) {
2362 // Introduce the global -> local mapping for declarations within this
2363 // module.
2364 GlobalDeclMap.insert(
2365 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2366
2367 // Introduce the local -> global mapping for declarations within this
2368 // module.
2369 F.DeclRemap.insertOrReplace(
2370 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2371
2372 // Introduce the global -> local mapping for declarations within this
2373 // module.
2374 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2375
2376 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2377 }
2378 break;
2379 }
2380
2381 case TU_UPDATE_LEXICAL: {
2382 DeclContext *TU = Context.getTranslationUnitDecl();
2383 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002384 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002386 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 TU->setHasExternalLexicalStorage(true);
2388 break;
2389 }
2390
2391 case UPDATE_VISIBLE: {
2392 unsigned Idx = 0;
2393 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2394 ASTDeclContextNameLookupTable *Table =
2395 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002396 (const unsigned char *)Blob.data() + Record[Idx++],
2397 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 ASTDeclContextNameLookupTrait(*this, F));
2399 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2400 DeclContext *TU = Context.getTranslationUnitDecl();
2401 F.DeclContextInfos[TU].NameLookupTableData = Table;
2402 TU->setHasExternalVisibleStorage(true);
2403 } else
2404 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2405 break;
2406 }
2407
2408 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002409 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 if (Record[0]) {
2411 F.IdentifierLookupTable
2412 = ASTIdentifierLookupTable::Create(
2413 (const unsigned char *)F.IdentifierTableData + Record[0],
2414 (const unsigned char *)F.IdentifierTableData,
2415 ASTIdentifierLookupTrait(*this, F));
2416
2417 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2418 }
2419 break;
2420
2421 case IDENTIFIER_OFFSET: {
2422 if (F.LocalNumIdentifiers != 0) {
2423 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2424 return true;
2425 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002426 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 F.LocalNumIdentifiers = Record[0];
2428 unsigned LocalBaseIdentifierID = Record[1];
2429 F.BaseIdentifierID = getTotalNumIdentifiers();
2430
2431 if (F.LocalNumIdentifiers > 0) {
2432 // Introduce the global -> local mapping for identifiers within this
2433 // module.
2434 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2435 &F));
2436
2437 // Introduce the local -> global mapping for identifiers within this
2438 // module.
2439 F.IdentifierRemap.insertOrReplace(
2440 std::make_pair(LocalBaseIdentifierID,
2441 F.BaseIdentifierID - LocalBaseIdentifierID));
2442
2443 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2444 + F.LocalNumIdentifiers);
2445 }
2446 break;
2447 }
2448
Ben Langmuir332aafe2014-01-31 01:06:56 +00002449 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002451 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 break;
2453
2454 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002455 if (SpecialTypes.empty()) {
2456 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2457 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2458 break;
2459 }
2460
2461 if (SpecialTypes.size() != Record.size()) {
2462 Error("invalid special-types record");
2463 return true;
2464 }
2465
2466 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2467 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2468 if (!SpecialTypes[I])
2469 SpecialTypes[I] = ID;
2470 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2471 // merge step?
2472 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 break;
2474
2475 case STATISTICS:
2476 TotalNumStatements += Record[0];
2477 TotalNumMacros += Record[1];
2478 TotalLexicalDeclContexts += Record[2];
2479 TotalVisibleDeclContexts += Record[3];
2480 break;
2481
2482 case UNUSED_FILESCOPED_DECLS:
2483 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2484 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2485 break;
2486
2487 case DELEGATING_CTORS:
2488 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2489 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2490 break;
2491
2492 case WEAK_UNDECLARED_IDENTIFIERS:
2493 if (Record.size() % 4 != 0) {
2494 Error("invalid weak identifiers record");
2495 return true;
2496 }
2497
2498 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2499 // files. This isn't the way to do it :)
2500 WeakUndeclaredIdentifiers.clear();
2501
2502 // Translate the weak, undeclared identifiers into global IDs.
2503 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2504 WeakUndeclaredIdentifiers.push_back(
2505 getGlobalIdentifierID(F, Record[I++]));
2506 WeakUndeclaredIdentifiers.push_back(
2507 getGlobalIdentifierID(F, Record[I++]));
2508 WeakUndeclaredIdentifiers.push_back(
2509 ReadSourceLocation(F, Record, I).getRawEncoding());
2510 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2511 }
2512 break;
2513
Richard Smith78165b52013-01-10 23:43:47 +00002514 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002516 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 break;
2518
2519 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002520 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 F.LocalNumSelectors = Record[0];
2522 unsigned LocalBaseSelectorID = Record[1];
2523 F.BaseSelectorID = getTotalNumSelectors();
2524
2525 if (F.LocalNumSelectors > 0) {
2526 // Introduce the global -> local mapping for selectors within this
2527 // module.
2528 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2529
2530 // Introduce the local -> global mapping for selectors within this
2531 // module.
2532 F.SelectorRemap.insertOrReplace(
2533 std::make_pair(LocalBaseSelectorID,
2534 F.BaseSelectorID - LocalBaseSelectorID));
2535
2536 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2537 }
2538 break;
2539 }
2540
2541 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002542 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 if (Record[0])
2544 F.SelectorLookupTable
2545 = ASTSelectorLookupTable::Create(
2546 F.SelectorLookupTableData + Record[0],
2547 F.SelectorLookupTableData,
2548 ASTSelectorLookupTrait(*this, F));
2549 TotalNumMethodPoolEntries += Record[1];
2550 break;
2551
2552 case REFERENCED_SELECTOR_POOL:
2553 if (!Record.empty()) {
2554 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2555 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2556 Record[Idx++]));
2557 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2558 getRawEncoding());
2559 }
2560 }
2561 break;
2562
2563 case PP_COUNTER_VALUE:
2564 if (!Record.empty() && Listener)
2565 Listener->ReadCounter(F, Record[0]);
2566 break;
2567
2568 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002569 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 F.NumFileSortedDecls = Record[0];
2571 break;
2572
2573 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002574 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 F.LocalNumSLocEntries = Record[0];
2576 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002577 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2579 SLocSpaceSize);
2580 // Make our entry in the range map. BaseID is negative and growing, so
2581 // we invert it. Because we invert it, though, we need the other end of
2582 // the range.
2583 unsigned RangeStart =
2584 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2585 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2586 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2587
2588 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2589 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2590 GlobalSLocOffsetMap.insert(
2591 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2592 - SLocSpaceSize,&F));
2593
2594 // Initialize the remapping table.
2595 // Invalid stays invalid.
2596 F.SLocRemap.insert(std::make_pair(0U, 0));
2597 // This module. Base was 2 when being compiled.
2598 F.SLocRemap.insert(std::make_pair(2U,
2599 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2600
2601 TotalNumSLocEntries += F.LocalNumSLocEntries;
2602 break;
2603 }
2604
2605 case MODULE_OFFSET_MAP: {
2606 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002607 const unsigned char *Data = (const unsigned char*)Blob.data();
2608 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002609
2610 // Continuous range maps we may be updating in our module.
2611 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2612 ContinuousRangeMap<uint32_t, int, 2>::Builder
2613 IdentifierRemap(F.IdentifierRemap);
2614 ContinuousRangeMap<uint32_t, int, 2>::Builder
2615 MacroRemap(F.MacroRemap);
2616 ContinuousRangeMap<uint32_t, int, 2>::Builder
2617 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2618 ContinuousRangeMap<uint32_t, int, 2>::Builder
2619 SubmoduleRemap(F.SubmoduleRemap);
2620 ContinuousRangeMap<uint32_t, int, 2>::Builder
2621 SelectorRemap(F.SelectorRemap);
2622 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2623 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2624
2625 while(Data < DataEnd) {
2626 uint16_t Len = io::ReadUnalignedLE16(Data);
2627 StringRef Name = StringRef((const char*)Data, Len);
2628 Data += Len;
2629 ModuleFile *OM = ModuleMgr.lookup(Name);
2630 if (!OM) {
2631 Error("SourceLocation remap refers to unknown module");
2632 return true;
2633 }
2634
2635 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2636 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2637 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2638 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2639 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2640 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2641 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2642 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2643
2644 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2645 SLocRemap.insert(std::make_pair(SLocOffset,
2646 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2647 IdentifierRemap.insert(
2648 std::make_pair(IdentifierIDOffset,
2649 OM->BaseIdentifierID - IdentifierIDOffset));
2650 MacroRemap.insert(std::make_pair(MacroIDOffset,
2651 OM->BaseMacroID - MacroIDOffset));
2652 PreprocessedEntityRemap.insert(
2653 std::make_pair(PreprocessedEntityIDOffset,
2654 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2655 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2656 OM->BaseSubmoduleID - SubmoduleIDOffset));
2657 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2658 OM->BaseSelectorID - SelectorIDOffset));
2659 DeclRemap.insert(std::make_pair(DeclIDOffset,
2660 OM->BaseDeclID - DeclIDOffset));
2661
2662 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2663 OM->BaseTypeIndex - TypeIndexOffset));
2664
2665 // Global -> local mappings.
2666 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2667 }
2668 break;
2669 }
2670
2671 case SOURCE_MANAGER_LINE_TABLE:
2672 if (ParseLineTable(F, Record))
2673 return true;
2674 break;
2675
2676 case SOURCE_LOCATION_PRELOADS: {
2677 // Need to transform from the local view (1-based IDs) to the global view,
2678 // which is based off F.SLocEntryBaseID.
2679 if (!F.PreloadSLocEntries.empty()) {
2680 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2681 return true;
2682 }
2683
2684 F.PreloadSLocEntries.swap(Record);
2685 break;
2686 }
2687
2688 case EXT_VECTOR_DECLS:
2689 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2690 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2691 break;
2692
2693 case VTABLE_USES:
2694 if (Record.size() % 3 != 0) {
2695 Error("Invalid VTABLE_USES record");
2696 return true;
2697 }
2698
2699 // Later tables overwrite earlier ones.
2700 // FIXME: Modules will have some trouble with this. This is clearly not
2701 // the right way to do this.
2702 VTableUses.clear();
2703
2704 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2705 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2706 VTableUses.push_back(
2707 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2708 VTableUses.push_back(Record[Idx++]);
2709 }
2710 break;
2711
2712 case DYNAMIC_CLASSES:
2713 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2714 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2715 break;
2716
2717 case PENDING_IMPLICIT_INSTANTIATIONS:
2718 if (PendingInstantiations.size() % 2 != 0) {
2719 Error("Invalid existing PendingInstantiations");
2720 return true;
2721 }
2722
2723 if (Record.size() % 2 != 0) {
2724 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2725 return true;
2726 }
2727
2728 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2729 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2730 PendingInstantiations.push_back(
2731 ReadSourceLocation(F, Record, I).getRawEncoding());
2732 }
2733 break;
2734
2735 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002736 if (Record.size() != 2) {
2737 Error("Invalid SEMA_DECL_REFS block");
2738 return true;
2739 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2741 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2742 break;
2743
2744 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002745 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2746 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2747 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748
2749 unsigned LocalBasePreprocessedEntityID = Record[0];
2750
2751 unsigned StartingID;
2752 if (!PP.getPreprocessingRecord())
2753 PP.createPreprocessingRecord();
2754 if (!PP.getPreprocessingRecord()->getExternalSource())
2755 PP.getPreprocessingRecord()->SetExternalSource(*this);
2756 StartingID
2757 = PP.getPreprocessingRecord()
2758 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2759 F.BasePreprocessedEntityID = StartingID;
2760
2761 if (F.NumPreprocessedEntities > 0) {
2762 // Introduce the global -> local mapping for preprocessed entities in
2763 // this module.
2764 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2765
2766 // Introduce the local -> global mapping for preprocessed entities in
2767 // this module.
2768 F.PreprocessedEntityRemap.insertOrReplace(
2769 std::make_pair(LocalBasePreprocessedEntityID,
2770 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2771 }
2772
2773 break;
2774 }
2775
2776 case DECL_UPDATE_OFFSETS: {
2777 if (Record.size() % 2 != 0) {
2778 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2779 return true;
2780 }
2781 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2782 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2783 .push_back(std::make_pair(&F, Record[I+1]));
2784 break;
2785 }
2786
2787 case DECL_REPLACEMENTS: {
2788 if (Record.size() % 3 != 0) {
2789 Error("invalid DECL_REPLACEMENTS block in AST file");
2790 return true;
2791 }
2792 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2793 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2794 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2795 break;
2796 }
2797
2798 case OBJC_CATEGORIES_MAP: {
2799 if (F.LocalNumObjCCategoriesInMap != 0) {
2800 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2801 return true;
2802 }
2803
2804 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002805 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 break;
2807 }
2808
2809 case OBJC_CATEGORIES:
2810 F.ObjCCategories.swap(Record);
2811 break;
2812
2813 case CXX_BASE_SPECIFIER_OFFSETS: {
2814 if (F.LocalNumCXXBaseSpecifiers != 0) {
2815 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2816 return true;
2817 }
2818
2819 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002820 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2822 break;
2823 }
2824
2825 case DIAG_PRAGMA_MAPPINGS:
2826 if (F.PragmaDiagMappings.empty())
2827 F.PragmaDiagMappings.swap(Record);
2828 else
2829 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2830 Record.begin(), Record.end());
2831 break;
2832
2833 case CUDA_SPECIAL_DECL_REFS:
2834 // Later tables overwrite earlier ones.
2835 // FIXME: Modules will have trouble with this.
2836 CUDASpecialDeclRefs.clear();
2837 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2838 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2839 break;
2840
2841 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002842 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 if (Record[0]) {
2845 F.HeaderFileInfoTable
2846 = HeaderFileInfoLookupTable::Create(
2847 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2848 (const unsigned char *)F.HeaderFileInfoTableData,
2849 HeaderFileInfoTrait(*this, F,
2850 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002851 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002852
2853 PP.getHeaderSearchInfo().SetExternalSource(this);
2854 if (!PP.getHeaderSearchInfo().getExternalLookup())
2855 PP.getHeaderSearchInfo().SetExternalLookup(this);
2856 }
2857 break;
2858 }
2859
2860 case FP_PRAGMA_OPTIONS:
2861 // Later tables overwrite earlier ones.
2862 FPPragmaOptions.swap(Record);
2863 break;
2864
2865 case OPENCL_EXTENSIONS:
2866 // Later tables overwrite earlier ones.
2867 OpenCLExtensions.swap(Record);
2868 break;
2869
2870 case TENTATIVE_DEFINITIONS:
2871 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2872 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2873 break;
2874
2875 case KNOWN_NAMESPACES:
2876 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2877 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2878 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002879
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002880 case UNDEFINED_BUT_USED:
2881 if (UndefinedButUsed.size() % 2 != 0) {
2882 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002883 return true;
2884 }
2885
2886 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002887 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00002888 return true;
2889 }
2890 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002891 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2892 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00002893 ReadSourceLocation(F, Record, I).getRawEncoding());
2894 }
2895 break;
2896
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 case IMPORTED_MODULES: {
2898 if (F.Kind != MK_Module) {
2899 // If we aren't loading a module (which has its own exports), make
2900 // all of the imported modules visible.
2901 // FIXME: Deal with macros-only imports.
2902 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2903 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2904 ImportedModules.push_back(GlobalID);
2905 }
2906 }
2907 break;
2908 }
2909
2910 case LOCAL_REDECLARATIONS: {
2911 F.RedeclarationChains.swap(Record);
2912 break;
2913 }
2914
2915 case LOCAL_REDECLARATIONS_MAP: {
2916 if (F.LocalNumRedeclarationsInMap != 0) {
2917 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2918 return true;
2919 }
2920
2921 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002922 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 break;
2924 }
2925
2926 case MERGED_DECLARATIONS: {
2927 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2928 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2929 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2930 for (unsigned N = Record[Idx++]; N > 0; --N)
2931 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2932 }
2933 break;
2934 }
2935
2936 case MACRO_OFFSET: {
2937 if (F.LocalNumMacros != 0) {
2938 Error("duplicate MACRO_OFFSET record in AST file");
2939 return true;
2940 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002941 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 F.LocalNumMacros = Record[0];
2943 unsigned LocalBaseMacroID = Record[1];
2944 F.BaseMacroID = getTotalNumMacros();
2945
2946 if (F.LocalNumMacros > 0) {
2947 // Introduce the global -> local mapping for macros within this module.
2948 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2949
2950 // Introduce the local -> global mapping for macros within this module.
2951 F.MacroRemap.insertOrReplace(
2952 std::make_pair(LocalBaseMacroID,
2953 F.BaseMacroID - LocalBaseMacroID));
2954
2955 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2956 }
2957 break;
2958 }
2959
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002960 case MACRO_TABLE: {
2961 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 break;
2963 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00002964
2965 case LATE_PARSED_TEMPLATE: {
2966 LateParsedTemplates.append(Record.begin(), Record.end());
2967 break;
2968 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002969 }
2970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002971}
2972
Douglas Gregorc1489562013-02-12 23:36:21 +00002973/// \brief Move the given method to the back of the global list of methods.
2974static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
2975 // Find the entry for this selector in the method pool.
2976 Sema::GlobalMethodPool::iterator Known
2977 = S.MethodPool.find(Method->getSelector());
2978 if (Known == S.MethodPool.end())
2979 return;
2980
2981 // Retrieve the appropriate method list.
2982 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
2983 : Known->second.second;
2984 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002985 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00002986 if (!Found) {
2987 if (List->Method == Method) {
2988 Found = true;
2989 } else {
2990 // Keep searching.
2991 continue;
2992 }
2993 }
2994
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002995 if (List->getNext())
2996 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00002997 else
2998 List->Method = Method;
2999 }
3000}
3001
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003002void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003003 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3004 Decl *D = Names.HiddenDecls[I];
3005 bool wasHidden = D->Hidden;
3006 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003007
Richard Smith49f906a2014-03-01 00:08:04 +00003008 if (wasHidden && SemaObj) {
3009 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3010 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003011 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 }
3013 }
Richard Smith49f906a2014-03-01 00:08:04 +00003014
3015 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3016 E = Names.HiddenMacros.end();
3017 I != E; ++I)
3018 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003019}
3020
Richard Smith49f906a2014-03-01 00:08:04 +00003021void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003022 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003023 SourceLocation ImportLoc,
3024 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003026 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003027 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003029 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003030
3031 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003032 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // there is nothing more to do.
3034 continue;
3035 }
Richard Smith49f906a2014-03-01 00:08:04 +00003036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 if (!Mod->isAvailable()) {
3038 // Modules that aren't available cannot be made visible.
3039 continue;
3040 }
3041
3042 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003043 if (NameVisibility >= Module::MacrosVisible &&
3044 Mod->NameVisibility < Module::MacrosVisible)
3045 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003047
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 // If we've already deserialized any names from this module,
3049 // mark them as visible.
3050 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3051 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003052 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 HiddenNamesMap.erase(Hidden);
3054 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003055
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003057 SmallVector<Module *, 16> Exports;
3058 Mod->getExportedModules(Exports);
3059 for (SmallVectorImpl<Module *>::iterator
3060 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3061 Module *Exported = *I;
3062 if (Visited.insert(Exported))
3063 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003065
3066 // Detect any conflicts.
3067 if (Complain) {
3068 assert(ImportLoc.isValid() && "Missing import location");
3069 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3070 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3071 Diag(ImportLoc, diag::warn_module_conflict)
3072 << Mod->getFullModuleName()
3073 << Mod->Conflicts[I].Other->getFullModuleName()
3074 << Mod->Conflicts[I].Message;
3075 // FIXME: Need note where the other module was imported.
3076 }
3077 }
3078 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 }
3080}
3081
Douglas Gregore060e572013-01-25 01:03:03 +00003082bool ASTReader::loadGlobalIndex() {
3083 if (GlobalIndex)
3084 return false;
3085
3086 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3087 !Context.getLangOpts().Modules)
3088 return true;
3089
3090 // Try to load the global index.
3091 TriedLoadingGlobalIndex = true;
3092 StringRef ModuleCachePath
3093 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3094 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003095 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003096 if (!Result.first)
3097 return true;
3098
3099 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003100 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003101 return false;
3102}
3103
3104bool ASTReader::isGlobalIndexUnavailable() const {
3105 return Context.getLangOpts().Modules && UseGlobalIndex &&
3106 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3107}
3108
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003109static void updateModuleTimestamp(ModuleFile &MF) {
3110 // Overwrite the timestamp file contents so that file's mtime changes.
3111 std::string TimestampFilename = MF.getTimestampFilename();
3112 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003113 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003114 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003115 if (!ErrorInfo.empty())
3116 return;
3117 OS << "Timestamp file\n";
3118}
3119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3121 ModuleKind Type,
3122 SourceLocation ImportLoc,
3123 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003124 llvm::SaveAndRestore<SourceLocation>
3125 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 // Bump the generation number.
3128 unsigned PreviousGeneration = CurrentGeneration++;
3129
3130 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003131 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3133 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003134 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 ClientLoadCapabilities)) {
3136 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003137 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 case OutOfDate:
3139 case VersionMismatch:
3140 case ConfigurationMismatch:
3141 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003142 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3143 Context.getLangOpts().Modules
3144 ? &PP.getHeaderSearchInfo().getModuleMap()
3145 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003146
3147 // If we find that any modules are unusable, the global index is going
3148 // to be out-of-date. Just remove it.
3149 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003150 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 return ReadResult;
3152
3153 case Success:
3154 break;
3155 }
3156
3157 // Here comes stuff that we only do once the entire chain is loaded.
3158
3159 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003160 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3161 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 M != MEnd; ++M) {
3163 ModuleFile &F = *M->Mod;
3164
3165 // Read the AST block.
3166 if (ReadASTBlock(F))
3167 return Failure;
3168
3169 // Once read, set the ModuleFile bit base offset and update the size in
3170 // bits of all files we've seen.
3171 F.GlobalBitOffset = TotalModulesSizeInBits;
3172 TotalModulesSizeInBits += F.SizeInBits;
3173 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3174
3175 // Preload SLocEntries.
3176 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3177 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3178 // Load it through the SourceManager and don't call ReadSLocEntry()
3179 // directly because the entry may have already been loaded in which case
3180 // calling ReadSLocEntry() directly would trigger an assertion in
3181 // SourceManager.
3182 SourceMgr.getLoadedSLocEntryByID(Index);
3183 }
3184 }
3185
Douglas Gregor603cd862013-03-22 18:50:14 +00003186 // Setup the import locations and notify the module manager that we've
3187 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003188 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3189 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 M != MEnd; ++M) {
3191 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003192
3193 ModuleMgr.moduleFileAccepted(&F);
3194
3195 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003196 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 if (!M->ImportedBy)
3198 F.ImportLoc = M->ImportLoc;
3199 else
3200 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3201 M->ImportLoc.getRawEncoding());
3202 }
3203
3204 // Mark all of the identifiers in the identifier table as being out of date,
3205 // so that various accessors know to check the loaded modules when the
3206 // identifier is used.
3207 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3208 IdEnd = PP.getIdentifierTable().end();
3209 Id != IdEnd; ++Id)
3210 Id->second->setOutOfDate(true);
3211
3212 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003213 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3214 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3216 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003217
3218 switch (Unresolved.Kind) {
3219 case UnresolvedModuleRef::Conflict:
3220 if (ResolvedMod) {
3221 Module::Conflict Conflict;
3222 Conflict.Other = ResolvedMod;
3223 Conflict.Message = Unresolved.String.str();
3224 Unresolved.Mod->Conflicts.push_back(Conflict);
3225 }
3226 continue;
3227
3228 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 if (ResolvedMod)
3230 Unresolved.Mod->Imports.push_back(ResolvedMod);
3231 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003232
Douglas Gregorfb912652013-03-20 21:10:35 +00003233 case UnresolvedModuleRef::Export:
3234 if (ResolvedMod || Unresolved.IsWildcard)
3235 Unresolved.Mod->Exports.push_back(
3236 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3237 continue;
3238 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003240 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003241
3242 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3243 // Might be unnecessary as use declarations are only used to build the
3244 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003245
3246 InitializeContext();
3247
Richard Smith3d8e97e2013-10-18 06:54:39 +00003248 if (SemaObj)
3249 UpdateSema();
3250
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 if (DeserializationListener)
3252 DeserializationListener->ReaderInitialized(this);
3253
3254 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3255 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3256 PrimaryModule.OriginalSourceFileID
3257 = FileID::get(PrimaryModule.SLocEntryBaseID
3258 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3259
3260 // If this AST file is a precompiled preamble, then set the
3261 // preamble file ID of the source manager to the file source file
3262 // from which the preamble was built.
3263 if (Type == MK_Preamble) {
3264 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3265 } else if (Type == MK_MainFile) {
3266 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3267 }
3268 }
3269
3270 // For any Objective-C class definitions we have already loaded, make sure
3271 // that we load any additional categories.
3272 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3273 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3274 ObjCClassesLoaded[I],
3275 PreviousGeneration);
3276 }
Douglas Gregore060e572013-01-25 01:03:03 +00003277
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003278 if (PP.getHeaderSearchInfo()
3279 .getHeaderSearchOpts()
3280 .ModulesValidateOncePerBuildSession) {
3281 // Now we are certain that the module and all modules it depends on are
3282 // up to date. Create or update timestamp files for modules that are
3283 // located in the module cache (not for PCH files that could be anywhere
3284 // in the filesystem).
3285 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3286 ImportedModule &M = Loaded[I];
3287 if (M.Mod->Kind == MK_Module) {
3288 updateModuleTimestamp(*M.Mod);
3289 }
3290 }
3291 }
3292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 return Success;
3294}
3295
3296ASTReader::ASTReadResult
3297ASTReader::ReadASTCore(StringRef FileName,
3298 ModuleKind Type,
3299 SourceLocation ImportLoc,
3300 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003301 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003302 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 unsigned ClientLoadCapabilities) {
3304 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003306 ModuleManager::AddModuleResult AddResult
3307 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3308 CurrentGeneration, ExpectedSize, ExpectedModTime,
3309 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003310
Douglas Gregor7029ce12013-03-19 00:28:20 +00003311 switch (AddResult) {
3312 case ModuleManager::AlreadyLoaded:
3313 return Success;
3314
3315 case ModuleManager::NewlyLoaded:
3316 // Load module file below.
3317 break;
3318
3319 case ModuleManager::Missing:
3320 // The module file was missing; if the client handle handle, that, return
3321 // it.
3322 if (ClientLoadCapabilities & ARR_Missing)
3323 return Missing;
3324
3325 // Otherwise, return an error.
3326 {
3327 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3328 + ErrorStr;
3329 Error(Msg);
3330 }
3331 return Failure;
3332
3333 case ModuleManager::OutOfDate:
3334 // We couldn't load the module file because it is out-of-date. If the
3335 // client can handle out-of-date, return it.
3336 if (ClientLoadCapabilities & ARR_OutOfDate)
3337 return OutOfDate;
3338
3339 // Otherwise, return an error.
3340 {
3341 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3342 + ErrorStr;
3343 Error(Msg);
3344 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 return Failure;
3346 }
3347
Douglas Gregor7029ce12013-03-19 00:28:20 +00003348 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003349
3350 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3351 // module?
3352 if (FileName != "-") {
3353 CurrentDir = llvm::sys::path::parent_path(FileName);
3354 if (CurrentDir.empty()) CurrentDir = ".";
3355 }
3356
3357 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003358 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 Stream.init(F.StreamFile);
3360 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3361
3362 // Sniff for the signature.
3363 if (Stream.Read(8) != 'C' ||
3364 Stream.Read(8) != 'P' ||
3365 Stream.Read(8) != 'C' ||
3366 Stream.Read(8) != 'H') {
3367 Diag(diag::err_not_a_pch_file) << FileName;
3368 return Failure;
3369 }
3370
3371 // This is used for compatibility with older PCH formats.
3372 bool HaveReadControlBlock = false;
3373
Chris Lattnerefa77172013-01-20 00:00:22 +00003374 while (1) {
3375 llvm::BitstreamEntry Entry = Stream.advance();
3376
3377 switch (Entry.Kind) {
3378 case llvm::BitstreamEntry::Error:
3379 case llvm::BitstreamEntry::EndBlock:
3380 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 Error("invalid record at top-level of AST file");
3382 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003383
3384 case llvm::BitstreamEntry::SubBlock:
3385 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 }
3387
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003389 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3391 if (Stream.ReadBlockInfoBlock()) {
3392 Error("malformed BlockInfoBlock in AST file");
3393 return Failure;
3394 }
3395 break;
3396 case CONTROL_BLOCK_ID:
3397 HaveReadControlBlock = true;
3398 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3399 case Success:
3400 break;
3401
3402 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003403 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 case OutOfDate: return OutOfDate;
3405 case VersionMismatch: return VersionMismatch;
3406 case ConfigurationMismatch: return ConfigurationMismatch;
3407 case HadErrors: return HadErrors;
3408 }
3409 break;
3410 case AST_BLOCK_ID:
3411 if (!HaveReadControlBlock) {
3412 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003413 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 return VersionMismatch;
3415 }
3416
3417 // Record that we've loaded this module.
3418 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3419 return Success;
3420
3421 default:
3422 if (Stream.SkipBlock()) {
3423 Error("malformed block record in AST file");
3424 return Failure;
3425 }
3426 break;
3427 }
3428 }
3429
3430 return Success;
3431}
3432
3433void ASTReader::InitializeContext() {
3434 // If there's a listener, notify them that we "read" the translation unit.
3435 if (DeserializationListener)
3436 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3437 Context.getTranslationUnitDecl());
3438
3439 // Make sure we load the declaration update records for the translation unit,
3440 // if there are any.
3441 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3442 Context.getTranslationUnitDecl());
3443
3444 // FIXME: Find a better way to deal with collisions between these
3445 // built-in types. Right now, we just ignore the problem.
3446
3447 // Load the special types.
3448 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3449 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3450 if (!Context.CFConstantStringTypeDecl)
3451 Context.setCFConstantStringType(GetType(String));
3452 }
3453
3454 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3455 QualType FileType = GetType(File);
3456 if (FileType.isNull()) {
3457 Error("FILE type is NULL");
3458 return;
3459 }
3460
3461 if (!Context.FILEDecl) {
3462 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3463 Context.setFILEDecl(Typedef->getDecl());
3464 else {
3465 const TagType *Tag = FileType->getAs<TagType>();
3466 if (!Tag) {
3467 Error("Invalid FILE type in AST file");
3468 return;
3469 }
3470 Context.setFILEDecl(Tag->getDecl());
3471 }
3472 }
3473 }
3474
3475 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3476 QualType Jmp_bufType = GetType(Jmp_buf);
3477 if (Jmp_bufType.isNull()) {
3478 Error("jmp_buf type is NULL");
3479 return;
3480 }
3481
3482 if (!Context.jmp_bufDecl) {
3483 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3484 Context.setjmp_bufDecl(Typedef->getDecl());
3485 else {
3486 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3487 if (!Tag) {
3488 Error("Invalid jmp_buf type in AST file");
3489 return;
3490 }
3491 Context.setjmp_bufDecl(Tag->getDecl());
3492 }
3493 }
3494 }
3495
3496 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3497 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3498 if (Sigjmp_bufType.isNull()) {
3499 Error("sigjmp_buf type is NULL");
3500 return;
3501 }
3502
3503 if (!Context.sigjmp_bufDecl) {
3504 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3505 Context.setsigjmp_bufDecl(Typedef->getDecl());
3506 else {
3507 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3508 assert(Tag && "Invalid sigjmp_buf type in AST file");
3509 Context.setsigjmp_bufDecl(Tag->getDecl());
3510 }
3511 }
3512 }
3513
3514 if (unsigned ObjCIdRedef
3515 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3516 if (Context.ObjCIdRedefinitionType.isNull())
3517 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3518 }
3519
3520 if (unsigned ObjCClassRedef
3521 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3522 if (Context.ObjCClassRedefinitionType.isNull())
3523 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3524 }
3525
3526 if (unsigned ObjCSelRedef
3527 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3528 if (Context.ObjCSelRedefinitionType.isNull())
3529 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3530 }
3531
3532 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3533 QualType Ucontext_tType = GetType(Ucontext_t);
3534 if (Ucontext_tType.isNull()) {
3535 Error("ucontext_t type is NULL");
3536 return;
3537 }
3538
3539 if (!Context.ucontext_tDecl) {
3540 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3541 Context.setucontext_tDecl(Typedef->getDecl());
3542 else {
3543 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3544 assert(Tag && "Invalid ucontext_t type in AST file");
3545 Context.setucontext_tDecl(Tag->getDecl());
3546 }
3547 }
3548 }
3549 }
3550
3551 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3552
3553 // If there were any CUDA special declarations, deserialize them.
3554 if (!CUDASpecialDeclRefs.empty()) {
3555 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3556 Context.setcudaConfigureCallDecl(
3557 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3558 }
3559
3560 // Re-export any modules that were imported by a non-module AST file.
3561 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3562 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003563 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003564 /*ImportLoc=*/SourceLocation(),
3565 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 }
3567 ImportedModules.clear();
3568}
3569
3570void ASTReader::finalizeForWriting() {
3571 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3572 HiddenEnd = HiddenNamesMap.end();
3573 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003574 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 }
3576 HiddenNamesMap.clear();
3577}
3578
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003579/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3580/// cursor into the start of the given block ID, returning false on success and
3581/// true on failure.
3582static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003583 while (1) {
3584 llvm::BitstreamEntry Entry = Cursor.advance();
3585 switch (Entry.Kind) {
3586 case llvm::BitstreamEntry::Error:
3587 case llvm::BitstreamEntry::EndBlock:
3588 return true;
3589
3590 case llvm::BitstreamEntry::Record:
3591 // Ignore top-level records.
3592 Cursor.skipRecord(Entry.ID);
3593 break;
3594
3595 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003596 if (Entry.ID == BlockID) {
3597 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003598 return true;
3599 // Found it!
3600 return false;
3601 }
3602
3603 if (Cursor.SkipBlock())
3604 return true;
3605 }
3606 }
3607}
3608
Guy Benyei11169dd2012-12-18 14:30:41 +00003609/// \brief Retrieve the name of the original source file name
3610/// directly from the AST file, without actually loading the AST
3611/// file.
3612std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3613 FileManager &FileMgr,
3614 DiagnosticsEngine &Diags) {
3615 // Open the AST file.
3616 std::string ErrStr;
3617 OwningPtr<llvm::MemoryBuffer> Buffer;
3618 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3619 if (!Buffer) {
3620 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3621 return std::string();
3622 }
3623
3624 // Initialize the stream
3625 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003626 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3628 (const unsigned char *)Buffer->getBufferEnd());
3629 Stream.init(StreamFile);
3630
3631 // Sniff for the signature.
3632 if (Stream.Read(8) != 'C' ||
3633 Stream.Read(8) != 'P' ||
3634 Stream.Read(8) != 'C' ||
3635 Stream.Read(8) != 'H') {
3636 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3637 return std::string();
3638 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003639
Chris Lattnere7b154b2013-01-19 21:39:22 +00003640 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003641 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003642 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3643 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003644 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003645
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003646 // Scan for ORIGINAL_FILE inside the control block.
3647 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003648 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003649 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003650 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3651 return std::string();
3652
3653 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3654 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3655 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003656 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003659 StringRef Blob;
3660 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3661 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003663}
3664
3665namespace {
3666 class SimplePCHValidator : public ASTReaderListener {
3667 const LangOptions &ExistingLangOpts;
3668 const TargetOptions &ExistingTargetOpts;
3669 const PreprocessorOptions &ExistingPPOpts;
3670 FileManager &FileMgr;
3671
3672 public:
3673 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3674 const TargetOptions &ExistingTargetOpts,
3675 const PreprocessorOptions &ExistingPPOpts,
3676 FileManager &FileMgr)
3677 : ExistingLangOpts(ExistingLangOpts),
3678 ExistingTargetOpts(ExistingTargetOpts),
3679 ExistingPPOpts(ExistingPPOpts),
3680 FileMgr(FileMgr)
3681 {
3682 }
3683
3684 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3685 bool Complain) {
3686 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3687 }
3688 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3689 bool Complain) {
3690 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3691 }
3692 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3693 bool Complain,
3694 std::string &SuggestedPredefines) {
3695 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003696 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 }
3698 };
3699}
3700
3701bool ASTReader::readASTFileControlBlock(StringRef Filename,
3702 FileManager &FileMgr,
3703 ASTReaderListener &Listener) {
3704 // Open the AST file.
3705 std::string ErrStr;
3706 OwningPtr<llvm::MemoryBuffer> Buffer;
3707 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3708 if (!Buffer) {
3709 return true;
3710 }
3711
3712 // Initialize the stream
3713 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003714 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3716 (const unsigned char *)Buffer->getBufferEnd());
3717 Stream.init(StreamFile);
3718
3719 // Sniff for the signature.
3720 if (Stream.Read(8) != 'C' ||
3721 Stream.Read(8) != 'P' ||
3722 Stream.Read(8) != 'C' ||
3723 Stream.Read(8) != 'H') {
3724 return true;
3725 }
3726
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003727 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003728 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003729 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003730
3731 bool NeedsInputFiles = Listener.needsInputFileVisitation();
3732 BitstreamCursor InputFilesCursor;
3733 if (NeedsInputFiles) {
3734 InputFilesCursor = Stream;
3735 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3736 return true;
3737
3738 // Read the abbreviations
3739 while (true) {
3740 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3741 unsigned Code = InputFilesCursor.ReadCode();
3742
3743 // We expect all abbrevs to be at the start of the block.
3744 if (Code != llvm::bitc::DEFINE_ABBREV) {
3745 InputFilesCursor.JumpToBit(Offset);
3746 break;
3747 }
3748 InputFilesCursor.ReadAbbrevRecord();
3749 }
3750 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003751
3752 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003754 while (1) {
3755 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3756 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3757 return false;
3758
3759 if (Entry.Kind != llvm::BitstreamEntry::Record)
3760 return true;
3761
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003763 StringRef Blob;
3764 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003765 switch ((ControlRecordTypes)RecCode) {
3766 case METADATA: {
3767 if (Record[0] != VERSION_MAJOR)
3768 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003769
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003770 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003771 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003772
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003773 break;
3774 }
3775 case LANGUAGE_OPTIONS:
3776 if (ParseLanguageOptions(Record, false, Listener))
3777 return true;
3778 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003779
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003780 case TARGET_OPTIONS:
3781 if (ParseTargetOptions(Record, false, Listener))
3782 return true;
3783 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003784
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003785 case DIAGNOSTIC_OPTIONS:
3786 if (ParseDiagnosticOptions(Record, false, Listener))
3787 return true;
3788 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003789
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003790 case FILE_SYSTEM_OPTIONS:
3791 if (ParseFileSystemOptions(Record, false, Listener))
3792 return true;
3793 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003794
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003795 case HEADER_SEARCH_OPTIONS:
3796 if (ParseHeaderSearchOptions(Record, false, Listener))
3797 return true;
3798 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003799
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003800 case PREPROCESSOR_OPTIONS: {
3801 std::string IgnoredSuggestedPredefines;
3802 if (ParsePreprocessorOptions(Record, false, Listener,
3803 IgnoredSuggestedPredefines))
3804 return true;
3805 break;
3806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003807
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003808 case INPUT_FILE_OFFSETS: {
3809 if (!NeedsInputFiles)
3810 break;
3811
3812 unsigned NumInputFiles = Record[0];
3813 unsigned NumUserFiles = Record[1];
3814 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3815 for (unsigned I = 0; I != NumInputFiles; ++I) {
3816 // Go find this input file.
3817 bool isSystemFile = I >= NumUserFiles;
3818 BitstreamCursor &Cursor = InputFilesCursor;
3819 SavedStreamPosition SavedPosition(Cursor);
3820 Cursor.JumpToBit(InputFileOffs[I]);
3821
3822 unsigned Code = Cursor.ReadCode();
3823 RecordData Record;
3824 StringRef Blob;
3825 bool shouldContinue = false;
3826 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3827 case INPUT_FILE:
3828 shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3829 break;
3830 }
3831 if (!shouldContinue)
3832 break;
3833 }
3834 break;
3835 }
3836
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003837 default:
3838 // No other validation to perform.
3839 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003840 }
3841 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003842}
3843
3844
3845bool ASTReader::isAcceptableASTFile(StringRef Filename,
3846 FileManager &FileMgr,
3847 const LangOptions &LangOpts,
3848 const TargetOptions &TargetOpts,
3849 const PreprocessorOptions &PPOpts) {
3850 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3851 return !readASTFileControlBlock(Filename, FileMgr, validator);
3852}
3853
3854bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3855 // Enter the submodule block.
3856 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3857 Error("malformed submodule block record in AST file");
3858 return true;
3859 }
3860
3861 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3862 bool First = true;
3863 Module *CurrentModule = 0;
3864 RecordData Record;
3865 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003866 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3867
3868 switch (Entry.Kind) {
3869 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3870 case llvm::BitstreamEntry::Error:
3871 Error("malformed block record in AST file");
3872 return true;
3873 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003875 case llvm::BitstreamEntry::Record:
3876 // The interesting case.
3877 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003881 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003883 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 default: // Default behavior: ignore.
3885 break;
3886
3887 case SUBMODULE_DEFINITION: {
3888 if (First) {
3889 Error("missing submodule metadata record at beginning of block");
3890 return true;
3891 }
3892
Douglas Gregor8d932422013-03-20 03:59:18 +00003893 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 Error("malformed module definition");
3895 return true;
3896 }
3897
Chris Lattner0e6c9402013-01-20 02:38:54 +00003898 StringRef Name = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3900 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3901 bool IsFramework = Record[2];
3902 bool IsExplicit = Record[3];
3903 bool IsSystem = Record[4];
3904 bool InferSubmodules = Record[5];
3905 bool InferExplicitSubmodules = Record[6];
3906 bool InferExportWildcard = Record[7];
Douglas Gregor8d932422013-03-20 03:59:18 +00003907 bool ConfigMacrosExhaustive = Record[8];
3908
Guy Benyei11169dd2012-12-18 14:30:41 +00003909 Module *ParentModule = 0;
3910 if (Parent)
3911 ParentModule = getSubmodule(Parent);
3912
3913 // Retrieve this (sub)module from the module map, creating it if
3914 // necessary.
3915 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3916 IsFramework,
3917 IsExplicit).first;
3918 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3919 if (GlobalIndex >= SubmodulesLoaded.size() ||
3920 SubmodulesLoaded[GlobalIndex]) {
3921 Error("too many submodules");
3922 return true;
3923 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003924
Douglas Gregor7029ce12013-03-19 00:28:20 +00003925 if (!ParentModule) {
3926 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
3927 if (CurFile != F.File) {
3928 if (!Diags.isDiagnosticInFlight()) {
3929 Diag(diag::err_module_file_conflict)
3930 << CurrentModule->getTopLevelModuleName()
3931 << CurFile->getName()
3932 << F.File->getName();
3933 }
3934 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003935 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003936 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003937
3938 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00003939 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00003940
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 CurrentModule->IsFromModuleFile = true;
3942 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3943 CurrentModule->InferSubmodules = InferSubmodules;
3944 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3945 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00003946 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 if (DeserializationListener)
3948 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3949
3950 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003951
Douglas Gregorfb912652013-03-20 21:10:35 +00003952 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003953 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00003954 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00003955 CurrentModule->UnresolvedConflicts.clear();
3956 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00003957 break;
3958 }
3959
3960 case SUBMODULE_UMBRELLA_HEADER: {
3961 if (First) {
3962 Error("missing submodule metadata record at beginning of block");
3963 return true;
3964 }
3965
3966 if (!CurrentModule)
3967 break;
3968
Chris Lattner0e6c9402013-01-20 02:38:54 +00003969 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 if (!CurrentModule->getUmbrellaHeader())
3971 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3972 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3973 Error("mismatched umbrella headers in submodule");
3974 return true;
3975 }
3976 }
3977 break;
3978 }
3979
3980 case SUBMODULE_HEADER: {
3981 if (First) {
3982 Error("missing submodule metadata record at beginning of block");
3983 return true;
3984 }
3985
3986 if (!CurrentModule)
3987 break;
3988
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00003989 // We lazily associate headers with their modules via the HeaderInfoTable.
3990 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
3991 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 break;
3993 }
3994
3995 case SUBMODULE_EXCLUDED_HEADER: {
3996 if (First) {
3997 Error("missing submodule metadata record at beginning of block");
3998 return true;
3999 }
4000
4001 if (!CurrentModule)
4002 break;
4003
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004004 // We lazily associate headers with their modules via the HeaderInfoTable.
4005 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4006 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 break;
4008 }
4009
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004010 case SUBMODULE_PRIVATE_HEADER: {
4011 if (First) {
4012 Error("missing submodule metadata record at beginning of block");
4013 return true;
4014 }
4015
4016 if (!CurrentModule)
4017 break;
4018
4019 // We lazily associate headers with their modules via the HeaderInfoTable.
4020 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4021 // of complete filenames or remove it entirely.
4022 break;
4023 }
4024
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 case SUBMODULE_TOPHEADER: {
4026 if (First) {
4027 Error("missing submodule metadata record at beginning of block");
4028 return true;
4029 }
4030
4031 if (!CurrentModule)
4032 break;
4033
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004034 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 break;
4036 }
4037
4038 case SUBMODULE_UMBRELLA_DIR: {
4039 if (First) {
4040 Error("missing submodule metadata record at beginning of block");
4041 return true;
4042 }
4043
4044 if (!CurrentModule)
4045 break;
4046
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004048 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 if (!CurrentModule->getUmbrellaDir())
4050 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4051 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4052 Error("mismatched umbrella directories in submodule");
4053 return true;
4054 }
4055 }
4056 break;
4057 }
4058
4059 case SUBMODULE_METADATA: {
4060 if (!First) {
4061 Error("submodule metadata record not at beginning of block");
4062 return true;
4063 }
4064 First = false;
4065
4066 F.BaseSubmoduleID = getTotalNumSubmodules();
4067 F.LocalNumSubmodules = Record[0];
4068 unsigned LocalBaseSubmoduleID = Record[1];
4069 if (F.LocalNumSubmodules > 0) {
4070 // Introduce the global -> local mapping for submodules within this
4071 // module.
4072 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4073
4074 // Introduce the local -> global mapping for submodules within this
4075 // module.
4076 F.SubmoduleRemap.insertOrReplace(
4077 std::make_pair(LocalBaseSubmoduleID,
4078 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4079
4080 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4081 }
4082 break;
4083 }
4084
4085 case SUBMODULE_IMPORTS: {
4086 if (First) {
4087 Error("missing submodule metadata record at beginning of block");
4088 return true;
4089 }
4090
4091 if (!CurrentModule)
4092 break;
4093
4094 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004095 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 Unresolved.File = &F;
4097 Unresolved.Mod = CurrentModule;
4098 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004099 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004101 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004102 }
4103 break;
4104 }
4105
4106 case SUBMODULE_EXPORTS: {
4107 if (First) {
4108 Error("missing submodule metadata record at beginning of block");
4109 return true;
4110 }
4111
4112 if (!CurrentModule)
4113 break;
4114
4115 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004116 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 Unresolved.File = &F;
4118 Unresolved.Mod = CurrentModule;
4119 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004120 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004122 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 }
4124
4125 // Once we've loaded the set of exports, there's no reason to keep
4126 // the parsed, unresolved exports around.
4127 CurrentModule->UnresolvedExports.clear();
4128 break;
4129 }
4130 case SUBMODULE_REQUIRES: {
4131 if (First) {
4132 Error("missing submodule metadata record at beginning of block");
4133 return true;
4134 }
4135
4136 if (!CurrentModule)
4137 break;
4138
Richard Smitha3feee22013-10-28 22:18:19 +00004139 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 Context.getTargetInfo());
4141 break;
4142 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004143
4144 case SUBMODULE_LINK_LIBRARY:
4145 if (First) {
4146 Error("missing submodule metadata record at beginning of block");
4147 return true;
4148 }
4149
4150 if (!CurrentModule)
4151 break;
4152
4153 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004154 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004155 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004156
4157 case SUBMODULE_CONFIG_MACRO:
4158 if (First) {
4159 Error("missing submodule metadata record at beginning of block");
4160 return true;
4161 }
4162
4163 if (!CurrentModule)
4164 break;
4165
4166 CurrentModule->ConfigMacros.push_back(Blob.str());
4167 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004168
4169 case SUBMODULE_CONFLICT: {
4170 if (First) {
4171 Error("missing submodule metadata record at beginning of block");
4172 return true;
4173 }
4174
4175 if (!CurrentModule)
4176 break;
4177
4178 UnresolvedModuleRef Unresolved;
4179 Unresolved.File = &F;
4180 Unresolved.Mod = CurrentModule;
4181 Unresolved.ID = Record[0];
4182 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4183 Unresolved.IsWildcard = false;
4184 Unresolved.String = Blob;
4185 UnresolvedModuleRefs.push_back(Unresolved);
4186 break;
4187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004188 }
4189 }
4190}
4191
4192/// \brief Parse the record that corresponds to a LangOptions data
4193/// structure.
4194///
4195/// This routine parses the language options from the AST file and then gives
4196/// them to the AST listener if one is set.
4197///
4198/// \returns true if the listener deems the file unacceptable, false otherwise.
4199bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4200 bool Complain,
4201 ASTReaderListener &Listener) {
4202 LangOptions LangOpts;
4203 unsigned Idx = 0;
4204#define LANGOPT(Name, Bits, Default, Description) \
4205 LangOpts.Name = Record[Idx++];
4206#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4207 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4208#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004209#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4210#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
4212 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4213 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4214 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4215
4216 unsigned Length = Record[Idx++];
4217 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4218 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004219
4220 Idx += Length;
4221
4222 // Comment options.
4223 for (unsigned N = Record[Idx++]; N; --N) {
4224 LangOpts.CommentOpts.BlockCommandNames.push_back(
4225 ReadString(Record, Idx));
4226 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004227 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004228
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 return Listener.ReadLanguageOptions(LangOpts, Complain);
4230}
4231
4232bool ASTReader::ParseTargetOptions(const RecordData &Record,
4233 bool Complain,
4234 ASTReaderListener &Listener) {
4235 unsigned Idx = 0;
4236 TargetOptions TargetOpts;
4237 TargetOpts.Triple = ReadString(Record, Idx);
4238 TargetOpts.CPU = ReadString(Record, Idx);
4239 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4241 for (unsigned N = Record[Idx++]; N; --N) {
4242 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4243 }
4244 for (unsigned N = Record[Idx++]; N; --N) {
4245 TargetOpts.Features.push_back(ReadString(Record, Idx));
4246 }
4247
4248 return Listener.ReadTargetOptions(TargetOpts, Complain);
4249}
4250
4251bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4252 ASTReaderListener &Listener) {
4253 DiagnosticOptions DiagOpts;
4254 unsigned Idx = 0;
4255#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4256#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4257 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4258#include "clang/Basic/DiagnosticOptions.def"
4259
4260 for (unsigned N = Record[Idx++]; N; --N) {
4261 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4262 }
4263
4264 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4265}
4266
4267bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4268 ASTReaderListener &Listener) {
4269 FileSystemOptions FSOpts;
4270 unsigned Idx = 0;
4271 FSOpts.WorkingDir = ReadString(Record, Idx);
4272 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4273}
4274
4275bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4276 bool Complain,
4277 ASTReaderListener &Listener) {
4278 HeaderSearchOptions HSOpts;
4279 unsigned Idx = 0;
4280 HSOpts.Sysroot = ReadString(Record, Idx);
4281
4282 // Include entries.
4283 for (unsigned N = Record[Idx++]; N; --N) {
4284 std::string Path = ReadString(Record, Idx);
4285 frontend::IncludeDirGroup Group
4286 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 bool IsFramework = Record[Idx++];
4288 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004290 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 }
4292
4293 // System header prefixes.
4294 for (unsigned N = Record[Idx++]; N; --N) {
4295 std::string Prefix = ReadString(Record, Idx);
4296 bool IsSystemHeader = Record[Idx++];
4297 HSOpts.SystemHeaderPrefixes.push_back(
4298 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4299 }
4300
4301 HSOpts.ResourceDir = ReadString(Record, Idx);
4302 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004303 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 HSOpts.DisableModuleHash = Record[Idx++];
4305 HSOpts.UseBuiltinIncludes = Record[Idx++];
4306 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4307 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4308 HSOpts.UseLibcxx = Record[Idx++];
4309
4310 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4311}
4312
4313bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4314 bool Complain,
4315 ASTReaderListener &Listener,
4316 std::string &SuggestedPredefines) {
4317 PreprocessorOptions PPOpts;
4318 unsigned Idx = 0;
4319
4320 // Macro definitions/undefs
4321 for (unsigned N = Record[Idx++]; N; --N) {
4322 std::string Macro = ReadString(Record, Idx);
4323 bool IsUndef = Record[Idx++];
4324 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4325 }
4326
4327 // Includes
4328 for (unsigned N = Record[Idx++]; N; --N) {
4329 PPOpts.Includes.push_back(ReadString(Record, Idx));
4330 }
4331
4332 // Macro Includes
4333 for (unsigned N = Record[Idx++]; N; --N) {
4334 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4335 }
4336
4337 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004338 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4340 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4341 PPOpts.ObjCXXARCStandardLibrary =
4342 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4343 SuggestedPredefines.clear();
4344 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4345 SuggestedPredefines);
4346}
4347
4348std::pair<ModuleFile *, unsigned>
4349ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4350 GlobalPreprocessedEntityMapType::iterator
4351 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4352 assert(I != GlobalPreprocessedEntityMap.end() &&
4353 "Corrupted global preprocessed entity map");
4354 ModuleFile *M = I->second;
4355 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4356 return std::make_pair(M, LocalIndex);
4357}
4358
4359std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4360ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4361 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4362 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4363 Mod.NumPreprocessedEntities);
4364
4365 return std::make_pair(PreprocessingRecord::iterator(),
4366 PreprocessingRecord::iterator());
4367}
4368
4369std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4370ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4371 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4372 ModuleDeclIterator(this, &Mod,
4373 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4374}
4375
4376PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4377 PreprocessedEntityID PPID = Index+1;
4378 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4379 ModuleFile &M = *PPInfo.first;
4380 unsigned LocalIndex = PPInfo.second;
4381 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4382
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 if (!PP.getPreprocessingRecord()) {
4384 Error("no preprocessing record");
4385 return 0;
4386 }
4387
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004388 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4389 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4390
4391 llvm::BitstreamEntry Entry =
4392 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4393 if (Entry.Kind != llvm::BitstreamEntry::Record)
4394 return 0;
4395
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 // Read the record.
4397 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4398 ReadSourceLocation(M, PPOffs.End));
4399 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004400 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 RecordData Record;
4402 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004403 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4404 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 switch (RecType) {
4406 case PPD_MACRO_EXPANSION: {
4407 bool isBuiltin = Record[0];
4408 IdentifierInfo *Name = 0;
4409 MacroDefinition *Def = 0;
4410 if (isBuiltin)
4411 Name = getLocalIdentifier(M, Record[1]);
4412 else {
4413 PreprocessedEntityID
4414 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4415 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4416 }
4417
4418 MacroExpansion *ME;
4419 if (isBuiltin)
4420 ME = new (PPRec) MacroExpansion(Name, Range);
4421 else
4422 ME = new (PPRec) MacroExpansion(Def, Range);
4423
4424 return ME;
4425 }
4426
4427 case PPD_MACRO_DEFINITION: {
4428 // Decode the identifier info and then check again; if the macro is
4429 // still defined and associated with the identifier,
4430 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4431 MacroDefinition *MD
4432 = new (PPRec) MacroDefinition(II, Range);
4433
4434 if (DeserializationListener)
4435 DeserializationListener->MacroDefinitionRead(PPID, MD);
4436
4437 return MD;
4438 }
4439
4440 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004441 const char *FullFileNameStart = Blob.data() + Record[0];
4442 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 const FileEntry *File = 0;
4444 if (!FullFileName.empty())
4445 File = PP.getFileManager().getFile(FullFileName);
4446
4447 // FIXME: Stable encoding
4448 InclusionDirective::InclusionKind Kind
4449 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4450 InclusionDirective *ID
4451 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004452 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 Record[1], Record[3],
4454 File,
4455 Range);
4456 return ID;
4457 }
4458 }
4459
4460 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4461}
4462
4463/// \brief \arg SLocMapI points at a chunk of a module that contains no
4464/// preprocessed entities or the entities it contains are not the ones we are
4465/// looking for. Find the next module that contains entities and return the ID
4466/// of the first entry.
4467PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4468 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4469 ++SLocMapI;
4470 for (GlobalSLocOffsetMapType::const_iterator
4471 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4472 ModuleFile &M = *SLocMapI->second;
4473 if (M.NumPreprocessedEntities)
4474 return M.BasePreprocessedEntityID;
4475 }
4476
4477 return getTotalNumPreprocessedEntities();
4478}
4479
4480namespace {
4481
4482template <unsigned PPEntityOffset::*PPLoc>
4483struct PPEntityComp {
4484 const ASTReader &Reader;
4485 ModuleFile &M;
4486
4487 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4488
4489 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4490 SourceLocation LHS = getLoc(L);
4491 SourceLocation RHS = getLoc(R);
4492 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4493 }
4494
4495 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4496 SourceLocation LHS = getLoc(L);
4497 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4498 }
4499
4500 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4501 SourceLocation RHS = getLoc(R);
4502 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4503 }
4504
4505 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4506 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4507 }
4508};
4509
4510}
4511
4512/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4513PreprocessedEntityID
4514ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4515 if (SourceMgr.isLocalSourceLocation(BLoc))
4516 return getTotalNumPreprocessedEntities();
4517
4518 GlobalSLocOffsetMapType::const_iterator
4519 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004520 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4522 "Corrupted global sloc offset map");
4523
4524 if (SLocMapI->second->NumPreprocessedEntities == 0)
4525 return findNextPreprocessedEntity(SLocMapI);
4526
4527 ModuleFile &M = *SLocMapI->second;
4528 typedef const PPEntityOffset *pp_iterator;
4529 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4530 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4531
4532 size_t Count = M.NumPreprocessedEntities;
4533 size_t Half;
4534 pp_iterator First = pp_begin;
4535 pp_iterator PPI;
4536
4537 // Do a binary search manually instead of using std::lower_bound because
4538 // The end locations of entities may be unordered (when a macro expansion
4539 // is inside another macro argument), but for this case it is not important
4540 // whether we get the first macro expansion or its containing macro.
4541 while (Count > 0) {
4542 Half = Count/2;
4543 PPI = First;
4544 std::advance(PPI, Half);
4545 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4546 BLoc)){
4547 First = PPI;
4548 ++First;
4549 Count = Count - Half - 1;
4550 } else
4551 Count = Half;
4552 }
4553
4554 if (PPI == pp_end)
4555 return findNextPreprocessedEntity(SLocMapI);
4556
4557 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4558}
4559
4560/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4561PreprocessedEntityID
4562ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4563 if (SourceMgr.isLocalSourceLocation(ELoc))
4564 return getTotalNumPreprocessedEntities();
4565
4566 GlobalSLocOffsetMapType::const_iterator
4567 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004568 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4570 "Corrupted global sloc offset map");
4571
4572 if (SLocMapI->second->NumPreprocessedEntities == 0)
4573 return findNextPreprocessedEntity(SLocMapI);
4574
4575 ModuleFile &M = *SLocMapI->second;
4576 typedef const PPEntityOffset *pp_iterator;
4577 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4578 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4579 pp_iterator PPI =
4580 std::upper_bound(pp_begin, pp_end, ELoc,
4581 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4582
4583 if (PPI == pp_end)
4584 return findNextPreprocessedEntity(SLocMapI);
4585
4586 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4587}
4588
4589/// \brief Returns a pair of [Begin, End) indices of preallocated
4590/// preprocessed entities that \arg Range encompasses.
4591std::pair<unsigned, unsigned>
4592 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4593 if (Range.isInvalid())
4594 return std::make_pair(0,0);
4595 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4596
4597 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4598 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4599 return std::make_pair(BeginID, EndID);
4600}
4601
4602/// \brief Optionally returns true or false if the preallocated preprocessed
4603/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004604Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 FileID FID) {
4606 if (FID.isInvalid())
4607 return false;
4608
4609 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4610 ModuleFile &M = *PPInfo.first;
4611 unsigned LocalIndex = PPInfo.second;
4612 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4613
4614 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4615 if (Loc.isInvalid())
4616 return false;
4617
4618 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4619 return true;
4620 else
4621 return false;
4622}
4623
4624namespace {
4625 /// \brief Visitor used to search for information about a header file.
4626 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 const FileEntry *FE;
4628
David Blaikie05785d12013-02-20 22:23:23 +00004629 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004630
4631 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004632 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4633 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004634
4635 static bool visit(ModuleFile &M, void *UserData) {
4636 HeaderFileInfoVisitor *This
4637 = static_cast<HeaderFileInfoVisitor *>(UserData);
4638
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 HeaderFileInfoLookupTable *Table
4640 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4641 if (!Table)
4642 return false;
4643
4644 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004645 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 if (Pos == Table->end())
4647 return false;
4648
4649 This->HFI = *Pos;
4650 return true;
4651 }
4652
David Blaikie05785d12013-02-20 22:23:23 +00004653 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 };
4655}
4656
4657HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004658 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004660 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004662
4663 return HeaderFileInfo();
4664}
4665
4666void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4667 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004668 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4670 ModuleFile &F = *(*I);
4671 unsigned Idx = 0;
4672 DiagStates.clear();
4673 assert(!Diag.DiagStates.empty());
4674 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4675 while (Idx < F.PragmaDiagMappings.size()) {
4676 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4677 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4678 if (DiagStateID != 0) {
4679 Diag.DiagStatePoints.push_back(
4680 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4681 FullSourceLoc(Loc, SourceMgr)));
4682 continue;
4683 }
4684
4685 assert(DiagStateID == 0);
4686 // A new DiagState was created here.
4687 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4688 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4689 DiagStates.push_back(NewState);
4690 Diag.DiagStatePoints.push_back(
4691 DiagnosticsEngine::DiagStatePoint(NewState,
4692 FullSourceLoc(Loc, SourceMgr)));
4693 while (1) {
4694 assert(Idx < F.PragmaDiagMappings.size() &&
4695 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4696 if (Idx >= F.PragmaDiagMappings.size()) {
4697 break; // Something is messed up but at least avoid infinite loop in
4698 // release build.
4699 }
4700 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4701 if (DiagID == (unsigned)-1) {
4702 break; // no more diag/map pairs for this location.
4703 }
4704 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4705 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4706 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4707 }
4708 }
4709 }
4710}
4711
4712/// \brief Get the correct cursor and offset for loading a type.
4713ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4714 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4715 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4716 ModuleFile *M = I->second;
4717 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4718}
4719
4720/// \brief Read and return the type with the given index..
4721///
4722/// The index is the type ID, shifted and minus the number of predefs. This
4723/// routine actually reads the record corresponding to the type at the given
4724/// location. It is a helper routine for GetType, which deals with reading type
4725/// IDs.
4726QualType ASTReader::readTypeRecord(unsigned Index) {
4727 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004728 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004729
4730 // Keep track of where we are in the stream, then jump back there
4731 // after reading this type.
4732 SavedStreamPosition SavedPosition(DeclsCursor);
4733
4734 ReadingKindTracker ReadingKind(Read_Type, *this);
4735
4736 // Note that we are loading a type record.
4737 Deserializing AType(this);
4738
4739 unsigned Idx = 0;
4740 DeclsCursor.JumpToBit(Loc.Offset);
4741 RecordData Record;
4742 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004743 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 case TYPE_EXT_QUAL: {
4745 if (Record.size() != 2) {
4746 Error("Incorrect encoding of extended qualifier type");
4747 return QualType();
4748 }
4749 QualType Base = readType(*Loc.F, Record, Idx);
4750 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4751 return Context.getQualifiedType(Base, Quals);
4752 }
4753
4754 case TYPE_COMPLEX: {
4755 if (Record.size() != 1) {
4756 Error("Incorrect encoding of complex type");
4757 return QualType();
4758 }
4759 QualType ElemType = readType(*Loc.F, Record, Idx);
4760 return Context.getComplexType(ElemType);
4761 }
4762
4763 case TYPE_POINTER: {
4764 if (Record.size() != 1) {
4765 Error("Incorrect encoding of pointer type");
4766 return QualType();
4767 }
4768 QualType PointeeType = readType(*Loc.F, Record, Idx);
4769 return Context.getPointerType(PointeeType);
4770 }
4771
Reid Kleckner8a365022013-06-24 17:51:48 +00004772 case TYPE_DECAYED: {
4773 if (Record.size() != 1) {
4774 Error("Incorrect encoding of decayed type");
4775 return QualType();
4776 }
4777 QualType OriginalType = readType(*Loc.F, Record, Idx);
4778 QualType DT = Context.getAdjustedParameterType(OriginalType);
4779 if (!isa<DecayedType>(DT))
4780 Error("Decayed type does not decay");
4781 return DT;
4782 }
4783
Reid Kleckner0503a872013-12-05 01:23:43 +00004784 case TYPE_ADJUSTED: {
4785 if (Record.size() != 2) {
4786 Error("Incorrect encoding of adjusted type");
4787 return QualType();
4788 }
4789 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4790 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4791 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4792 }
4793
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 case TYPE_BLOCK_POINTER: {
4795 if (Record.size() != 1) {
4796 Error("Incorrect encoding of block pointer type");
4797 return QualType();
4798 }
4799 QualType PointeeType = readType(*Loc.F, Record, Idx);
4800 return Context.getBlockPointerType(PointeeType);
4801 }
4802
4803 case TYPE_LVALUE_REFERENCE: {
4804 if (Record.size() != 2) {
4805 Error("Incorrect encoding of lvalue reference type");
4806 return QualType();
4807 }
4808 QualType PointeeType = readType(*Loc.F, Record, Idx);
4809 return Context.getLValueReferenceType(PointeeType, Record[1]);
4810 }
4811
4812 case TYPE_RVALUE_REFERENCE: {
4813 if (Record.size() != 1) {
4814 Error("Incorrect encoding of rvalue reference type");
4815 return QualType();
4816 }
4817 QualType PointeeType = readType(*Loc.F, Record, Idx);
4818 return Context.getRValueReferenceType(PointeeType);
4819 }
4820
4821 case TYPE_MEMBER_POINTER: {
4822 if (Record.size() != 2) {
4823 Error("Incorrect encoding of member pointer type");
4824 return QualType();
4825 }
4826 QualType PointeeType = readType(*Loc.F, Record, Idx);
4827 QualType ClassType = readType(*Loc.F, Record, Idx);
4828 if (PointeeType.isNull() || ClassType.isNull())
4829 return QualType();
4830
4831 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4832 }
4833
4834 case TYPE_CONSTANT_ARRAY: {
4835 QualType ElementType = readType(*Loc.F, Record, Idx);
4836 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4837 unsigned IndexTypeQuals = Record[2];
4838 unsigned Idx = 3;
4839 llvm::APInt Size = ReadAPInt(Record, Idx);
4840 return Context.getConstantArrayType(ElementType, Size,
4841 ASM, IndexTypeQuals);
4842 }
4843
4844 case TYPE_INCOMPLETE_ARRAY: {
4845 QualType ElementType = readType(*Loc.F, Record, Idx);
4846 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4847 unsigned IndexTypeQuals = Record[2];
4848 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4849 }
4850
4851 case TYPE_VARIABLE_ARRAY: {
4852 QualType ElementType = readType(*Loc.F, Record, Idx);
4853 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4854 unsigned IndexTypeQuals = Record[2];
4855 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4856 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4857 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4858 ASM, IndexTypeQuals,
4859 SourceRange(LBLoc, RBLoc));
4860 }
4861
4862 case TYPE_VECTOR: {
4863 if (Record.size() != 3) {
4864 Error("incorrect encoding of vector type in AST file");
4865 return QualType();
4866 }
4867
4868 QualType ElementType = readType(*Loc.F, Record, Idx);
4869 unsigned NumElements = Record[1];
4870 unsigned VecKind = Record[2];
4871 return Context.getVectorType(ElementType, NumElements,
4872 (VectorType::VectorKind)VecKind);
4873 }
4874
4875 case TYPE_EXT_VECTOR: {
4876 if (Record.size() != 3) {
4877 Error("incorrect encoding of extended vector type in AST file");
4878 return QualType();
4879 }
4880
4881 QualType ElementType = readType(*Loc.F, Record, Idx);
4882 unsigned NumElements = Record[1];
4883 return Context.getExtVectorType(ElementType, NumElements);
4884 }
4885
4886 case TYPE_FUNCTION_NO_PROTO: {
4887 if (Record.size() != 6) {
4888 Error("incorrect encoding of no-proto function type");
4889 return QualType();
4890 }
4891 QualType ResultType = readType(*Loc.F, Record, Idx);
4892 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4893 (CallingConv)Record[4], Record[5]);
4894 return Context.getFunctionNoProtoType(ResultType, Info);
4895 }
4896
4897 case TYPE_FUNCTION_PROTO: {
4898 QualType ResultType = readType(*Loc.F, Record, Idx);
4899
4900 FunctionProtoType::ExtProtoInfo EPI;
4901 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4902 /*hasregparm*/ Record[2],
4903 /*regparm*/ Record[3],
4904 static_cast<CallingConv>(Record[4]),
4905 /*produces*/ Record[5]);
4906
4907 unsigned Idx = 6;
4908 unsigned NumParams = Record[Idx++];
4909 SmallVector<QualType, 16> ParamTypes;
4910 for (unsigned I = 0; I != NumParams; ++I)
4911 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4912
4913 EPI.Variadic = Record[Idx++];
4914 EPI.HasTrailingReturn = Record[Idx++];
4915 EPI.TypeQuals = Record[Idx++];
4916 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4917 ExceptionSpecificationType EST =
4918 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4919 EPI.ExceptionSpecType = EST;
4920 SmallVector<QualType, 2> Exceptions;
4921 if (EST == EST_Dynamic) {
4922 EPI.NumExceptions = Record[Idx++];
4923 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4924 Exceptions.push_back(readType(*Loc.F, Record, Idx));
4925 EPI.Exceptions = Exceptions.data();
4926 } else if (EST == EST_ComputedNoexcept) {
4927 EPI.NoexceptExpr = ReadExpr(*Loc.F);
4928 } else if (EST == EST_Uninstantiated) {
4929 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4930 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4931 } else if (EST == EST_Unevaluated) {
4932 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4933 }
Jordan Rose5c382722013-03-08 21:51:21 +00004934 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 }
4936
4937 case TYPE_UNRESOLVED_USING: {
4938 unsigned Idx = 0;
4939 return Context.getTypeDeclType(
4940 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4941 }
4942
4943 case TYPE_TYPEDEF: {
4944 if (Record.size() != 2) {
4945 Error("incorrect encoding of typedef type");
4946 return QualType();
4947 }
4948 unsigned Idx = 0;
4949 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4950 QualType Canonical = readType(*Loc.F, Record, Idx);
4951 if (!Canonical.isNull())
4952 Canonical = Context.getCanonicalType(Canonical);
4953 return Context.getTypedefType(Decl, Canonical);
4954 }
4955
4956 case TYPE_TYPEOF_EXPR:
4957 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4958
4959 case TYPE_TYPEOF: {
4960 if (Record.size() != 1) {
4961 Error("incorrect encoding of typeof(type) in AST file");
4962 return QualType();
4963 }
4964 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4965 return Context.getTypeOfType(UnderlyingType);
4966 }
4967
4968 case TYPE_DECLTYPE: {
4969 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4970 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4971 }
4972
4973 case TYPE_UNARY_TRANSFORM: {
4974 QualType BaseType = readType(*Loc.F, Record, Idx);
4975 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4976 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4977 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4978 }
4979
Richard Smith74aeef52013-04-26 16:15:35 +00004980 case TYPE_AUTO: {
4981 QualType Deduced = readType(*Loc.F, Record, Idx);
4982 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00004983 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004984 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00004985 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004986
4987 case TYPE_RECORD: {
4988 if (Record.size() != 2) {
4989 Error("incorrect encoding of record type");
4990 return QualType();
4991 }
4992 unsigned Idx = 0;
4993 bool IsDependent = Record[Idx++];
4994 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4995 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4996 QualType T = Context.getRecordType(RD);
4997 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4998 return T;
4999 }
5000
5001 case TYPE_ENUM: {
5002 if (Record.size() != 2) {
5003 Error("incorrect encoding of enum type");
5004 return QualType();
5005 }
5006 unsigned Idx = 0;
5007 bool IsDependent = Record[Idx++];
5008 QualType T
5009 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5010 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5011 return T;
5012 }
5013
5014 case TYPE_ATTRIBUTED: {
5015 if (Record.size() != 3) {
5016 Error("incorrect encoding of attributed type");
5017 return QualType();
5018 }
5019 QualType modifiedType = readType(*Loc.F, Record, Idx);
5020 QualType equivalentType = readType(*Loc.F, Record, Idx);
5021 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5022 return Context.getAttributedType(kind, modifiedType, equivalentType);
5023 }
5024
5025 case TYPE_PAREN: {
5026 if (Record.size() != 1) {
5027 Error("incorrect encoding of paren type");
5028 return QualType();
5029 }
5030 QualType InnerType = readType(*Loc.F, Record, Idx);
5031 return Context.getParenType(InnerType);
5032 }
5033
5034 case TYPE_PACK_EXPANSION: {
5035 if (Record.size() != 2) {
5036 Error("incorrect encoding of pack expansion type");
5037 return QualType();
5038 }
5039 QualType Pattern = readType(*Loc.F, Record, Idx);
5040 if (Pattern.isNull())
5041 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005042 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 if (Record[1])
5044 NumExpansions = Record[1] - 1;
5045 return Context.getPackExpansionType(Pattern, NumExpansions);
5046 }
5047
5048 case TYPE_ELABORATED: {
5049 unsigned Idx = 0;
5050 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5051 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5052 QualType NamedType = readType(*Loc.F, Record, Idx);
5053 return Context.getElaboratedType(Keyword, NNS, NamedType);
5054 }
5055
5056 case TYPE_OBJC_INTERFACE: {
5057 unsigned Idx = 0;
5058 ObjCInterfaceDecl *ItfD
5059 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5060 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5061 }
5062
5063 case TYPE_OBJC_OBJECT: {
5064 unsigned Idx = 0;
5065 QualType Base = readType(*Loc.F, Record, Idx);
5066 unsigned NumProtos = Record[Idx++];
5067 SmallVector<ObjCProtocolDecl*, 4> Protos;
5068 for (unsigned I = 0; I != NumProtos; ++I)
5069 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5070 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5071 }
5072
5073 case TYPE_OBJC_OBJECT_POINTER: {
5074 unsigned Idx = 0;
5075 QualType Pointee = readType(*Loc.F, Record, Idx);
5076 return Context.getObjCObjectPointerType(Pointee);
5077 }
5078
5079 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5080 unsigned Idx = 0;
5081 QualType Parm = readType(*Loc.F, Record, Idx);
5082 QualType Replacement = readType(*Loc.F, Record, Idx);
5083 return
5084 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
5085 Replacement);
5086 }
5087
5088 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5089 unsigned Idx = 0;
5090 QualType Parm = readType(*Loc.F, Record, Idx);
5091 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5092 return Context.getSubstTemplateTypeParmPackType(
5093 cast<TemplateTypeParmType>(Parm),
5094 ArgPack);
5095 }
5096
5097 case TYPE_INJECTED_CLASS_NAME: {
5098 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5099 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5100 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5101 // for AST reading, too much interdependencies.
5102 return
5103 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5104 }
5105
5106 case TYPE_TEMPLATE_TYPE_PARM: {
5107 unsigned Idx = 0;
5108 unsigned Depth = Record[Idx++];
5109 unsigned Index = Record[Idx++];
5110 bool Pack = Record[Idx++];
5111 TemplateTypeParmDecl *D
5112 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5113 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5114 }
5115
5116 case TYPE_DEPENDENT_NAME: {
5117 unsigned Idx = 0;
5118 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5119 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5120 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5121 QualType Canon = readType(*Loc.F, Record, Idx);
5122 if (!Canon.isNull())
5123 Canon = Context.getCanonicalType(Canon);
5124 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5125 }
5126
5127 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5128 unsigned Idx = 0;
5129 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5130 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5131 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5132 unsigned NumArgs = Record[Idx++];
5133 SmallVector<TemplateArgument, 8> Args;
5134 Args.reserve(NumArgs);
5135 while (NumArgs--)
5136 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5137 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5138 Args.size(), Args.data());
5139 }
5140
5141 case TYPE_DEPENDENT_SIZED_ARRAY: {
5142 unsigned Idx = 0;
5143
5144 // ArrayType
5145 QualType ElementType = readType(*Loc.F, Record, Idx);
5146 ArrayType::ArraySizeModifier ASM
5147 = (ArrayType::ArraySizeModifier)Record[Idx++];
5148 unsigned IndexTypeQuals = Record[Idx++];
5149
5150 // DependentSizedArrayType
5151 Expr *NumElts = ReadExpr(*Loc.F);
5152 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5153
5154 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5155 IndexTypeQuals, Brackets);
5156 }
5157
5158 case TYPE_TEMPLATE_SPECIALIZATION: {
5159 unsigned Idx = 0;
5160 bool IsDependent = Record[Idx++];
5161 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5162 SmallVector<TemplateArgument, 8> Args;
5163 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5164 QualType Underlying = readType(*Loc.F, Record, Idx);
5165 QualType T;
5166 if (Underlying.isNull())
5167 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5168 Args.size());
5169 else
5170 T = Context.getTemplateSpecializationType(Name, Args.data(),
5171 Args.size(), Underlying);
5172 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5173 return T;
5174 }
5175
5176 case TYPE_ATOMIC: {
5177 if (Record.size() != 1) {
5178 Error("Incorrect encoding of atomic type");
5179 return QualType();
5180 }
5181 QualType ValueType = readType(*Loc.F, Record, Idx);
5182 return Context.getAtomicType(ValueType);
5183 }
5184 }
5185 llvm_unreachable("Invalid TypeCode!");
5186}
5187
5188class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5189 ASTReader &Reader;
5190 ModuleFile &F;
5191 const ASTReader::RecordData &Record;
5192 unsigned &Idx;
5193
5194 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5195 unsigned &I) {
5196 return Reader.ReadSourceLocation(F, R, I);
5197 }
5198
5199 template<typename T>
5200 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5201 return Reader.ReadDeclAs<T>(F, Record, Idx);
5202 }
5203
5204public:
5205 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5206 const ASTReader::RecordData &Record, unsigned &Idx)
5207 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5208 { }
5209
5210 // We want compile-time assurance that we've enumerated all of
5211 // these, so unfortunately we have to declare them first, then
5212 // define them out-of-line.
5213#define ABSTRACT_TYPELOC(CLASS, PARENT)
5214#define TYPELOC(CLASS, PARENT) \
5215 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5216#include "clang/AST/TypeLocNodes.def"
5217
5218 void VisitFunctionTypeLoc(FunctionTypeLoc);
5219 void VisitArrayTypeLoc(ArrayTypeLoc);
5220};
5221
5222void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5223 // nothing to do
5224}
5225void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5226 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5227 if (TL.needsExtraLocalData()) {
5228 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5229 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5230 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5231 TL.setModeAttr(Record[Idx++]);
5232 }
5233}
5234void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5235 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5236}
5237void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5238 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5239}
Reid Kleckner8a365022013-06-24 17:51:48 +00005240void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5241 // nothing to do
5242}
Reid Kleckner0503a872013-12-05 01:23:43 +00005243void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5244 // nothing to do
5245}
Guy Benyei11169dd2012-12-18 14:30:41 +00005246void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5247 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5248}
5249void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5250 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5251}
5252void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5253 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5254}
5255void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5256 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5257 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5258}
5259void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5260 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5261 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5262 if (Record[Idx++])
5263 TL.setSizeExpr(Reader.ReadExpr(F));
5264 else
5265 TL.setSizeExpr(0);
5266}
5267void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5268 VisitArrayTypeLoc(TL);
5269}
5270void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5271 VisitArrayTypeLoc(TL);
5272}
5273void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5274 VisitArrayTypeLoc(TL);
5275}
5276void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5277 DependentSizedArrayTypeLoc TL) {
5278 VisitArrayTypeLoc(TL);
5279}
5280void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5281 DependentSizedExtVectorTypeLoc TL) {
5282 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5283}
5284void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5285 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5286}
5287void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5288 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5289}
5290void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5291 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5292 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5293 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5294 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005295 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5296 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 }
5298}
5299void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5300 VisitFunctionTypeLoc(TL);
5301}
5302void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5303 VisitFunctionTypeLoc(TL);
5304}
5305void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5306 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5307}
5308void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5309 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5310}
5311void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5312 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5313 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5314 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5315}
5316void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5317 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5318 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5319 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5320 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5321}
5322void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5323 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5324}
5325void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5326 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5327 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5328 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5329 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5330}
5331void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5332 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5333}
5334void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5335 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5336}
5337void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5338 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5339}
5340void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5341 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5342 if (TL.hasAttrOperand()) {
5343 SourceRange range;
5344 range.setBegin(ReadSourceLocation(Record, Idx));
5345 range.setEnd(ReadSourceLocation(Record, Idx));
5346 TL.setAttrOperandParensRange(range);
5347 }
5348 if (TL.hasAttrExprOperand()) {
5349 if (Record[Idx++])
5350 TL.setAttrExprOperand(Reader.ReadExpr(F));
5351 else
5352 TL.setAttrExprOperand(0);
5353 } else if (TL.hasAttrEnumOperand())
5354 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5355}
5356void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5357 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5358}
5359void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5360 SubstTemplateTypeParmTypeLoc TL) {
5361 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5362}
5363void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5364 SubstTemplateTypeParmPackTypeLoc TL) {
5365 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5366}
5367void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5368 TemplateSpecializationTypeLoc TL) {
5369 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5370 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5371 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5372 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5373 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5374 TL.setArgLocInfo(i,
5375 Reader.GetTemplateArgumentLocInfo(F,
5376 TL.getTypePtr()->getArg(i).getKind(),
5377 Record, Idx));
5378}
5379void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5380 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5381 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5382}
5383void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5384 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5385 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5386}
5387void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5388 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5389}
5390void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5391 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5392 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5393 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5394}
5395void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5396 DependentTemplateSpecializationTypeLoc TL) {
5397 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5398 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5399 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5400 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5401 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5402 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5403 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5404 TL.setArgLocInfo(I,
5405 Reader.GetTemplateArgumentLocInfo(F,
5406 TL.getTypePtr()->getArg(I).getKind(),
5407 Record, Idx));
5408}
5409void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5410 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5411}
5412void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5413 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5414}
5415void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5416 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5417 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5418 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5419 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5420 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5421}
5422void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5423 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5424}
5425void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5426 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5427 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5428 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5429}
5430
5431TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5432 const RecordData &Record,
5433 unsigned &Idx) {
5434 QualType InfoTy = readType(F, Record, Idx);
5435 if (InfoTy.isNull())
5436 return 0;
5437
5438 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5439 TypeLocReader TLR(*this, F, Record, Idx);
5440 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5441 TLR.Visit(TL);
5442 return TInfo;
5443}
5444
5445QualType ASTReader::GetType(TypeID ID) {
5446 unsigned FastQuals = ID & Qualifiers::FastMask;
5447 unsigned Index = ID >> Qualifiers::FastWidth;
5448
5449 if (Index < NUM_PREDEF_TYPE_IDS) {
5450 QualType T;
5451 switch ((PredefinedTypeIDs)Index) {
5452 case PREDEF_TYPE_NULL_ID: return QualType();
5453 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5454 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5455
5456 case PREDEF_TYPE_CHAR_U_ID:
5457 case PREDEF_TYPE_CHAR_S_ID:
5458 // FIXME: Check that the signedness of CharTy is correct!
5459 T = Context.CharTy;
5460 break;
5461
5462 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5463 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5464 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5465 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5466 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5467 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5468 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5469 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5470 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5471 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5472 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5473 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5474 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5475 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5476 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5477 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5478 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5479 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5480 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5481 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5482 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5483 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5484 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5485 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5486 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5487 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5488 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5489 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005490 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5491 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5492 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5493 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5494 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5495 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005496 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005497 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005498 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5499
5500 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5501 T = Context.getAutoRRefDeductType();
5502 break;
5503
5504 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5505 T = Context.ARCUnbridgedCastTy;
5506 break;
5507
5508 case PREDEF_TYPE_VA_LIST_TAG:
5509 T = Context.getVaListTagType();
5510 break;
5511
5512 case PREDEF_TYPE_BUILTIN_FN:
5513 T = Context.BuiltinFnTy;
5514 break;
5515 }
5516
5517 assert(!T.isNull() && "Unknown predefined type");
5518 return T.withFastQualifiers(FastQuals);
5519 }
5520
5521 Index -= NUM_PREDEF_TYPE_IDS;
5522 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5523 if (TypesLoaded[Index].isNull()) {
5524 TypesLoaded[Index] = readTypeRecord(Index);
5525 if (TypesLoaded[Index].isNull())
5526 return QualType();
5527
5528 TypesLoaded[Index]->setFromAST();
5529 if (DeserializationListener)
5530 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5531 TypesLoaded[Index]);
5532 }
5533
5534 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5535}
5536
5537QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5538 return GetType(getGlobalTypeID(F, LocalID));
5539}
5540
5541serialization::TypeID
5542ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5543 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5544 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5545
5546 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5547 return LocalID;
5548
5549 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5550 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5551 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5552
5553 unsigned GlobalIndex = LocalIndex + I->second;
5554 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5555}
5556
5557TemplateArgumentLocInfo
5558ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5559 TemplateArgument::ArgKind Kind,
5560 const RecordData &Record,
5561 unsigned &Index) {
5562 switch (Kind) {
5563 case TemplateArgument::Expression:
5564 return ReadExpr(F);
5565 case TemplateArgument::Type:
5566 return GetTypeSourceInfo(F, Record, Index);
5567 case TemplateArgument::Template: {
5568 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5569 Index);
5570 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5571 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5572 SourceLocation());
5573 }
5574 case TemplateArgument::TemplateExpansion: {
5575 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5576 Index);
5577 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5578 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5579 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5580 EllipsisLoc);
5581 }
5582 case TemplateArgument::Null:
5583 case TemplateArgument::Integral:
5584 case TemplateArgument::Declaration:
5585 case TemplateArgument::NullPtr:
5586 case TemplateArgument::Pack:
5587 // FIXME: Is this right?
5588 return TemplateArgumentLocInfo();
5589 }
5590 llvm_unreachable("unexpected template argument loc");
5591}
5592
5593TemplateArgumentLoc
5594ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5595 const RecordData &Record, unsigned &Index) {
5596 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5597
5598 if (Arg.getKind() == TemplateArgument::Expression) {
5599 if (Record[Index++]) // bool InfoHasSameExpr.
5600 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5601 }
5602 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5603 Record, Index));
5604}
5605
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005606const ASTTemplateArgumentListInfo*
5607ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5608 const RecordData &Record,
5609 unsigned &Index) {
5610 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5611 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5612 unsigned NumArgsAsWritten = Record[Index++];
5613 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5614 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5615 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5616 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5617}
5618
Guy Benyei11169dd2012-12-18 14:30:41 +00005619Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5620 return GetDecl(ID);
5621}
5622
5623uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5624 unsigned &Idx){
5625 if (Idx >= Record.size())
5626 return 0;
5627
5628 unsigned LocalID = Record[Idx++];
5629 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5630}
5631
5632CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5633 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005634 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005635 SavedStreamPosition SavedPosition(Cursor);
5636 Cursor.JumpToBit(Loc.Offset);
5637 ReadingKindTracker ReadingKind(Read_Decl, *this);
5638 RecordData Record;
5639 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005640 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5642 Error("Malformed AST file: missing C++ base specifiers");
5643 return 0;
5644 }
5645
5646 unsigned Idx = 0;
5647 unsigned NumBases = Record[Idx++];
5648 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5649 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5650 for (unsigned I = 0; I != NumBases; ++I)
5651 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5652 return Bases;
5653}
5654
5655serialization::DeclID
5656ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5657 if (LocalID < NUM_PREDEF_DECL_IDS)
5658 return LocalID;
5659
5660 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5661 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5662 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5663
5664 return LocalID + I->second;
5665}
5666
5667bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5668 ModuleFile &M) const {
5669 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5670 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5671 return &M == I->second;
5672}
5673
Douglas Gregor9f782892013-01-21 15:25:38 +00005674ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 if (!D->isFromASTFile())
5676 return 0;
5677 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5678 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5679 return I->second;
5680}
5681
5682SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5683 if (ID < NUM_PREDEF_DECL_IDS)
5684 return SourceLocation();
5685
5686 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5687
5688 if (Index > DeclsLoaded.size()) {
5689 Error("declaration ID out-of-range for AST file");
5690 return SourceLocation();
5691 }
5692
5693 if (Decl *D = DeclsLoaded[Index])
5694 return D->getLocation();
5695
5696 unsigned RawLocation = 0;
5697 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5698 return ReadSourceLocation(*Rec.F, RawLocation);
5699}
5700
5701Decl *ASTReader::GetDecl(DeclID ID) {
5702 if (ID < NUM_PREDEF_DECL_IDS) {
5703 switch ((PredefinedDeclIDs)ID) {
5704 case PREDEF_DECL_NULL_ID:
5705 return 0;
5706
5707 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5708 return Context.getTranslationUnitDecl();
5709
5710 case PREDEF_DECL_OBJC_ID_ID:
5711 return Context.getObjCIdDecl();
5712
5713 case PREDEF_DECL_OBJC_SEL_ID:
5714 return Context.getObjCSelDecl();
5715
5716 case PREDEF_DECL_OBJC_CLASS_ID:
5717 return Context.getObjCClassDecl();
5718
5719 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5720 return Context.getObjCProtocolDecl();
5721
5722 case PREDEF_DECL_INT_128_ID:
5723 return Context.getInt128Decl();
5724
5725 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5726 return Context.getUInt128Decl();
5727
5728 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5729 return Context.getObjCInstanceTypeDecl();
5730
5731 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5732 return Context.getBuiltinVaListDecl();
5733 }
5734 }
5735
5736 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5737
5738 if (Index >= DeclsLoaded.size()) {
5739 assert(0 && "declaration ID out-of-range for AST file");
5740 Error("declaration ID out-of-range for AST file");
5741 return 0;
5742 }
5743
5744 if (!DeclsLoaded[Index]) {
5745 ReadDeclRecord(ID);
5746 if (DeserializationListener)
5747 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5748 }
5749
5750 return DeclsLoaded[Index];
5751}
5752
5753DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5754 DeclID GlobalID) {
5755 if (GlobalID < NUM_PREDEF_DECL_IDS)
5756 return GlobalID;
5757
5758 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5759 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5760 ModuleFile *Owner = I->second;
5761
5762 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5763 = M.GlobalToLocalDeclIDs.find(Owner);
5764 if (Pos == M.GlobalToLocalDeclIDs.end())
5765 return 0;
5766
5767 return GlobalID - Owner->BaseDeclID + Pos->second;
5768}
5769
5770serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5771 const RecordData &Record,
5772 unsigned &Idx) {
5773 if (Idx >= Record.size()) {
5774 Error("Corrupted AST file");
5775 return 0;
5776 }
5777
5778 return getGlobalDeclID(F, Record[Idx++]);
5779}
5780
5781/// \brief Resolve the offset of a statement into a statement.
5782///
5783/// This operation will read a new statement from the external
5784/// source each time it is called, and is meant to be used via a
5785/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5786Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5787 // Switch case IDs are per Decl.
5788 ClearSwitchCaseIDs();
5789
5790 // Offset here is a global offset across the entire chain.
5791 RecordLocation Loc = getLocalBitOffset(Offset);
5792 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5793 return ReadStmtFromStream(*Loc.F);
5794}
5795
5796namespace {
5797 class FindExternalLexicalDeclsVisitor {
5798 ASTReader &Reader;
5799 const DeclContext *DC;
5800 bool (*isKindWeWant)(Decl::Kind);
5801
5802 SmallVectorImpl<Decl*> &Decls;
5803 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5804
5805 public:
5806 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5807 bool (*isKindWeWant)(Decl::Kind),
5808 SmallVectorImpl<Decl*> &Decls)
5809 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5810 {
5811 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5812 PredefsVisited[I] = false;
5813 }
5814
5815 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5816 if (Preorder)
5817 return false;
5818
5819 FindExternalLexicalDeclsVisitor *This
5820 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5821
5822 ModuleFile::DeclContextInfosMap::iterator Info
5823 = M.DeclContextInfos.find(This->DC);
5824 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5825 return false;
5826
5827 // Load all of the declaration IDs
5828 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5829 *IDE = ID + Info->second.NumLexicalDecls;
5830 ID != IDE; ++ID) {
5831 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5832 continue;
5833
5834 // Don't add predefined declarations to the lexical context more
5835 // than once.
5836 if (ID->second < NUM_PREDEF_DECL_IDS) {
5837 if (This->PredefsVisited[ID->second])
5838 continue;
5839
5840 This->PredefsVisited[ID->second] = true;
5841 }
5842
5843 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5844 if (!This->DC->isDeclInLexicalTraversal(D))
5845 This->Decls.push_back(D);
5846 }
5847 }
5848
5849 return false;
5850 }
5851 };
5852}
5853
5854ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5855 bool (*isKindWeWant)(Decl::Kind),
5856 SmallVectorImpl<Decl*> &Decls) {
5857 // There might be lexical decls in multiple modules, for the TU at
5858 // least. Walk all of the modules in the order they were loaded.
5859 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5860 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5861 ++NumLexicalDeclContextsRead;
5862 return ELR_Success;
5863}
5864
5865namespace {
5866
5867class DeclIDComp {
5868 ASTReader &Reader;
5869 ModuleFile &Mod;
5870
5871public:
5872 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5873
5874 bool operator()(LocalDeclID L, LocalDeclID R) const {
5875 SourceLocation LHS = getLocation(L);
5876 SourceLocation RHS = getLocation(R);
5877 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5878 }
5879
5880 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5881 SourceLocation RHS = getLocation(R);
5882 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5883 }
5884
5885 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5886 SourceLocation LHS = getLocation(L);
5887 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5888 }
5889
5890 SourceLocation getLocation(LocalDeclID ID) const {
5891 return Reader.getSourceManager().getFileLoc(
5892 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5893 }
5894};
5895
5896}
5897
5898void ASTReader::FindFileRegionDecls(FileID File,
5899 unsigned Offset, unsigned Length,
5900 SmallVectorImpl<Decl *> &Decls) {
5901 SourceManager &SM = getSourceManager();
5902
5903 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5904 if (I == FileDeclIDs.end())
5905 return;
5906
5907 FileDeclsInfo &DInfo = I->second;
5908 if (DInfo.Decls.empty())
5909 return;
5910
5911 SourceLocation
5912 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5913 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5914
5915 DeclIDComp DIDComp(*this, *DInfo.Mod);
5916 ArrayRef<serialization::LocalDeclID>::iterator
5917 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5918 BeginLoc, DIDComp);
5919 if (BeginIt != DInfo.Decls.begin())
5920 --BeginIt;
5921
5922 // If we are pointing at a top-level decl inside an objc container, we need
5923 // to backtrack until we find it otherwise we will fail to report that the
5924 // region overlaps with an objc container.
5925 while (BeginIt != DInfo.Decls.begin() &&
5926 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5927 ->isTopLevelDeclInObjCContainer())
5928 --BeginIt;
5929
5930 ArrayRef<serialization::LocalDeclID>::iterator
5931 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5932 EndLoc, DIDComp);
5933 if (EndIt != DInfo.Decls.end())
5934 ++EndIt;
5935
5936 for (ArrayRef<serialization::LocalDeclID>::iterator
5937 DIt = BeginIt; DIt != EndIt; ++DIt)
5938 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5939}
5940
5941namespace {
5942 /// \brief ModuleFile visitor used to perform name lookup into a
5943 /// declaration context.
5944 class DeclContextNameLookupVisitor {
5945 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005946 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 DeclarationName Name;
5948 SmallVectorImpl<NamedDecl *> &Decls;
5949
5950 public:
5951 DeclContextNameLookupVisitor(ASTReader &Reader,
5952 SmallVectorImpl<const DeclContext *> &Contexts,
5953 DeclarationName Name,
5954 SmallVectorImpl<NamedDecl *> &Decls)
5955 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5956
5957 static bool visit(ModuleFile &M, void *UserData) {
5958 DeclContextNameLookupVisitor *This
5959 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5960
5961 // Check whether we have any visible declaration information for
5962 // this context in this module.
5963 ModuleFile::DeclContextInfosMap::iterator Info;
5964 bool FoundInfo = false;
5965 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5966 Info = M.DeclContextInfos.find(This->Contexts[I]);
5967 if (Info != M.DeclContextInfos.end() &&
5968 Info->second.NameLookupTableData) {
5969 FoundInfo = true;
5970 break;
5971 }
5972 }
5973
5974 if (!FoundInfo)
5975 return false;
5976
5977 // Look for this name within this module.
5978 ASTDeclContextNameLookupTable *LookupTable =
5979 Info->second.NameLookupTableData;
5980 ASTDeclContextNameLookupTable::iterator Pos
5981 = LookupTable->find(This->Name);
5982 if (Pos == LookupTable->end())
5983 return false;
5984
5985 bool FoundAnything = false;
5986 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5987 for (; Data.first != Data.second; ++Data.first) {
5988 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5989 if (!ND)
5990 continue;
5991
5992 if (ND->getDeclName() != This->Name) {
5993 // A name might be null because the decl's redeclarable part is
5994 // currently read before reading its name. The lookup is triggered by
5995 // building that decl (likely indirectly), and so it is later in the
5996 // sense of "already existing" and can be ignored here.
5997 continue;
5998 }
5999
6000 // Record this declaration.
6001 FoundAnything = true;
6002 This->Decls.push_back(ND);
6003 }
6004
6005 return FoundAnything;
6006 }
6007 };
6008}
6009
Douglas Gregor9f782892013-01-21 15:25:38 +00006010/// \brief Retrieve the "definitive" module file for the definition of the
6011/// given declaration context, if there is one.
6012///
6013/// The "definitive" module file is the only place where we need to look to
6014/// find information about the declarations within the given declaration
6015/// context. For example, C++ and Objective-C classes, C structs/unions, and
6016/// Objective-C protocols, categories, and extensions are all defined in a
6017/// single place in the source code, so they have definitive module files
6018/// associated with them. C++ namespaces, on the other hand, can have
6019/// definitions in multiple different module files.
6020///
6021/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6022/// NDEBUG checking.
6023static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6024 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006025 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6026 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006027
6028 return 0;
6029}
6030
Richard Smith9ce12e32013-02-07 03:30:24 +00006031bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006032ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6033 DeclarationName Name) {
6034 assert(DC->hasExternalVisibleStorage() &&
6035 "DeclContext has no visible decls in storage");
6036 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006037 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006038
6039 SmallVector<NamedDecl *, 64> Decls;
6040
6041 // Compute the declaration contexts we need to look into. Multiple such
6042 // declaration contexts occur when two declaration contexts from disjoint
6043 // modules get merged, e.g., when two namespaces with the same name are
6044 // independently defined in separate modules.
6045 SmallVector<const DeclContext *, 2> Contexts;
6046 Contexts.push_back(DC);
6047
6048 if (DC->isNamespace()) {
6049 MergedDeclsMap::iterator Merged
6050 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6051 if (Merged != MergedDecls.end()) {
6052 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6053 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6054 }
6055 }
6056
6057 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006058
6059 // If we can definitively determine which module file to look into,
6060 // only look there. Otherwise, look in all module files.
6061 ModuleFile *Definitive;
6062 if (Contexts.size() == 1 &&
6063 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6064 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6065 } else {
6066 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6067 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006068 ++NumVisibleDeclContextsRead;
6069 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006070 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006071}
6072
6073namespace {
6074 /// \brief ModuleFile visitor used to retrieve all visible names in a
6075 /// declaration context.
6076 class DeclContextAllNamesVisitor {
6077 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006078 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006079 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006080 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006081
6082 public:
6083 DeclContextAllNamesVisitor(ASTReader &Reader,
6084 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006085 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006086 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006087
6088 static bool visit(ModuleFile &M, void *UserData) {
6089 DeclContextAllNamesVisitor *This
6090 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6091
6092 // Check whether we have any visible declaration information for
6093 // this context in this module.
6094 ModuleFile::DeclContextInfosMap::iterator Info;
6095 bool FoundInfo = false;
6096 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6097 Info = M.DeclContextInfos.find(This->Contexts[I]);
6098 if (Info != M.DeclContextInfos.end() &&
6099 Info->second.NameLookupTableData) {
6100 FoundInfo = true;
6101 break;
6102 }
6103 }
6104
6105 if (!FoundInfo)
6106 return false;
6107
6108 ASTDeclContextNameLookupTable *LookupTable =
6109 Info->second.NameLookupTableData;
6110 bool FoundAnything = false;
6111 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006112 I = LookupTable->data_begin(), E = LookupTable->data_end();
6113 I != E;
6114 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006115 ASTDeclContextNameLookupTrait::data_type Data = *I;
6116 for (; Data.first != Data.second; ++Data.first) {
6117 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6118 *Data.first);
6119 if (!ND)
6120 continue;
6121
6122 // Record this declaration.
6123 FoundAnything = true;
6124 This->Decls[ND->getDeclName()].push_back(ND);
6125 }
6126 }
6127
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006128 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 }
6130 };
6131}
6132
6133void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6134 if (!DC->hasExternalVisibleStorage())
6135 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006136 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006137
6138 // Compute the declaration contexts we need to look into. Multiple such
6139 // declaration contexts occur when two declaration contexts from disjoint
6140 // modules get merged, e.g., when two namespaces with the same name are
6141 // independently defined in separate modules.
6142 SmallVector<const DeclContext *, 2> Contexts;
6143 Contexts.push_back(DC);
6144
6145 if (DC->isNamespace()) {
6146 MergedDeclsMap::iterator Merged
6147 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6148 if (Merged != MergedDecls.end()) {
6149 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6150 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6151 }
6152 }
6153
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006154 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6155 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6157 ++NumVisibleDeclContextsRead;
6158
Craig Topper79be4cd2013-07-05 04:33:53 +00006159 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6161 }
6162 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6163}
6164
6165/// \brief Under non-PCH compilation the consumer receives the objc methods
6166/// before receiving the implementation, and codegen depends on this.
6167/// We simulate this by deserializing and passing to consumer the methods of the
6168/// implementation before passing the deserialized implementation decl.
6169static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6170 ASTConsumer *Consumer) {
6171 assert(ImplD && Consumer);
6172
6173 for (ObjCImplDecl::method_iterator
6174 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
6175 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
6176
6177 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6178}
6179
6180void ASTReader::PassInterestingDeclsToConsumer() {
6181 assert(Consumer);
6182 while (!InterestingDecls.empty()) {
6183 Decl *D = InterestingDecls.front();
6184 InterestingDecls.pop_front();
6185
6186 PassInterestingDeclToConsumer(D);
6187 }
6188}
6189
6190void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6191 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6192 PassObjCImplDeclToConsumer(ImplD, Consumer);
6193 else
6194 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6195}
6196
6197void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6198 this->Consumer = Consumer;
6199
6200 if (!Consumer)
6201 return;
6202
Ben Langmuir332aafe2014-01-31 01:06:56 +00006203 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 // Force deserialization of this decl, which will cause it to be queued for
6205 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006206 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006207 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006208 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006209
6210 PassInterestingDeclsToConsumer();
6211}
6212
6213void ASTReader::PrintStats() {
6214 std::fprintf(stderr, "*** AST File Statistics:\n");
6215
6216 unsigned NumTypesLoaded
6217 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6218 QualType());
6219 unsigned NumDeclsLoaded
6220 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6221 (Decl *)0);
6222 unsigned NumIdentifiersLoaded
6223 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6224 IdentifiersLoaded.end(),
6225 (IdentifierInfo *)0);
6226 unsigned NumMacrosLoaded
6227 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6228 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006229 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 unsigned NumSelectorsLoaded
6231 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6232 SelectorsLoaded.end(),
6233 Selector());
6234
6235 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6236 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6237 NumSLocEntriesRead, TotalNumSLocEntries,
6238 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6239 if (!TypesLoaded.empty())
6240 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6241 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6242 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6243 if (!DeclsLoaded.empty())
6244 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6245 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6246 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6247 if (!IdentifiersLoaded.empty())
6248 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6249 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6250 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6251 if (!MacrosLoaded.empty())
6252 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6253 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6254 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6255 if (!SelectorsLoaded.empty())
6256 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6257 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6258 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6259 if (TotalNumStatements)
6260 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6261 NumStatementsRead, TotalNumStatements,
6262 ((float)NumStatementsRead/TotalNumStatements * 100));
6263 if (TotalNumMacros)
6264 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6265 NumMacrosRead, TotalNumMacros,
6266 ((float)NumMacrosRead/TotalNumMacros * 100));
6267 if (TotalLexicalDeclContexts)
6268 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6269 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6270 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6271 * 100));
6272 if (TotalVisibleDeclContexts)
6273 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6274 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6275 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6276 * 100));
6277 if (TotalNumMethodPoolEntries) {
6278 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6279 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6280 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6281 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006282 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006283 if (NumMethodPoolLookups) {
6284 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6285 NumMethodPoolHits, NumMethodPoolLookups,
6286 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6287 }
6288 if (NumMethodPoolTableLookups) {
6289 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6290 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6291 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6292 * 100.0));
6293 }
6294
Douglas Gregor00a50f72013-01-25 00:38:33 +00006295 if (NumIdentifierLookupHits) {
6296 std::fprintf(stderr,
6297 " %u / %u identifier table lookups succeeded (%f%%)\n",
6298 NumIdentifierLookupHits, NumIdentifierLookups,
6299 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6300 }
6301
Douglas Gregore060e572013-01-25 01:03:03 +00006302 if (GlobalIndex) {
6303 std::fprintf(stderr, "\n");
6304 GlobalIndex->printStats();
6305 }
6306
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 std::fprintf(stderr, "\n");
6308 dump();
6309 std::fprintf(stderr, "\n");
6310}
6311
6312template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6313static void
6314dumpModuleIDMap(StringRef Name,
6315 const ContinuousRangeMap<Key, ModuleFile *,
6316 InitialCapacity> &Map) {
6317 if (Map.begin() == Map.end())
6318 return;
6319
6320 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6321 llvm::errs() << Name << ":\n";
6322 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6323 I != IEnd; ++I) {
6324 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6325 << "\n";
6326 }
6327}
6328
6329void ASTReader::dump() {
6330 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6331 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6332 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6333 dumpModuleIDMap("Global type map", GlobalTypeMap);
6334 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6335 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6336 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6337 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6338 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6339 dumpModuleIDMap("Global preprocessed entity map",
6340 GlobalPreprocessedEntityMap);
6341
6342 llvm::errs() << "\n*** PCH/Modules Loaded:";
6343 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6344 MEnd = ModuleMgr.end();
6345 M != MEnd; ++M)
6346 (*M)->dump();
6347}
6348
6349/// Return the amount of memory used by memory buffers, breaking down
6350/// by heap-backed versus mmap'ed memory.
6351void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6352 for (ModuleConstIterator I = ModuleMgr.begin(),
6353 E = ModuleMgr.end(); I != E; ++I) {
6354 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6355 size_t bytes = buf->getBufferSize();
6356 switch (buf->getBufferKind()) {
6357 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6358 sizes.malloc_bytes += bytes;
6359 break;
6360 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6361 sizes.mmap_bytes += bytes;
6362 break;
6363 }
6364 }
6365 }
6366}
6367
6368void ASTReader::InitializeSema(Sema &S) {
6369 SemaObj = &S;
6370 S.addExternalSource(this);
6371
6372 // Makes sure any declarations that were deserialized "too early"
6373 // still get added to the identifier's declaration chains.
6374 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006375 pushExternalDeclIntoScope(PreloadedDecls[I],
6376 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 }
6378 PreloadedDecls.clear();
6379
Richard Smith3d8e97e2013-10-18 06:54:39 +00006380 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 if (!FPPragmaOptions.empty()) {
6382 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6383 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6384 }
6385
Richard Smith3d8e97e2013-10-18 06:54:39 +00006386 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 if (!OpenCLExtensions.empty()) {
6388 unsigned I = 0;
6389#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6390#include "clang/Basic/OpenCLExtensions.def"
6391
6392 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6393 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006394
6395 UpdateSema();
6396}
6397
6398void ASTReader::UpdateSema() {
6399 assert(SemaObj && "no Sema to update");
6400
6401 // Load the offsets of the declarations that Sema references.
6402 // They will be lazily deserialized when needed.
6403 if (!SemaDeclRefs.empty()) {
6404 assert(SemaDeclRefs.size() % 2 == 0);
6405 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6406 if (!SemaObj->StdNamespace)
6407 SemaObj->StdNamespace = SemaDeclRefs[I];
6408 if (!SemaObj->StdBadAlloc)
6409 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6410 }
6411 SemaDeclRefs.clear();
6412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006413}
6414
6415IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6416 // Note that we are loading an identifier.
6417 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006418 StringRef Name(NameStart, NameEnd - NameStart);
6419
6420 // If there is a global index, look there first to determine which modules
6421 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006422 GlobalModuleIndex::HitSet Hits;
6423 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006424 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006425 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6426 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006427 }
6428 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006429 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006430 NumIdentifierLookups,
6431 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006432 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 IdentifierInfo *II = Visitor.getIdentifierInfo();
6434 markIdentifierUpToDate(II);
6435 return II;
6436}
6437
6438namespace clang {
6439 /// \brief An identifier-lookup iterator that enumerates all of the
6440 /// identifiers stored within a set of AST files.
6441 class ASTIdentifierIterator : public IdentifierIterator {
6442 /// \brief The AST reader whose identifiers are being enumerated.
6443 const ASTReader &Reader;
6444
6445 /// \brief The current index into the chain of AST files stored in
6446 /// the AST reader.
6447 unsigned Index;
6448
6449 /// \brief The current position within the identifier lookup table
6450 /// of the current AST file.
6451 ASTIdentifierLookupTable::key_iterator Current;
6452
6453 /// \brief The end position within the identifier lookup table of
6454 /// the current AST file.
6455 ASTIdentifierLookupTable::key_iterator End;
6456
6457 public:
6458 explicit ASTIdentifierIterator(const ASTReader &Reader);
6459
6460 virtual StringRef Next();
6461 };
6462}
6463
6464ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6465 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6466 ASTIdentifierLookupTable *IdTable
6467 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6468 Current = IdTable->key_begin();
6469 End = IdTable->key_end();
6470}
6471
6472StringRef ASTIdentifierIterator::Next() {
6473 while (Current == End) {
6474 // If we have exhausted all of our AST files, we're done.
6475 if (Index == 0)
6476 return StringRef();
6477
6478 --Index;
6479 ASTIdentifierLookupTable *IdTable
6480 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6481 IdentifierLookupTable;
6482 Current = IdTable->key_begin();
6483 End = IdTable->key_end();
6484 }
6485
6486 // We have any identifiers remaining in the current AST file; return
6487 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006488 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006489 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006490 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006491}
6492
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006493IdentifierIterator *ASTReader::getIdentifiers() {
6494 if (!loadGlobalIndex())
6495 return GlobalIndex->createIdentifierIterator();
6496
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 return new ASTIdentifierIterator(*this);
6498}
6499
6500namespace clang { namespace serialization {
6501 class ReadMethodPoolVisitor {
6502 ASTReader &Reader;
6503 Selector Sel;
6504 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006505 unsigned InstanceBits;
6506 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006507 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6508 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006509
6510 public:
6511 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6512 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006513 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6514 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006515
6516 static bool visit(ModuleFile &M, void *UserData) {
6517 ReadMethodPoolVisitor *This
6518 = static_cast<ReadMethodPoolVisitor *>(UserData);
6519
6520 if (!M.SelectorLookupTable)
6521 return false;
6522
6523 // If we've already searched this module file, skip it now.
6524 if (M.Generation <= This->PriorGeneration)
6525 return true;
6526
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006527 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 ASTSelectorLookupTable *PoolTable
6529 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6530 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6531 if (Pos == PoolTable->end())
6532 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006533
6534 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 ++This->Reader.NumSelectorsRead;
6536 // FIXME: Not quite happy with the statistics here. We probably should
6537 // disable this tracking when called via LoadSelector.
6538 // Also, should entries without methods count as misses?
6539 ++This->Reader.NumMethodPoolEntriesRead;
6540 ASTSelectorLookupTrait::data_type Data = *Pos;
6541 if (This->Reader.DeserializationListener)
6542 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6543 This->Sel);
6544
6545 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6546 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006547 This->InstanceBits = Data.InstanceBits;
6548 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 return true;
6550 }
6551
6552 /// \brief Retrieve the instance methods found by this visitor.
6553 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6554 return InstanceMethods;
6555 }
6556
6557 /// \brief Retrieve the instance methods found by this visitor.
6558 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6559 return FactoryMethods;
6560 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006561
6562 unsigned getInstanceBits() const { return InstanceBits; }
6563 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 };
6565} } // end namespace clang::serialization
6566
6567/// \brief Add the given set of methods to the method list.
6568static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6569 ObjCMethodList &List) {
6570 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6571 S.addMethodToGlobalList(&List, Methods[I]);
6572 }
6573}
6574
6575void ASTReader::ReadMethodPool(Selector Sel) {
6576 // Get the selector generation and update it to the current generation.
6577 unsigned &Generation = SelectorGeneration[Sel];
6578 unsigned PriorGeneration = Generation;
6579 Generation = CurrentGeneration;
6580
6581 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006582 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6584 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6585
6586 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006587 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006589
6590 ++NumMethodPoolHits;
6591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 if (!getSema())
6593 return;
6594
6595 Sema &S = *getSema();
6596 Sema::GlobalMethodPool::iterator Pos
6597 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6598
6599 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6600 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006601 Pos->second.first.setBits(Visitor.getInstanceBits());
6602 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006603}
6604
6605void ASTReader::ReadKnownNamespaces(
6606 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6607 Namespaces.clear();
6608
6609 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6610 if (NamespaceDecl *Namespace
6611 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6612 Namespaces.push_back(Namespace);
6613 }
6614}
6615
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006616void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006617 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006618 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6619 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006620 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006621 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006622 Undefined.insert(std::make_pair(D, Loc));
6623 }
6624}
Nick Lewycky8334af82013-01-26 00:35:08 +00006625
Guy Benyei11169dd2012-12-18 14:30:41 +00006626void ASTReader::ReadTentativeDefinitions(
6627 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6628 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6629 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6630 if (Var)
6631 TentativeDefs.push_back(Var);
6632 }
6633 TentativeDefinitions.clear();
6634}
6635
6636void ASTReader::ReadUnusedFileScopedDecls(
6637 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6638 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6639 DeclaratorDecl *D
6640 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6641 if (D)
6642 Decls.push_back(D);
6643 }
6644 UnusedFileScopedDecls.clear();
6645}
6646
6647void ASTReader::ReadDelegatingConstructors(
6648 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6649 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6650 CXXConstructorDecl *D
6651 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6652 if (D)
6653 Decls.push_back(D);
6654 }
6655 DelegatingCtorDecls.clear();
6656}
6657
6658void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6659 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6660 TypedefNameDecl *D
6661 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6662 if (D)
6663 Decls.push_back(D);
6664 }
6665 ExtVectorDecls.clear();
6666}
6667
6668void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6669 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6670 CXXRecordDecl *D
6671 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6672 if (D)
6673 Decls.push_back(D);
6674 }
6675 DynamicClasses.clear();
6676}
6677
6678void
Richard Smith78165b52013-01-10 23:43:47 +00006679ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6680 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6681 NamedDecl *D
6682 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 if (D)
6684 Decls.push_back(D);
6685 }
Richard Smith78165b52013-01-10 23:43:47 +00006686 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006687}
6688
6689void ASTReader::ReadReferencedSelectors(
6690 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6691 if (ReferencedSelectorsData.empty())
6692 return;
6693
6694 // If there are @selector references added them to its pool. This is for
6695 // implementation of -Wselector.
6696 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6697 unsigned I = 0;
6698 while (I < DataSize) {
6699 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6700 SourceLocation SelLoc
6701 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6702 Sels.push_back(std::make_pair(Sel, SelLoc));
6703 }
6704 ReferencedSelectorsData.clear();
6705}
6706
6707void ASTReader::ReadWeakUndeclaredIdentifiers(
6708 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6709 if (WeakUndeclaredIdentifiers.empty())
6710 return;
6711
6712 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6713 IdentifierInfo *WeakId
6714 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6715 IdentifierInfo *AliasId
6716 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6717 SourceLocation Loc
6718 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6719 bool Used = WeakUndeclaredIdentifiers[I++];
6720 WeakInfo WI(AliasId, Loc);
6721 WI.setUsed(Used);
6722 WeakIDs.push_back(std::make_pair(WeakId, WI));
6723 }
6724 WeakUndeclaredIdentifiers.clear();
6725}
6726
6727void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6728 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6729 ExternalVTableUse VT;
6730 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6731 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6732 VT.DefinitionRequired = VTableUses[Idx++];
6733 VTables.push_back(VT);
6734 }
6735
6736 VTableUses.clear();
6737}
6738
6739void ASTReader::ReadPendingInstantiations(
6740 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6741 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6742 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6743 SourceLocation Loc
6744 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6745
6746 Pending.push_back(std::make_pair(D, Loc));
6747 }
6748 PendingInstantiations.clear();
6749}
6750
Richard Smithe40f2ba2013-08-07 21:41:30 +00006751void ASTReader::ReadLateParsedTemplates(
6752 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6753 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6754 /* In loop */) {
6755 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6756
6757 LateParsedTemplate *LT = new LateParsedTemplate;
6758 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6759
6760 ModuleFile *F = getOwningModuleFile(LT->D);
6761 assert(F && "No module");
6762
6763 unsigned TokN = LateParsedTemplates[Idx++];
6764 LT->Toks.reserve(TokN);
6765 for (unsigned T = 0; T < TokN; ++T)
6766 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6767
6768 LPTMap[FD] = LT;
6769 }
6770
6771 LateParsedTemplates.clear();
6772}
6773
Guy Benyei11169dd2012-12-18 14:30:41 +00006774void ASTReader::LoadSelector(Selector Sel) {
6775 // It would be complicated to avoid reading the methods anyway. So don't.
6776 ReadMethodPool(Sel);
6777}
6778
6779void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6780 assert(ID && "Non-zero identifier ID required");
6781 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6782 IdentifiersLoaded[ID - 1] = II;
6783 if (DeserializationListener)
6784 DeserializationListener->IdentifierRead(ID, II);
6785}
6786
6787/// \brief Set the globally-visible declarations associated with the given
6788/// identifier.
6789///
6790/// If the AST reader is currently in a state where the given declaration IDs
6791/// cannot safely be resolved, they are queued until it is safe to resolve
6792/// them.
6793///
6794/// \param II an IdentifierInfo that refers to one or more globally-visible
6795/// declarations.
6796///
6797/// \param DeclIDs the set of declaration IDs with the name @p II that are
6798/// visible at global scope.
6799///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006800/// \param Decls if non-null, this vector will be populated with the set of
6801/// deserialized declarations. These declarations will not be pushed into
6802/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006803void
6804ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6805 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006806 SmallVectorImpl<Decl *> *Decls) {
6807 if (NumCurrentElementsDeserializing && !Decls) {
6808 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006809 return;
6810 }
6811
6812 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6813 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6814 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006815 // If we're simply supposed to record the declarations, do so now.
6816 if (Decls) {
6817 Decls->push_back(D);
6818 continue;
6819 }
6820
Guy Benyei11169dd2012-12-18 14:30:41 +00006821 // Introduce this declaration into the translation-unit scope
6822 // and add it to the declaration chain for this identifier, so
6823 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006824 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 } else {
6826 // Queue this declaration so that it will be added to the
6827 // translation unit scope and identifier's declaration chain
6828 // once a Sema object is known.
6829 PreloadedDecls.push_back(D);
6830 }
6831 }
6832}
6833
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006834IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006835 if (ID == 0)
6836 return 0;
6837
6838 if (IdentifiersLoaded.empty()) {
6839 Error("no identifier table in AST file");
6840 return 0;
6841 }
6842
6843 ID -= 1;
6844 if (!IdentifiersLoaded[ID]) {
6845 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6846 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6847 ModuleFile *M = I->second;
6848 unsigned Index = ID - M->BaseIdentifierID;
6849 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6850
6851 // All of the strings in the AST file are preceded by a 16-bit length.
6852 // Extract that 16-bit length to avoid having to execute strlen().
6853 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6854 // unsigned integers. This is important to avoid integer overflow when
6855 // we cast them to 'unsigned'.
6856 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6857 unsigned StrLen = (((unsigned) StrLenPtr[0])
6858 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006859 IdentifiersLoaded[ID]
6860 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 if (DeserializationListener)
6862 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6863 }
6864
6865 return IdentifiersLoaded[ID];
6866}
6867
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006868IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6869 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006870}
6871
6872IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6873 if (LocalID < NUM_PREDEF_IDENT_IDS)
6874 return LocalID;
6875
6876 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6877 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6878 assert(I != M.IdentifierRemap.end()
6879 && "Invalid index into identifier index remap");
6880
6881 return LocalID + I->second;
6882}
6883
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006884MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 if (ID == 0)
6886 return 0;
6887
6888 if (MacrosLoaded.empty()) {
6889 Error("no macro table in AST file");
6890 return 0;
6891 }
6892
6893 ID -= NUM_PREDEF_MACRO_IDS;
6894 if (!MacrosLoaded[ID]) {
6895 GlobalMacroMapType::iterator I
6896 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6897 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6898 ModuleFile *M = I->second;
6899 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006900 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
6901
6902 if (DeserializationListener)
6903 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
6904 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006905 }
6906
6907 return MacrosLoaded[ID];
6908}
6909
6910MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6911 if (LocalID < NUM_PREDEF_MACRO_IDS)
6912 return LocalID;
6913
6914 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6915 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6916 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6917
6918 return LocalID + I->second;
6919}
6920
6921serialization::SubmoduleID
6922ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6923 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6924 return LocalID;
6925
6926 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6927 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6928 assert(I != M.SubmoduleRemap.end()
6929 && "Invalid index into submodule index remap");
6930
6931 return LocalID + I->second;
6932}
6933
6934Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6935 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6936 assert(GlobalID == 0 && "Unhandled global submodule ID");
6937 return 0;
6938 }
6939
6940 if (GlobalID > SubmodulesLoaded.size()) {
6941 Error("submodule ID out of range in AST file");
6942 return 0;
6943 }
6944
6945 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6946}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00006947
6948Module *ASTReader::getModule(unsigned ID) {
6949 return getSubmodule(ID);
6950}
6951
Guy Benyei11169dd2012-12-18 14:30:41 +00006952Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6953 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6954}
6955
6956Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6957 if (ID == 0)
6958 return Selector();
6959
6960 if (ID > SelectorsLoaded.size()) {
6961 Error("selector ID out of range in AST file");
6962 return Selector();
6963 }
6964
6965 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6966 // Load this selector from the selector table.
6967 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6968 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6969 ModuleFile &M = *I->second;
6970 ASTSelectorLookupTrait Trait(*this, M);
6971 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6972 SelectorsLoaded[ID - 1] =
6973 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6974 if (DeserializationListener)
6975 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6976 }
6977
6978 return SelectorsLoaded[ID - 1];
6979}
6980
6981Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6982 return DecodeSelector(ID);
6983}
6984
6985uint32_t ASTReader::GetNumExternalSelectors() {
6986 // ID 0 (the null selector) is considered an external selector.
6987 return getTotalNumSelectors() + 1;
6988}
6989
6990serialization::SelectorID
6991ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6992 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6993 return LocalID;
6994
6995 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6996 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6997 assert(I != M.SelectorRemap.end()
6998 && "Invalid index into selector index remap");
6999
7000 return LocalID + I->second;
7001}
7002
7003DeclarationName
7004ASTReader::ReadDeclarationName(ModuleFile &F,
7005 const RecordData &Record, unsigned &Idx) {
7006 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7007 switch (Kind) {
7008 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007009 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007010
7011 case DeclarationName::ObjCZeroArgSelector:
7012 case DeclarationName::ObjCOneArgSelector:
7013 case DeclarationName::ObjCMultiArgSelector:
7014 return DeclarationName(ReadSelector(F, Record, Idx));
7015
7016 case DeclarationName::CXXConstructorName:
7017 return Context.DeclarationNames.getCXXConstructorName(
7018 Context.getCanonicalType(readType(F, Record, Idx)));
7019
7020 case DeclarationName::CXXDestructorName:
7021 return Context.DeclarationNames.getCXXDestructorName(
7022 Context.getCanonicalType(readType(F, Record, Idx)));
7023
7024 case DeclarationName::CXXConversionFunctionName:
7025 return Context.DeclarationNames.getCXXConversionFunctionName(
7026 Context.getCanonicalType(readType(F, Record, Idx)));
7027
7028 case DeclarationName::CXXOperatorName:
7029 return Context.DeclarationNames.getCXXOperatorName(
7030 (OverloadedOperatorKind)Record[Idx++]);
7031
7032 case DeclarationName::CXXLiteralOperatorName:
7033 return Context.DeclarationNames.getCXXLiteralOperatorName(
7034 GetIdentifierInfo(F, Record, Idx));
7035
7036 case DeclarationName::CXXUsingDirective:
7037 return DeclarationName::getUsingDirectiveName();
7038 }
7039
7040 llvm_unreachable("Invalid NameKind!");
7041}
7042
7043void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7044 DeclarationNameLoc &DNLoc,
7045 DeclarationName Name,
7046 const RecordData &Record, unsigned &Idx) {
7047 switch (Name.getNameKind()) {
7048 case DeclarationName::CXXConstructorName:
7049 case DeclarationName::CXXDestructorName:
7050 case DeclarationName::CXXConversionFunctionName:
7051 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7052 break;
7053
7054 case DeclarationName::CXXOperatorName:
7055 DNLoc.CXXOperatorName.BeginOpNameLoc
7056 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7057 DNLoc.CXXOperatorName.EndOpNameLoc
7058 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7059 break;
7060
7061 case DeclarationName::CXXLiteralOperatorName:
7062 DNLoc.CXXLiteralOperatorName.OpNameLoc
7063 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7064 break;
7065
7066 case DeclarationName::Identifier:
7067 case DeclarationName::ObjCZeroArgSelector:
7068 case DeclarationName::ObjCOneArgSelector:
7069 case DeclarationName::ObjCMultiArgSelector:
7070 case DeclarationName::CXXUsingDirective:
7071 break;
7072 }
7073}
7074
7075void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7076 DeclarationNameInfo &NameInfo,
7077 const RecordData &Record, unsigned &Idx) {
7078 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7079 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7080 DeclarationNameLoc DNLoc;
7081 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7082 NameInfo.setInfo(DNLoc);
7083}
7084
7085void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7086 const RecordData &Record, unsigned &Idx) {
7087 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7088 unsigned NumTPLists = Record[Idx++];
7089 Info.NumTemplParamLists = NumTPLists;
7090 if (NumTPLists) {
7091 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7092 for (unsigned i=0; i != NumTPLists; ++i)
7093 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7094 }
7095}
7096
7097TemplateName
7098ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7099 unsigned &Idx) {
7100 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7101 switch (Kind) {
7102 case TemplateName::Template:
7103 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7104
7105 case TemplateName::OverloadedTemplate: {
7106 unsigned size = Record[Idx++];
7107 UnresolvedSet<8> Decls;
7108 while (size--)
7109 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7110
7111 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7112 }
7113
7114 case TemplateName::QualifiedTemplate: {
7115 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7116 bool hasTemplKeyword = Record[Idx++];
7117 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7118 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7119 }
7120
7121 case TemplateName::DependentTemplate: {
7122 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7123 if (Record[Idx++]) // isIdentifier
7124 return Context.getDependentTemplateName(NNS,
7125 GetIdentifierInfo(F, Record,
7126 Idx));
7127 return Context.getDependentTemplateName(NNS,
7128 (OverloadedOperatorKind)Record[Idx++]);
7129 }
7130
7131 case TemplateName::SubstTemplateTemplateParm: {
7132 TemplateTemplateParmDecl *param
7133 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7134 if (!param) return TemplateName();
7135 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7136 return Context.getSubstTemplateTemplateParm(param, replacement);
7137 }
7138
7139 case TemplateName::SubstTemplateTemplateParmPack: {
7140 TemplateTemplateParmDecl *Param
7141 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7142 if (!Param)
7143 return TemplateName();
7144
7145 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7146 if (ArgPack.getKind() != TemplateArgument::Pack)
7147 return TemplateName();
7148
7149 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7150 }
7151 }
7152
7153 llvm_unreachable("Unhandled template name kind!");
7154}
7155
7156TemplateArgument
7157ASTReader::ReadTemplateArgument(ModuleFile &F,
7158 const RecordData &Record, unsigned &Idx) {
7159 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7160 switch (Kind) {
7161 case TemplateArgument::Null:
7162 return TemplateArgument();
7163 case TemplateArgument::Type:
7164 return TemplateArgument(readType(F, Record, Idx));
7165 case TemplateArgument::Declaration: {
7166 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7167 bool ForReferenceParam = Record[Idx++];
7168 return TemplateArgument(D, ForReferenceParam);
7169 }
7170 case TemplateArgument::NullPtr:
7171 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7172 case TemplateArgument::Integral: {
7173 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7174 QualType T = readType(F, Record, Idx);
7175 return TemplateArgument(Context, Value, T);
7176 }
7177 case TemplateArgument::Template:
7178 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7179 case TemplateArgument::TemplateExpansion: {
7180 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007181 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 if (unsigned NumExpansions = Record[Idx++])
7183 NumTemplateExpansions = NumExpansions - 1;
7184 return TemplateArgument(Name, NumTemplateExpansions);
7185 }
7186 case TemplateArgument::Expression:
7187 return TemplateArgument(ReadExpr(F));
7188 case TemplateArgument::Pack: {
7189 unsigned NumArgs = Record[Idx++];
7190 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7191 for (unsigned I = 0; I != NumArgs; ++I)
7192 Args[I] = ReadTemplateArgument(F, Record, Idx);
7193 return TemplateArgument(Args, NumArgs);
7194 }
7195 }
7196
7197 llvm_unreachable("Unhandled template argument kind!");
7198}
7199
7200TemplateParameterList *
7201ASTReader::ReadTemplateParameterList(ModuleFile &F,
7202 const RecordData &Record, unsigned &Idx) {
7203 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7204 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7205 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7206
7207 unsigned NumParams = Record[Idx++];
7208 SmallVector<NamedDecl *, 16> Params;
7209 Params.reserve(NumParams);
7210 while (NumParams--)
7211 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7212
7213 TemplateParameterList* TemplateParams =
7214 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7215 Params.data(), Params.size(), RAngleLoc);
7216 return TemplateParams;
7217}
7218
7219void
7220ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007221ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 ModuleFile &F, const RecordData &Record,
7223 unsigned &Idx) {
7224 unsigned NumTemplateArgs = Record[Idx++];
7225 TemplArgs.reserve(NumTemplateArgs);
7226 while (NumTemplateArgs--)
7227 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7228}
7229
7230/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007231void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 const RecordData &Record, unsigned &Idx) {
7233 unsigned NumDecls = Record[Idx++];
7234 Set.reserve(Context, NumDecls);
7235 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007236 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007238 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 }
7240}
7241
7242CXXBaseSpecifier
7243ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7244 const RecordData &Record, unsigned &Idx) {
7245 bool isVirtual = static_cast<bool>(Record[Idx++]);
7246 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7247 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7248 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7249 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7250 SourceRange Range = ReadSourceRange(F, Record, Idx);
7251 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7252 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7253 EllipsisLoc);
7254 Result.setInheritConstructors(inheritConstructors);
7255 return Result;
7256}
7257
7258std::pair<CXXCtorInitializer **, unsigned>
7259ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7260 unsigned &Idx) {
7261 CXXCtorInitializer **CtorInitializers = 0;
7262 unsigned NumInitializers = Record[Idx++];
7263 if (NumInitializers) {
7264 CtorInitializers
7265 = new (Context) CXXCtorInitializer*[NumInitializers];
7266 for (unsigned i=0; i != NumInitializers; ++i) {
7267 TypeSourceInfo *TInfo = 0;
7268 bool IsBaseVirtual = false;
7269 FieldDecl *Member = 0;
7270 IndirectFieldDecl *IndirectMember = 0;
7271
7272 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7273 switch (Type) {
7274 case CTOR_INITIALIZER_BASE:
7275 TInfo = GetTypeSourceInfo(F, Record, Idx);
7276 IsBaseVirtual = Record[Idx++];
7277 break;
7278
7279 case CTOR_INITIALIZER_DELEGATING:
7280 TInfo = GetTypeSourceInfo(F, Record, Idx);
7281 break;
7282
7283 case CTOR_INITIALIZER_MEMBER:
7284 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7285 break;
7286
7287 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7288 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7289 break;
7290 }
7291
7292 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7293 Expr *Init = ReadExpr(F);
7294 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7295 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7296 bool IsWritten = Record[Idx++];
7297 unsigned SourceOrderOrNumArrayIndices;
7298 SmallVector<VarDecl *, 8> Indices;
7299 if (IsWritten) {
7300 SourceOrderOrNumArrayIndices = Record[Idx++];
7301 } else {
7302 SourceOrderOrNumArrayIndices = Record[Idx++];
7303 Indices.reserve(SourceOrderOrNumArrayIndices);
7304 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7305 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7306 }
7307
7308 CXXCtorInitializer *BOMInit;
7309 if (Type == CTOR_INITIALIZER_BASE) {
7310 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7311 LParenLoc, Init, RParenLoc,
7312 MemberOrEllipsisLoc);
7313 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7314 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7315 Init, RParenLoc);
7316 } else if (IsWritten) {
7317 if (Member)
7318 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7319 LParenLoc, Init, RParenLoc);
7320 else
7321 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7322 MemberOrEllipsisLoc, LParenLoc,
7323 Init, RParenLoc);
7324 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007325 if (IndirectMember) {
7326 assert(Indices.empty() && "Indirect field improperly initialized");
7327 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7328 MemberOrEllipsisLoc, LParenLoc,
7329 Init, RParenLoc);
7330 } else {
7331 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7332 LParenLoc, Init, RParenLoc,
7333 Indices.data(), Indices.size());
7334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 }
7336
7337 if (IsWritten)
7338 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7339 CtorInitializers[i] = BOMInit;
7340 }
7341 }
7342
7343 return std::make_pair(CtorInitializers, NumInitializers);
7344}
7345
7346NestedNameSpecifier *
7347ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7348 const RecordData &Record, unsigned &Idx) {
7349 unsigned N = Record[Idx++];
7350 NestedNameSpecifier *NNS = 0, *Prev = 0;
7351 for (unsigned I = 0; I != N; ++I) {
7352 NestedNameSpecifier::SpecifierKind Kind
7353 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7354 switch (Kind) {
7355 case NestedNameSpecifier::Identifier: {
7356 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7357 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7358 break;
7359 }
7360
7361 case NestedNameSpecifier::Namespace: {
7362 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7363 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7364 break;
7365 }
7366
7367 case NestedNameSpecifier::NamespaceAlias: {
7368 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7369 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7370 break;
7371 }
7372
7373 case NestedNameSpecifier::TypeSpec:
7374 case NestedNameSpecifier::TypeSpecWithTemplate: {
7375 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7376 if (!T)
7377 return 0;
7378
7379 bool Template = Record[Idx++];
7380 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7381 break;
7382 }
7383
7384 case NestedNameSpecifier::Global: {
7385 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7386 // No associated value, and there can't be a prefix.
7387 break;
7388 }
7389 }
7390 Prev = NNS;
7391 }
7392 return NNS;
7393}
7394
7395NestedNameSpecifierLoc
7396ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7397 unsigned &Idx) {
7398 unsigned N = Record[Idx++];
7399 NestedNameSpecifierLocBuilder Builder;
7400 for (unsigned I = 0; I != N; ++I) {
7401 NestedNameSpecifier::SpecifierKind Kind
7402 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7403 switch (Kind) {
7404 case NestedNameSpecifier::Identifier: {
7405 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7406 SourceRange Range = ReadSourceRange(F, Record, Idx);
7407 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7408 break;
7409 }
7410
7411 case NestedNameSpecifier::Namespace: {
7412 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7413 SourceRange Range = ReadSourceRange(F, Record, Idx);
7414 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7415 break;
7416 }
7417
7418 case NestedNameSpecifier::NamespaceAlias: {
7419 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7420 SourceRange Range = ReadSourceRange(F, Record, Idx);
7421 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7422 break;
7423 }
7424
7425 case NestedNameSpecifier::TypeSpec:
7426 case NestedNameSpecifier::TypeSpecWithTemplate: {
7427 bool Template = Record[Idx++];
7428 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7429 if (!T)
7430 return NestedNameSpecifierLoc();
7431 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7432
7433 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7434 Builder.Extend(Context,
7435 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7436 T->getTypeLoc(), ColonColonLoc);
7437 break;
7438 }
7439
7440 case NestedNameSpecifier::Global: {
7441 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7442 Builder.MakeGlobal(Context, ColonColonLoc);
7443 break;
7444 }
7445 }
7446 }
7447
7448 return Builder.getWithLocInContext(Context);
7449}
7450
7451SourceRange
7452ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7453 unsigned &Idx) {
7454 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7455 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7456 return SourceRange(beg, end);
7457}
7458
7459/// \brief Read an integral value
7460llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7461 unsigned BitWidth = Record[Idx++];
7462 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7463 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7464 Idx += NumWords;
7465 return Result;
7466}
7467
7468/// \brief Read a signed integral value
7469llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7470 bool isUnsigned = Record[Idx++];
7471 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7472}
7473
7474/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007475llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7476 const llvm::fltSemantics &Sem,
7477 unsigned &Idx) {
7478 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007479}
7480
7481// \brief Read a string
7482std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7483 unsigned Len = Record[Idx++];
7484 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7485 Idx += Len;
7486 return Result;
7487}
7488
7489VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7490 unsigned &Idx) {
7491 unsigned Major = Record[Idx++];
7492 unsigned Minor = Record[Idx++];
7493 unsigned Subminor = Record[Idx++];
7494 if (Minor == 0)
7495 return VersionTuple(Major);
7496 if (Subminor == 0)
7497 return VersionTuple(Major, Minor - 1);
7498 return VersionTuple(Major, Minor - 1, Subminor - 1);
7499}
7500
7501CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7502 const RecordData &Record,
7503 unsigned &Idx) {
7504 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7505 return CXXTemporary::Create(Context, Decl);
7506}
7507
7508DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007509 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007510}
7511
7512DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7513 return Diags.Report(Loc, DiagID);
7514}
7515
7516/// \brief Retrieve the identifier table associated with the
7517/// preprocessor.
7518IdentifierTable &ASTReader::getIdentifierTable() {
7519 return PP.getIdentifierTable();
7520}
7521
7522/// \brief Record that the given ID maps to the given switch-case
7523/// statement.
7524void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7525 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7526 "Already have a SwitchCase with this ID");
7527 (*CurrSwitchCaseStmts)[ID] = SC;
7528}
7529
7530/// \brief Retrieve the switch-case statement with the given ID.
7531SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7532 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7533 return (*CurrSwitchCaseStmts)[ID];
7534}
7535
7536void ASTReader::ClearSwitchCaseIDs() {
7537 CurrSwitchCaseStmts->clear();
7538}
7539
7540void ASTReader::ReadComments() {
7541 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007542 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007543 serialization::ModuleFile *> >::iterator
7544 I = CommentsCursors.begin(),
7545 E = CommentsCursors.end();
7546 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007547 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 serialization::ModuleFile &F = *I->second;
7549 SavedStreamPosition SavedPosition(Cursor);
7550
7551 RecordData Record;
7552 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007553 llvm::BitstreamEntry Entry =
7554 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7555
7556 switch (Entry.Kind) {
7557 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7558 case llvm::BitstreamEntry::Error:
7559 Error("malformed block record in AST file");
7560 return;
7561 case llvm::BitstreamEntry::EndBlock:
7562 goto NextCursor;
7563 case llvm::BitstreamEntry::Record:
7564 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007565 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007566 }
7567
7568 // Read a record.
7569 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007570 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 case COMMENTS_RAW_COMMENT: {
7572 unsigned Idx = 0;
7573 SourceRange SR = ReadSourceRange(F, Record, Idx);
7574 RawComment::CommentKind Kind =
7575 (RawComment::CommentKind) Record[Idx++];
7576 bool IsTrailingComment = Record[Idx++];
7577 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007578 Comments.push_back(new (Context) RawComment(
7579 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7580 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 break;
7582 }
7583 }
7584 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007585 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007586 }
7587 Context.Comments.addCommentsToFront(Comments);
7588}
7589
7590void ASTReader::finishPendingActions() {
7591 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007592 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7593 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007594 // If any identifiers with corresponding top-level declarations have
7595 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007596 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7597 TopLevelDeclsMap;
7598 TopLevelDeclsMap TopLevelDecls;
7599
Guy Benyei11169dd2012-12-18 14:30:41 +00007600 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007601 // FIXME: std::move
7602 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7603 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007604 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007605
7606 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 }
7608
7609 // Load pending declaration chains.
7610 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7611 loadPendingDeclChain(PendingDeclChains[I]);
7612 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7613 }
7614 PendingDeclChains.clear();
7615
Douglas Gregor6168bd22013-02-18 15:53:43 +00007616 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007617 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7618 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007619 IdentifierInfo *II = TLD->first;
7620 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007621 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007622 }
7623 }
7624
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 // Load any pending macro definitions.
7626 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007627 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7628 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7629 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7630 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007631 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007632 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007633 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7634 if (Info.M->Kind != MK_Module)
7635 resolvePendingMacro(II, Info);
7636 }
7637 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007638 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007639 ++IDIdx) {
7640 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7641 if (Info.M->Kind == MK_Module)
7642 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 }
7644 }
7645 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007646
7647 // Wire up the DeclContexts for Decls that we delayed setting until
7648 // recursive loading is completed.
7649 while (!PendingDeclContextInfos.empty()) {
7650 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7651 PendingDeclContextInfos.pop_front();
7652 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7653 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7654 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7655 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007656
7657 // For each declaration from a merged context, check that the canonical
7658 // definition of that context also contains a declaration of the same
7659 // entity.
7660 while (!PendingOdrMergeChecks.empty()) {
7661 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7662
7663 // FIXME: Skip over implicit declarations for now. This matters for things
7664 // like implicitly-declared special member functions. This isn't entirely
7665 // correct; we can end up with multiple unmerged declarations of the same
7666 // implicit entity.
7667 if (D->isImplicit())
7668 continue;
7669
7670 DeclContext *CanonDef = D->getDeclContext();
7671 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7672
7673 bool Found = false;
7674 const Decl *DCanon = D->getCanonicalDecl();
7675
7676 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7677 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7678 !Found && I != E; ++I) {
7679 for (Decl::redecl_iterator RI = (*I)->redecls_begin(),
7680 RE = (*I)->redecls_end();
7681 RI != RE; ++RI) {
7682 if ((*RI)->getLexicalDeclContext() == CanonDef) {
7683 // This declaration is present in the canonical definition. If it's
7684 // in the same redecl chain, it's the one we're looking for.
7685 if ((*RI)->getCanonicalDecl() == DCanon)
7686 Found = true;
7687 else
7688 Candidates.push_back(cast<NamedDecl>(*RI));
7689 break;
7690 }
7691 }
7692 }
7693
7694 if (!Found) {
7695 D->setInvalidDecl();
7696
7697 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7698 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7699 << D << D->getOwningModule()->getFullModuleName()
7700 << CanonDef << !CanonDefModule
7701 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7702
7703 if (Candidates.empty())
7704 Diag(cast<Decl>(CanonDef)->getLocation(),
7705 diag::note_module_odr_violation_no_possible_decls) << D;
7706 else {
7707 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7708 Diag(Candidates[I]->getLocation(),
7709 diag::note_module_odr_violation_possible_decl)
7710 << Candidates[I];
7711 }
7712 }
7713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 }
7715
7716 // If we deserialized any C++ or Objective-C class definitions, any
7717 // Objective-C protocol definitions, or any redeclarable templates, make sure
7718 // that all redeclarations point to the definitions. Note that this can only
7719 // happen now, after the redeclaration chains have been fully wired.
7720 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7721 DEnd = PendingDefinitions.end();
7722 D != DEnd; ++D) {
7723 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7724 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7725 // Make sure that the TagType points at the definition.
7726 const_cast<TagType*>(TagT)->decl = TD;
7727 }
7728
7729 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7730 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7731 REnd = RD->redecls_end();
7732 R != REnd; ++R)
7733 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7734
7735 }
7736
7737 continue;
7738 }
7739
7740 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7741 // Make sure that the ObjCInterfaceType points at the definition.
7742 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7743 ->Decl = ID;
7744
7745 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7746 REnd = ID->redecls_end();
7747 R != REnd; ++R)
7748 R->Data = ID->Data;
7749
7750 continue;
7751 }
7752
7753 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7754 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7755 REnd = PD->redecls_end();
7756 R != REnd; ++R)
7757 R->Data = PD->Data;
7758
7759 continue;
7760 }
7761
7762 RedeclarableTemplateDecl *RTD
7763 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7764 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7765 REnd = RTD->redecls_end();
7766 R != REnd; ++R)
7767 R->Common = RTD->Common;
7768 }
7769 PendingDefinitions.clear();
7770
7771 // Load the bodies of any functions or methods we've encountered. We do
7772 // this now (delayed) so that we can be sure that the declaration chains
7773 // have been fully wired up.
7774 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7775 PBEnd = PendingBodies.end();
7776 PB != PBEnd; ++PB) {
7777 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7778 // FIXME: Check for =delete/=default?
7779 // FIXME: Complain about ODR violations here?
7780 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7781 FD->setLazyBody(PB->second);
7782 continue;
7783 }
7784
7785 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7786 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7787 MD->setLazyBody(PB->second);
7788 }
7789 PendingBodies.clear();
7790}
7791
7792void ASTReader::FinishedDeserializing() {
7793 assert(NumCurrentElementsDeserializing &&
7794 "FinishedDeserializing not paired with StartedDeserializing");
7795 if (NumCurrentElementsDeserializing == 1) {
7796 // We decrease NumCurrentElementsDeserializing only after pending actions
7797 // are finished, to avoid recursively re-calling finishPendingActions().
7798 finishPendingActions();
7799 }
7800 --NumCurrentElementsDeserializing;
7801
7802 if (NumCurrentElementsDeserializing == 0 &&
7803 Consumer && !PassingDeclsToConsumer) {
7804 // Guard variable to avoid recursively redoing the process of passing
7805 // decls to consumer.
7806 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7807 true);
7808
7809 while (!InterestingDecls.empty()) {
7810 // We are not in recursive loading, so it's safe to pass the "interesting"
7811 // decls to the consumer.
7812 Decl *D = InterestingDecls.front();
7813 InterestingDecls.pop_front();
7814 PassInterestingDeclToConsumer(D);
7815 }
7816 }
7817}
7818
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007819void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007820 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007821
7822 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7823 SemaObj->TUScope->AddDecl(D);
7824 } else if (SemaObj->TUScope) {
7825 // Adding the decl to IdResolver may have failed because it was already in
7826 // (even though it was not added in scope). If it is already in, make sure
7827 // it gets in the scope as well.
7828 if (std::find(SemaObj->IdResolver.begin(Name),
7829 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7830 SemaObj->TUScope->AddDecl(D);
7831 }
7832}
7833
Guy Benyei11169dd2012-12-18 14:30:41 +00007834ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7835 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007836 bool AllowASTWithCompilerErrors,
7837 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007838 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007839 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007840 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7841 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7842 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7843 Consumer(0), ModuleMgr(PP.getFileManager()),
7844 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007845 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007846 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007847 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007848 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7850 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007851 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7852 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7853 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007854 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7855 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7856 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7858 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7859 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7860 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007861 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007862{
7863 SourceMgr.setExternalSLocEntrySource(this);
7864}
7865
7866ASTReader::~ASTReader() {
7867 for (DeclContextVisibleUpdatesPending::iterator
7868 I = PendingVisibleUpdates.begin(),
7869 E = PendingVisibleUpdates.end();
7870 I != E; ++I) {
7871 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7872 F = I->second.end();
7873 J != F; ++J)
7874 delete J->first;
7875 }
7876}