blob: a0ee3d37c5cef7b989f8fe450f2b56e6e8b435af [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
Ben Langmuircb69b572014-03-07 06:40:32 +000063
64//===----------------------------------------------------------------------===//
65// ChainedASTReaderListener implementation
66//===----------------------------------------------------------------------===//
67
68bool
69ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
70 return First->ReadFullVersionInformation(FullVersion) ||
71 Second->ReadFullVersionInformation(FullVersion);
72}
73bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
74 bool Complain) {
75 return First->ReadLanguageOptions(LangOpts, Complain) ||
76 Second->ReadLanguageOptions(LangOpts, Complain);
77}
78bool
79ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
80 bool Complain) {
81 return First->ReadTargetOptions(TargetOpts, Complain) ||
82 Second->ReadTargetOptions(TargetOpts, Complain);
83}
84bool ChainedASTReaderListener::ReadDiagnosticOptions(
85 const DiagnosticOptions &DiagOpts, bool Complain) {
86 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
87 Second->ReadDiagnosticOptions(DiagOpts, Complain);
88}
89bool
90ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
91 bool Complain) {
92 return First->ReadFileSystemOptions(FSOpts, Complain) ||
93 Second->ReadFileSystemOptions(FSOpts, Complain);
94}
95
96bool ChainedASTReaderListener::ReadHeaderSearchOptions(
97 const HeaderSearchOptions &HSOpts, bool Complain) {
98 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
99 Second->ReadHeaderSearchOptions(HSOpts, Complain);
100}
101bool ChainedASTReaderListener::ReadPreprocessorOptions(
102 const PreprocessorOptions &PPOpts, bool Complain,
103 std::string &SuggestedPredefines) {
104 return First->ReadPreprocessorOptions(PPOpts, Complain,
105 SuggestedPredefines) ||
106 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
107}
108void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
109 unsigned Value) {
110 First->ReadCounter(M, Value);
111 Second->ReadCounter(M, Value);
112}
113bool ChainedASTReaderListener::needsInputFileVisitation() {
114 return First->needsInputFileVisitation() ||
115 Second->needsInputFileVisitation();
116}
117bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
118 return First->needsSystemInputFileVisitation() ||
119 Second->needsSystemInputFileVisitation();
120}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000121void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
122 First->visitModuleFile(Filename);
123 Second->visitModuleFile(Filename);
124}
Ben Langmuircb69b572014-03-07 06:40:32 +0000125bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000126 bool isSystem,
127 bool isOverridden) {
128 return First->visitInputFile(Filename, isSystem, isOverridden) ||
129 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000130}
131
Guy Benyei11169dd2012-12-18 14:30:41 +0000132//===----------------------------------------------------------------------===//
133// PCH validator implementation
134//===----------------------------------------------------------------------===//
135
136ASTReaderListener::~ASTReaderListener() {}
137
138/// \brief Compare the given set of language options against an existing set of
139/// language options.
140///
141/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
142///
143/// \returns true if the languagae options mis-match, false otherwise.
144static bool checkLanguageOptions(const LangOptions &LangOpts,
145 const LangOptions &ExistingLangOpts,
146 DiagnosticsEngine *Diags) {
147#define LANGOPT(Name, Bits, Default, Description) \
148 if (ExistingLangOpts.Name != LangOpts.Name) { \
149 if (Diags) \
150 Diags->Report(diag::err_pch_langopt_mismatch) \
151 << Description << LangOpts.Name << ExistingLangOpts.Name; \
152 return true; \
153 }
154
155#define VALUE_LANGOPT(Name, Bits, Default, Description) \
156 if (ExistingLangOpts.Name != LangOpts.Name) { \
157 if (Diags) \
158 Diags->Report(diag::err_pch_langopt_value_mismatch) \
159 << Description; \
160 return true; \
161 }
162
163#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
164 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_value_mismatch) \
167 << Description; \
168 return true; \
169 }
170
171#define BENIGN_LANGOPT(Name, Bits, Default, Description)
172#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
173#include "clang/Basic/LangOptions.def"
174
175 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
176 if (Diags)
177 Diags->Report(diag::err_pch_langopt_value_mismatch)
178 << "target Objective-C runtime";
179 return true;
180 }
181
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000182 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
183 LangOpts.CommentOpts.BlockCommandNames) {
184 if (Diags)
185 Diags->Report(diag::err_pch_langopt_value_mismatch)
186 << "block command names";
187 return true;
188 }
189
Guy Benyei11169dd2012-12-18 14:30:41 +0000190 return false;
191}
192
193/// \brief Compare the given set of target options against an existing set of
194/// target options.
195///
196/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
197///
198/// \returns true if the target options mis-match, false otherwise.
199static bool checkTargetOptions(const TargetOptions &TargetOpts,
200 const TargetOptions &ExistingTargetOpts,
201 DiagnosticsEngine *Diags) {
202#define CHECK_TARGET_OPT(Field, Name) \
203 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
204 if (Diags) \
205 Diags->Report(diag::err_pch_targetopt_mismatch) \
206 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
207 return true; \
208 }
209
210 CHECK_TARGET_OPT(Triple, "target");
211 CHECK_TARGET_OPT(CPU, "target CPU");
212 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000213 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
214#undef CHECK_TARGET_OPT
215
216 // Compare feature sets.
217 SmallVector<StringRef, 4> ExistingFeatures(
218 ExistingTargetOpts.FeaturesAsWritten.begin(),
219 ExistingTargetOpts.FeaturesAsWritten.end());
220 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
221 TargetOpts.FeaturesAsWritten.end());
222 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
223 std::sort(ReadFeatures.begin(), ReadFeatures.end());
224
225 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
226 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
227 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
228 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
229 ++ExistingIdx;
230 ++ReadIdx;
231 continue;
232 }
233
234 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
235 if (Diags)
236 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
237 << false << ReadFeatures[ReadIdx];
238 return true;
239 }
240
241 if (Diags)
242 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
243 << true << ExistingFeatures[ExistingIdx];
244 return true;
245 }
246
247 if (ExistingIdx < ExistingN) {
248 if (Diags)
249 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
250 << true << ExistingFeatures[ExistingIdx];
251 return true;
252 }
253
254 if (ReadIdx < ReadN) {
255 if (Diags)
256 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
257 << false << ReadFeatures[ReadIdx];
258 return true;
259 }
260
261 return false;
262}
263
264bool
265PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
266 bool Complain) {
267 const LangOptions &ExistingLangOpts = PP.getLangOpts();
268 return checkLanguageOptions(LangOpts, ExistingLangOpts,
269 Complain? &Reader.Diags : 0);
270}
271
272bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
273 bool Complain) {
274 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
275 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
276 Complain? &Reader.Diags : 0);
277}
278
279namespace {
280 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
281 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000282 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
283 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000284}
285
286/// \brief Collect the macro definitions provided by the given preprocessor
287/// options.
288static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
289 MacroDefinitionsMap &Macros,
290 SmallVectorImpl<StringRef> *MacroNames = 0){
291 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
292 StringRef Macro = PPOpts.Macros[I].first;
293 bool IsUndef = PPOpts.Macros[I].second;
294
295 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
296 StringRef MacroName = MacroPair.first;
297 StringRef MacroBody = MacroPair.second;
298
299 // For an #undef'd macro, we only care about the name.
300 if (IsUndef) {
301 if (MacroNames && !Macros.count(MacroName))
302 MacroNames->push_back(MacroName);
303
304 Macros[MacroName] = std::make_pair("", true);
305 continue;
306 }
307
308 // For a #define'd macro, figure out the actual definition.
309 if (MacroName.size() == Macro.size())
310 MacroBody = "1";
311 else {
312 // Note: GCC drops anything following an end-of-line character.
313 StringRef::size_type End = MacroBody.find_first_of("\n\r");
314 MacroBody = MacroBody.substr(0, End);
315 }
316
317 if (MacroNames && !Macros.count(MacroName))
318 MacroNames->push_back(MacroName);
319 Macros[MacroName] = std::make_pair(MacroBody, false);
320 }
321}
322
323/// \brief Check the preprocessor options deserialized from the control block
324/// against the preprocessor options in an existing preprocessor.
325///
326/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
327static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
328 const PreprocessorOptions &ExistingPPOpts,
329 DiagnosticsEngine *Diags,
330 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000331 std::string &SuggestedPredefines,
332 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 // Check macro definitions.
334 MacroDefinitionsMap ASTFileMacros;
335 collectMacroDefinitions(PPOpts, ASTFileMacros);
336 MacroDefinitionsMap ExistingMacros;
337 SmallVector<StringRef, 4> ExistingMacroNames;
338 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
339
340 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
341 // Dig out the macro definition in the existing preprocessor options.
342 StringRef MacroName = ExistingMacroNames[I];
343 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
344
345 // Check whether we know anything about this macro name or not.
346 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
347 = ASTFileMacros.find(MacroName);
348 if (Known == ASTFileMacros.end()) {
349 // FIXME: Check whether this identifier was referenced anywhere in the
350 // AST file. If so, we should reject the AST file. Unfortunately, this
351 // information isn't in the control block. What shall we do about it?
352
353 if (Existing.second) {
354 SuggestedPredefines += "#undef ";
355 SuggestedPredefines += MacroName.str();
356 SuggestedPredefines += '\n';
357 } else {
358 SuggestedPredefines += "#define ";
359 SuggestedPredefines += MacroName.str();
360 SuggestedPredefines += ' ';
361 SuggestedPredefines += Existing.first.str();
362 SuggestedPredefines += '\n';
363 }
364 continue;
365 }
366
367 // If the macro was defined in one but undef'd in the other, we have a
368 // conflict.
369 if (Existing.second != Known->second.second) {
370 if (Diags) {
371 Diags->Report(diag::err_pch_macro_def_undef)
372 << MacroName << Known->second.second;
373 }
374 return true;
375 }
376
377 // If the macro was #undef'd in both, or if the macro bodies are identical,
378 // it's fine.
379 if (Existing.second || Existing.first == Known->second.first)
380 continue;
381
382 // The macro bodies differ; complain.
383 if (Diags) {
384 Diags->Report(diag::err_pch_macro_def_conflict)
385 << MacroName << Known->second.first << Existing.first;
386 }
387 return true;
388 }
389
390 // Check whether we're using predefines.
391 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
392 if (Diags) {
393 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
394 }
395 return true;
396 }
397
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000398 // Detailed record is important since it is used for the module cache hash.
399 if (LangOpts.Modules &&
400 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
401 if (Diags) {
402 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
403 }
404 return true;
405 }
406
Guy Benyei11169dd2012-12-18 14:30:41 +0000407 // Compute the #include and #include_macros lines we need.
408 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
409 StringRef File = ExistingPPOpts.Includes[I];
410 if (File == ExistingPPOpts.ImplicitPCHInclude)
411 continue;
412
413 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
414 != PPOpts.Includes.end())
415 continue;
416
417 SuggestedPredefines += "#include \"";
418 SuggestedPredefines +=
419 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
420 SuggestedPredefines += "\"\n";
421 }
422
423 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
424 StringRef File = ExistingPPOpts.MacroIncludes[I];
425 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
426 File)
427 != PPOpts.MacroIncludes.end())
428 continue;
429
430 SuggestedPredefines += "#__include_macros \"";
431 SuggestedPredefines +=
432 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
433 SuggestedPredefines += "\"\n##\n";
434 }
435
436 return false;
437}
438
439bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
440 bool Complain,
441 std::string &SuggestedPredefines) {
442 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
443
444 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
445 Complain? &Reader.Diags : 0,
446 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000447 SuggestedPredefines,
448 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000449}
450
Guy Benyei11169dd2012-12-18 14:30:41 +0000451void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
452 PP.setCounterValue(Value);
453}
454
455//===----------------------------------------------------------------------===//
456// AST reader implementation
457//===----------------------------------------------------------------------===//
458
459void
460ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
461 DeserializationListener = Listener;
462}
463
464
465
466unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
467 return serialization::ComputeHash(Sel);
468}
469
470
471std::pair<unsigned, unsigned>
472ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
473 using namespace clang::io;
474 unsigned KeyLen = ReadUnalignedLE16(d);
475 unsigned DataLen = ReadUnalignedLE16(d);
476 return std::make_pair(KeyLen, DataLen);
477}
478
479ASTSelectorLookupTrait::internal_key_type
480ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
481 using namespace clang::io;
482 SelectorTable &SelTable = Reader.getContext().Selectors;
483 unsigned N = ReadUnalignedLE16(d);
484 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000485 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000486 if (N == 0)
487 return SelTable.getNullarySelector(FirstII);
488 else if (N == 1)
489 return SelTable.getUnarySelector(FirstII);
490
491 SmallVector<IdentifierInfo *, 16> Args;
492 Args.push_back(FirstII);
493 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000494 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000495
496 return SelTable.getSelector(N, Args.data());
497}
498
499ASTSelectorLookupTrait::data_type
500ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
501 unsigned DataLen) {
502 using namespace clang::io;
503
504 data_type Result;
505
506 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000507 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
508 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
509 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
510 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
511 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
512 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000513
514 // Load instance methods
515 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
516 if (ObjCMethodDecl *Method
517 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
518 Result.Instance.push_back(Method);
519 }
520
521 // Load factory methods
522 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
523 if (ObjCMethodDecl *Method
524 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
525 Result.Factory.push_back(Method);
526 }
527
528 return Result;
529}
530
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000531unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
532 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000533}
534
535std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000536ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 using namespace clang::io;
538 unsigned DataLen = ReadUnalignedLE16(d);
539 unsigned KeyLen = ReadUnalignedLE16(d);
540 return std::make_pair(KeyLen, DataLen);
541}
542
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000543ASTIdentifierLookupTraitBase::internal_key_type
544ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000545 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000546 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000547}
548
Douglas Gregordcf25082013-02-11 18:16:18 +0000549/// \brief Whether the given identifier is "interesting".
550static bool isInterestingIdentifier(IdentifierInfo &II) {
551 return II.isPoisoned() ||
552 II.isExtensionToken() ||
553 II.getObjCOrBuiltinID() ||
554 II.hasRevertedTokenIDToIdentifier() ||
555 II.hadMacroDefinition() ||
556 II.getFETokenInfo<void>();
557}
558
Guy Benyei11169dd2012-12-18 14:30:41 +0000559IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
560 const unsigned char* d,
561 unsigned DataLen) {
562 using namespace clang::io;
563 unsigned RawID = ReadUnalignedLE32(d);
564 bool IsInteresting = RawID & 0x01;
565
566 // Wipe out the "is interesting" bit.
567 RawID = RawID >> 1;
568
569 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
570 if (!IsInteresting) {
571 // For uninteresting identifiers, just build the IdentifierInfo
572 // and associate it with the persistent ID.
573 IdentifierInfo *II = KnownII;
574 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000575 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 KnownII = II;
577 }
578 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000579 if (!II->isFromAST()) {
580 bool WasInteresting = isInterestingIdentifier(*II);
581 II->setIsFromAST();
582 if (WasInteresting)
583 II->setChangedSinceDeserialization();
584 }
585 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 return II;
587 }
588
589 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
590 unsigned Bits = ReadUnalignedLE16(d);
591 bool CPlusPlusOperatorKeyword = Bits & 0x01;
592 Bits >>= 1;
593 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
594 Bits >>= 1;
595 bool Poisoned = Bits & 0x01;
596 Bits >>= 1;
597 bool ExtensionToken = Bits & 0x01;
598 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000599 bool hasSubmoduleMacros = Bits & 0x01;
600 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 bool hadMacroDefinition = Bits & 0x01;
602 Bits >>= 1;
603
604 assert(Bits == 0 && "Extra bits in the identifier?");
605 DataLen -= 8;
606
607 // Build the IdentifierInfo itself and link the identifier ID with
608 // the new IdentifierInfo.
609 IdentifierInfo *II = KnownII;
610 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000611 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000612 KnownII = II;
613 }
614 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000615 if (!II->isFromAST()) {
616 bool WasInteresting = isInterestingIdentifier(*II);
617 II->setIsFromAST();
618 if (WasInteresting)
619 II->setChangedSinceDeserialization();
620 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000621
622 // Set or check the various bits in the IdentifierInfo structure.
623 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000624 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000625 II->RevertTokenIDToIdentifier();
626 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
627 assert(II->isExtensionToken() == ExtensionToken &&
628 "Incorrect extension token flag");
629 (void)ExtensionToken;
630 if (Poisoned)
631 II->setIsPoisoned(true);
632 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
633 "Incorrect C++ operator keyword flag");
634 (void)CPlusPlusOperatorKeyword;
635
636 // If this identifier is a macro, deserialize the macro
637 // definition.
638 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000639 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
640 DataLen -= 4;
641 SmallVector<uint32_t, 8> LocalMacroIDs;
642 if (hasSubmoduleMacros) {
643 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
644 DataLen -= 4;
645 LocalMacroIDs.push_back(LocalMacroID);
646 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000647 DataLen -= 4;
648 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000649
650 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000651 // Macro definitions are stored from newest to oldest, so reverse them
652 // before registering them.
653 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000654 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000655 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
656 unsigned Size = 1;
657
658 static const uint32_t HasOverridesFlag = 0x80000000U;
659 if (I + 1 != E && (I[1] & HasOverridesFlag))
660 Size += 1 + (I[1] & ~HasOverridesFlag);
661
662 MacroSizes.push_back(Size);
663 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000664 }
Richard Smith49f906a2014-03-01 00:08:04 +0000665
666 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
667 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
668 SE = MacroSizes.rend();
669 SI != SE; ++SI) {
670 I -= *SI;
671
672 uint32_t LocalMacroID = *I;
673 llvm::ArrayRef<uint32_t> Overrides;
674 if (*SI != 1)
675 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
676 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
677 }
678 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000679 } else {
680 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
681 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000682 }
683
684 Reader.SetIdentifierInfo(ID, II);
685
686 // Read all of the declarations visible at global scope with this
687 // name.
688 if (DataLen > 0) {
689 SmallVector<uint32_t, 4> DeclIDs;
690 for (; DataLen > 0; DataLen -= 4)
691 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
692 Reader.SetGloballyVisibleDecls(II, DeclIDs);
693 }
694
695 return II;
696}
697
698unsigned
699ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
700 llvm::FoldingSetNodeID ID;
701 ID.AddInteger(Key.Kind);
702
703 switch (Key.Kind) {
704 case DeclarationName::Identifier:
705 case DeclarationName::CXXLiteralOperatorName:
706 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
707 break;
708 case DeclarationName::ObjCZeroArgSelector:
709 case DeclarationName::ObjCOneArgSelector:
710 case DeclarationName::ObjCMultiArgSelector:
711 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
712 break;
713 case DeclarationName::CXXOperatorName:
714 ID.AddInteger((OverloadedOperatorKind)Key.Data);
715 break;
716 case DeclarationName::CXXConstructorName:
717 case DeclarationName::CXXDestructorName:
718 case DeclarationName::CXXConversionFunctionName:
719 case DeclarationName::CXXUsingDirective:
720 break;
721 }
722
723 return ID.ComputeHash();
724}
725
726ASTDeclContextNameLookupTrait::internal_key_type
727ASTDeclContextNameLookupTrait::GetInternalKey(
728 const external_key_type& Name) const {
729 DeclNameKey Key;
730 Key.Kind = Name.getNameKind();
731 switch (Name.getNameKind()) {
732 case DeclarationName::Identifier:
733 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
734 break;
735 case DeclarationName::ObjCZeroArgSelector:
736 case DeclarationName::ObjCOneArgSelector:
737 case DeclarationName::ObjCMultiArgSelector:
738 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
739 break;
740 case DeclarationName::CXXOperatorName:
741 Key.Data = Name.getCXXOverloadedOperator();
742 break;
743 case DeclarationName::CXXLiteralOperatorName:
744 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
745 break;
746 case DeclarationName::CXXConstructorName:
747 case DeclarationName::CXXDestructorName:
748 case DeclarationName::CXXConversionFunctionName:
749 case DeclarationName::CXXUsingDirective:
750 Key.Data = 0;
751 break;
752 }
753
754 return Key;
755}
756
757std::pair<unsigned, unsigned>
758ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
759 using namespace clang::io;
760 unsigned KeyLen = ReadUnalignedLE16(d);
761 unsigned DataLen = ReadUnalignedLE16(d);
762 return std::make_pair(KeyLen, DataLen);
763}
764
765ASTDeclContextNameLookupTrait::internal_key_type
766ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
767 using namespace clang::io;
768
769 DeclNameKey Key;
770 Key.Kind = (DeclarationName::NameKind)*d++;
771 switch (Key.Kind) {
772 case DeclarationName::Identifier:
773 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
774 break;
775 case DeclarationName::ObjCZeroArgSelector:
776 case DeclarationName::ObjCOneArgSelector:
777 case DeclarationName::ObjCMultiArgSelector:
778 Key.Data =
779 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
780 .getAsOpaquePtr();
781 break;
782 case DeclarationName::CXXOperatorName:
783 Key.Data = *d++; // OverloadedOperatorKind
784 break;
785 case DeclarationName::CXXLiteralOperatorName:
786 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
787 break;
788 case DeclarationName::CXXConstructorName:
789 case DeclarationName::CXXDestructorName:
790 case DeclarationName::CXXConversionFunctionName:
791 case DeclarationName::CXXUsingDirective:
792 Key.Data = 0;
793 break;
794 }
795
796 return Key;
797}
798
799ASTDeclContextNameLookupTrait::data_type
800ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
801 const unsigned char* d,
802 unsigned DataLen) {
803 using namespace clang::io;
804 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000805 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
806 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 return std::make_pair(Start, Start + NumDecls);
808}
809
810bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000811 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 const std::pair<uint64_t, uint64_t> &Offsets,
813 DeclContextInfo &Info) {
814 SavedStreamPosition SavedPosition(Cursor);
815 // First the lexical decls.
816 if (Offsets.first != 0) {
817 Cursor.JumpToBit(Offsets.first);
818
819 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000820 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000822 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 if (RecCode != DECL_CONTEXT_LEXICAL) {
824 Error("Expected lexical block");
825 return true;
826 }
827
Chris Lattner0e6c9402013-01-20 02:38:54 +0000828 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
829 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 // Now the lookup table.
833 if (Offsets.second != 0) {
834 Cursor.JumpToBit(Offsets.second);
835
836 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000837 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000839 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 if (RecCode != DECL_CONTEXT_VISIBLE) {
841 Error("Expected visible lookup table block");
842 return true;
843 }
Richard Smith52e3fba2014-03-11 07:17:35 +0000844 Info.NameLookupTableData
845 = ASTDeclContextNameLookupTable::Create(
846 (const unsigned char *)Blob.data() + Record[0],
847 (const unsigned char *)Blob.data(),
848 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 }
850
851 return false;
852}
853
854void ASTReader::Error(StringRef Msg) {
855 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000856 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
857 Diag(diag::note_module_cache_path)
858 << PP.getHeaderSearchInfo().getModuleCachePath();
859 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000860}
861
862void ASTReader::Error(unsigned DiagID,
863 StringRef Arg1, StringRef Arg2) {
864 if (Diags.isDiagnosticInFlight())
865 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
866 else
867 Diag(DiagID) << Arg1 << Arg2;
868}
869
870//===----------------------------------------------------------------------===//
871// Source Manager Deserialization
872//===----------------------------------------------------------------------===//
873
874/// \brief Read the line table in the source manager block.
875/// \returns true if there was an error.
876bool ASTReader::ParseLineTable(ModuleFile &F,
877 SmallVectorImpl<uint64_t> &Record) {
878 unsigned Idx = 0;
879 LineTableInfo &LineTable = SourceMgr.getLineTable();
880
881 // Parse the file names
882 std::map<int, int> FileIDs;
883 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
884 // Extract the file name
885 unsigned FilenameLen = Record[Idx++];
886 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
887 Idx += FilenameLen;
888 MaybeAddSystemRootToFilename(F, Filename);
889 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
890 }
891
892 // Parse the line entries
893 std::vector<LineEntry> Entries;
894 while (Idx < Record.size()) {
895 int FID = Record[Idx++];
896 assert(FID >= 0 && "Serialized line entries for non-local file.");
897 // Remap FileID from 1-based old view.
898 FID += F.SLocEntryBaseID - 1;
899
900 // Extract the line entries
901 unsigned NumEntries = Record[Idx++];
902 assert(NumEntries && "Numentries is 00000");
903 Entries.clear();
904 Entries.reserve(NumEntries);
905 for (unsigned I = 0; I != NumEntries; ++I) {
906 unsigned FileOffset = Record[Idx++];
907 unsigned LineNo = Record[Idx++];
908 int FilenameID = FileIDs[Record[Idx++]];
909 SrcMgr::CharacteristicKind FileKind
910 = (SrcMgr::CharacteristicKind)Record[Idx++];
911 unsigned IncludeOffset = Record[Idx++];
912 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
913 FileKind, IncludeOffset));
914 }
915 LineTable.AddEntry(FileID::get(FID), Entries);
916 }
917
918 return false;
919}
920
921/// \brief Read a source manager block
922bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
923 using namespace SrcMgr;
924
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000925 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000926
927 // Set the source-location entry cursor to the current position in
928 // the stream. This cursor will be used to read the contents of the
929 // source manager block initially, and then lazily read
930 // source-location entries as needed.
931 SLocEntryCursor = F.Stream;
932
933 // The stream itself is going to skip over the source manager block.
934 if (F.Stream.SkipBlock()) {
935 Error("malformed block record in AST file");
936 return true;
937 }
938
939 // Enter the source manager block.
940 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
941 Error("malformed source manager block record in AST file");
942 return true;
943 }
944
945 RecordData Record;
946 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000947 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
948
949 switch (E.Kind) {
950 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
951 case llvm::BitstreamEntry::Error:
952 Error("malformed block record in AST file");
953 return true;
954 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000956 case llvm::BitstreamEntry::Record:
957 // The interesting case.
958 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000960
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000963 StringRef Blob;
964 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 default: // Default behavior: ignore.
966 break;
967
968 case SM_SLOC_FILE_ENTRY:
969 case SM_SLOC_BUFFER_ENTRY:
970 case SM_SLOC_EXPANSION_ENTRY:
971 // Once we hit one of the source location entries, we're done.
972 return false;
973 }
974 }
975}
976
977/// \brief If a header file is not found at the path that we expect it to be
978/// and the PCH file was moved from its original location, try to resolve the
979/// file by assuming that header+PCH were moved together and the header is in
980/// the same place relative to the PCH.
981static std::string
982resolveFileRelativeToOriginalDir(const std::string &Filename,
983 const std::string &OriginalDir,
984 const std::string &CurrDir) {
985 assert(OriginalDir != CurrDir &&
986 "No point trying to resolve the file if the PCH dir didn't change");
987 using namespace llvm::sys;
988 SmallString<128> filePath(Filename);
989 fs::make_absolute(filePath);
990 assert(path::is_absolute(OriginalDir));
991 SmallString<128> currPCHPath(CurrDir);
992
993 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
994 fileDirE = path::end(path::parent_path(filePath));
995 path::const_iterator origDirI = path::begin(OriginalDir),
996 origDirE = path::end(OriginalDir);
997 // Skip the common path components from filePath and OriginalDir.
998 while (fileDirI != fileDirE && origDirI != origDirE &&
999 *fileDirI == *origDirI) {
1000 ++fileDirI;
1001 ++origDirI;
1002 }
1003 for (; origDirI != origDirE; ++origDirI)
1004 path::append(currPCHPath, "..");
1005 path::append(currPCHPath, fileDirI, fileDirE);
1006 path::append(currPCHPath, path::filename(Filename));
1007 return currPCHPath.str();
1008}
1009
1010bool ASTReader::ReadSLocEntry(int ID) {
1011 if (ID == 0)
1012 return false;
1013
1014 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1015 Error("source location entry ID out-of-range for AST file");
1016 return true;
1017 }
1018
1019 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1020 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001021 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 unsigned BaseOffset = F->SLocEntryBaseOffset;
1023
1024 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001025 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1026 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 Error("incorrectly-formatted source location entry in AST file");
1028 return true;
1029 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001030
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001032 StringRef Blob;
1033 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 default:
1035 Error("incorrectly-formatted source location entry in AST file");
1036 return true;
1037
1038 case SM_SLOC_FILE_ENTRY: {
1039 // We will detect whether a file changed and return 'Failure' for it, but
1040 // we will also try to fail gracefully by setting up the SLocEntry.
1041 unsigned InputID = Record[4];
1042 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001043 const FileEntry *File = IF.getFile();
1044 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001045
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001046 // Note that we only check if a File was returned. If it was out-of-date
1047 // we have complained but we will continue creating a FileID to recover
1048 // gracefully.
1049 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 return true;
1051
1052 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1053 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1054 // This is the module's main file.
1055 IncludeLoc = getImportLocation(F);
1056 }
1057 SrcMgr::CharacteristicKind
1058 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1059 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1060 ID, BaseOffset + Record[0]);
1061 SrcMgr::FileInfo &FileInfo =
1062 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1063 FileInfo.NumCreatedFIDs = Record[5];
1064 if (Record[3])
1065 FileInfo.setHasLineDirectives();
1066
1067 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1068 unsigned NumFileDecls = Record[7];
1069 if (NumFileDecls) {
1070 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1071 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1072 NumFileDecls));
1073 }
1074
1075 const SrcMgr::ContentCache *ContentCache
1076 = SourceMgr.getOrCreateContentCache(File,
1077 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1078 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1079 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1080 unsigned Code = SLocEntryCursor.ReadCode();
1081 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001082 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001083
1084 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1085 Error("AST record has invalid code");
1086 return true;
1087 }
1088
1089 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001090 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001091 SourceMgr.overrideFileContents(File, Buffer);
1092 }
1093
1094 break;
1095 }
1096
1097 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001098 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 unsigned Offset = Record[0];
1100 SrcMgr::CharacteristicKind
1101 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1102 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1103 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1104 IncludeLoc = getImportLocation(F);
1105 }
1106 unsigned Code = SLocEntryCursor.ReadCode();
1107 Record.clear();
1108 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001109 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001110
1111 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1112 Error("AST record has invalid code");
1113 return true;
1114 }
1115
1116 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001117 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1119 BaseOffset + Offset, IncludeLoc);
1120 break;
1121 }
1122
1123 case SM_SLOC_EXPANSION_ENTRY: {
1124 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1125 SourceMgr.createExpansionLoc(SpellingLoc,
1126 ReadSourceLocation(*F, Record[2]),
1127 ReadSourceLocation(*F, Record[3]),
1128 Record[4],
1129 ID,
1130 BaseOffset + Record[0]);
1131 break;
1132 }
1133 }
1134
1135 return false;
1136}
1137
1138std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1139 if (ID == 0)
1140 return std::make_pair(SourceLocation(), "");
1141
1142 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1143 Error("source location entry ID out-of-range for AST file");
1144 return std::make_pair(SourceLocation(), "");
1145 }
1146
1147 // Find which module file this entry lands in.
1148 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1149 if (M->Kind != MK_Module)
1150 return std::make_pair(SourceLocation(), "");
1151
1152 // FIXME: Can we map this down to a particular submodule? That would be
1153 // ideal.
1154 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1155}
1156
1157/// \brief Find the location where the module F is imported.
1158SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1159 if (F->ImportLoc.isValid())
1160 return F->ImportLoc;
1161
1162 // Otherwise we have a PCH. It's considered to be "imported" at the first
1163 // location of its includer.
1164 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1165 // Main file is the importer. We assume that it is the first entry in the
1166 // entry table. We can't ask the manager, because at the time of PCH loading
1167 // the main file entry doesn't exist yet.
1168 // The very first entry is the invalid instantiation loc, which takes up
1169 // offsets 0 and 1.
1170 return SourceLocation::getFromRawEncoding(2U);
1171 }
1172 //return F->Loaders[0]->FirstLoc;
1173 return F->ImportedBy[0]->FirstLoc;
1174}
1175
1176/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1177/// specified cursor. Read the abbreviations that are at the top of the block
1178/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001179bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 if (Cursor.EnterSubBlock(BlockID)) {
1181 Error("malformed block record in AST file");
1182 return Failure;
1183 }
1184
1185 while (true) {
1186 uint64_t Offset = Cursor.GetCurrentBitNo();
1187 unsigned Code = Cursor.ReadCode();
1188
1189 // We expect all abbrevs to be at the start of the block.
1190 if (Code != llvm::bitc::DEFINE_ABBREV) {
1191 Cursor.JumpToBit(Offset);
1192 return false;
1193 }
1194 Cursor.ReadAbbrevRecord();
1195 }
1196}
1197
Richard Smithe40f2ba2013-08-07 21:41:30 +00001198Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001199 unsigned &Idx) {
1200 Token Tok;
1201 Tok.startToken();
1202 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1203 Tok.setLength(Record[Idx++]);
1204 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1205 Tok.setIdentifierInfo(II);
1206 Tok.setKind((tok::TokenKind)Record[Idx++]);
1207 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1208 return Tok;
1209}
1210
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001211MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001212 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001213
1214 // Keep track of where we are in the stream, then jump back there
1215 // after reading this macro.
1216 SavedStreamPosition SavedPosition(Stream);
1217
1218 Stream.JumpToBit(Offset);
1219 RecordData Record;
1220 SmallVector<IdentifierInfo*, 16> MacroArgs;
1221 MacroInfo *Macro = 0;
1222
Guy Benyei11169dd2012-12-18 14:30:41 +00001223 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001224 // Advance to the next record, but if we get to the end of the block, don't
1225 // pop it (removing all the abbreviations from the cursor) since we want to
1226 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001227 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001228 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1229
1230 switch (Entry.Kind) {
1231 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1232 case llvm::BitstreamEntry::Error:
1233 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001234 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001235 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001236 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001237 case llvm::BitstreamEntry::Record:
1238 // The interesting case.
1239 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001240 }
1241
1242 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 Record.clear();
1244 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001245 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001247 case PP_MACRO_DIRECTIVE_HISTORY:
1248 return Macro;
1249
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 case PP_MACRO_OBJECT_LIKE:
1251 case PP_MACRO_FUNCTION_LIKE: {
1252 // If we already have a macro, that means that we've hit the end
1253 // of the definition of the macro we were looking for. We're
1254 // done.
1255 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001256 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001257
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001258 unsigned NextIndex = 1; // Skip identifier ID.
1259 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001261 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001262 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001264
Guy Benyei11169dd2012-12-18 14:30:41 +00001265 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1266 // Decode function-like macro info.
1267 bool isC99VarArgs = Record[NextIndex++];
1268 bool isGNUVarArgs = Record[NextIndex++];
1269 bool hasCommaPasting = Record[NextIndex++];
1270 MacroArgs.clear();
1271 unsigned NumArgs = Record[NextIndex++];
1272 for (unsigned i = 0; i != NumArgs; ++i)
1273 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1274
1275 // Install function-like macro info.
1276 MI->setIsFunctionLike();
1277 if (isC99VarArgs) MI->setIsC99Varargs();
1278 if (isGNUVarArgs) MI->setIsGNUVarargs();
1279 if (hasCommaPasting) MI->setHasCommaPasting();
1280 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1281 PP.getPreprocessorAllocator());
1282 }
1283
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 // Remember that we saw this macro last so that we add the tokens that
1285 // form its body to it.
1286 Macro = MI;
1287
1288 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1289 Record[NextIndex]) {
1290 // We have a macro definition. Register the association
1291 PreprocessedEntityID
1292 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1293 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001294 PreprocessingRecord::PPEntityID
1295 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1296 MacroDefinition *PPDef =
1297 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1298 if (PPDef)
1299 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 }
1301
1302 ++NumMacrosRead;
1303 break;
1304 }
1305
1306 case PP_TOKEN: {
1307 // If we see a TOKEN before a PP_MACRO_*, then the file is
1308 // erroneous, just pretend we didn't see this.
1309 if (Macro == 0) break;
1310
John McCallf413f5e2013-05-03 00:10:13 +00001311 unsigned Idx = 0;
1312 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Macro->AddTokenToBody(Tok);
1314 break;
1315 }
1316 }
1317 }
1318}
1319
1320PreprocessedEntityID
1321ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1322 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1323 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1324 assert(I != M.PreprocessedEntityRemap.end()
1325 && "Invalid index into preprocessed entity index remap");
1326
1327 return LocalID + I->second;
1328}
1329
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001330unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1331 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001332}
1333
1334HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001335HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1336 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1337 FE->getName() };
1338 return ikey;
1339}
Guy Benyei11169dd2012-12-18 14:30:41 +00001340
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001341bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1342 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 return false;
1344
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001345 if (strcmp(a.Filename, b.Filename) == 0)
1346 return true;
1347
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001349 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001350 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1351 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001352 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001353}
1354
1355std::pair<unsigned, unsigned>
1356HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1357 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1358 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001359 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001360}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001361
1362HeaderFileInfoTrait::internal_key_type
1363HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1364 internal_key_type ikey;
1365 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1366 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1367 ikey.Filename = (const char *)d;
1368 return ikey;
1369}
1370
Guy Benyei11169dd2012-12-18 14:30:41 +00001371HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001372HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 unsigned DataLen) {
1374 const unsigned char *End = d + DataLen;
1375 using namespace clang::io;
1376 HeaderFileInfo HFI;
1377 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001378 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1379 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 HFI.isImport = (Flags >> 5) & 0x01;
1381 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1382 HFI.DirInfo = (Flags >> 2) & 0x03;
1383 HFI.Resolved = (Flags >> 1) & 0x01;
1384 HFI.IndexHeaderMapHeader = Flags & 0x01;
1385 HFI.NumIncludes = ReadUnalignedLE16(d);
1386 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1387 ReadUnalignedLE32(d));
1388 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1389 // The framework offset is 1 greater than the actual offset,
1390 // since 0 is used as an indicator for "no framework name".
1391 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1392 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1393 }
1394
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001395 if (d != End) {
1396 uint32_t LocalSMID = ReadUnalignedLE32(d);
1397 if (LocalSMID) {
1398 // This header is part of a module. Associate it with the module to enable
1399 // implicit module import.
1400 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1401 Module *Mod = Reader.getSubmodule(GlobalSMID);
1402 HFI.isModuleHeader = true;
1403 FileManager &FileMgr = Reader.getFileManager();
1404 ModuleMap &ModMap =
1405 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001406 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001407 }
1408 }
1409
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1411 (void)End;
1412
1413 // This HeaderFileInfo was externally loaded.
1414 HFI.External = true;
1415 return HFI;
1416}
1417
Richard Smith49f906a2014-03-01 00:08:04 +00001418void
1419ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1420 GlobalMacroID GMacID,
1421 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001423 SubmoduleID *OverrideData = 0;
1424 if (!Overrides.empty()) {
1425 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1426 OverrideData[0] = Overrides.size();
1427 for (unsigned I = 0; I != Overrides.size(); ++I)
1428 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1429 }
1430 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001431}
1432
1433void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1434 ModuleFile *M,
1435 uint64_t MacroDirectivesOffset) {
1436 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1437 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001438}
1439
1440void ASTReader::ReadDefinedMacros() {
1441 // Note that we are loading defined macros.
1442 Deserializing Macros(this);
1443
1444 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1445 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001446 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
1448 // If there was no preprocessor block, skip this file.
1449 if (!MacroCursor.getBitStreamReader())
1450 continue;
1451
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001452 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 Cursor.JumpToBit((*I)->MacroStartOffset);
1454
1455 RecordData Record;
1456 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001457 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1458
1459 switch (E.Kind) {
1460 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1461 case llvm::BitstreamEntry::Error:
1462 Error("malformed block record in AST file");
1463 return;
1464 case llvm::BitstreamEntry::EndBlock:
1465 goto NextCursor;
1466
1467 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001468 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001469 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001470 default: // Default behavior: ignore.
1471 break;
1472
1473 case PP_MACRO_OBJECT_LIKE:
1474 case PP_MACRO_FUNCTION_LIKE:
1475 getLocalIdentifier(**I, Record[0]);
1476 break;
1477
1478 case PP_TOKEN:
1479 // Ignore tokens.
1480 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001482 break;
1483 }
1484 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001485 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 }
1487}
1488
1489namespace {
1490 /// \brief Visitor class used to look up identifirs in an AST file.
1491 class IdentifierLookupVisitor {
1492 StringRef Name;
1493 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001494 unsigned &NumIdentifierLookups;
1495 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001497
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001499 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1500 unsigned &NumIdentifierLookups,
1501 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001502 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001503 NumIdentifierLookups(NumIdentifierLookups),
1504 NumIdentifierLookupHits(NumIdentifierLookupHits),
1505 Found()
1506 {
1507 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001508
1509 static bool visit(ModuleFile &M, void *UserData) {
1510 IdentifierLookupVisitor *This
1511 = static_cast<IdentifierLookupVisitor *>(UserData);
1512
1513 // If we've already searched this module file, skip it now.
1514 if (M.Generation <= This->PriorGeneration)
1515 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 ASTIdentifierLookupTable *IdTable
1518 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1519 if (!IdTable)
1520 return false;
1521
1522 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1523 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001524 ++This->NumIdentifierLookups;
1525 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 if (Pos == IdTable->end())
1527 return false;
1528
1529 // Dereferencing the iterator has the effect of building the
1530 // IdentifierInfo node and populating it with the various
1531 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001532 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 This->Found = *Pos;
1534 return true;
1535 }
1536
1537 // \brief Retrieve the identifier info found within the module
1538 // files.
1539 IdentifierInfo *getIdentifierInfo() const { return Found; }
1540 };
1541}
1542
1543void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1544 // Note that we are loading an identifier.
1545 Deserializing AnIdentifier(this);
1546
1547 unsigned PriorGeneration = 0;
1548 if (getContext().getLangOpts().Modules)
1549 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001550
1551 // If there is a global index, look there first to determine which modules
1552 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001553 GlobalModuleIndex::HitSet Hits;
1554 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001555 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001556 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1557 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001558 }
1559 }
1560
Douglas Gregor7211ac12013-01-25 23:32:03 +00001561 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001562 NumIdentifierLookups,
1563 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001564 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 markIdentifierUpToDate(&II);
1566}
1567
1568void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1569 if (!II)
1570 return;
1571
1572 II->setOutOfDate(false);
1573
1574 // Update the generation for this identifier.
1575 if (getContext().getLangOpts().Modules)
1576 IdentifierGeneration[II] = CurrentGeneration;
1577}
1578
Richard Smith49f906a2014-03-01 00:08:04 +00001579struct ASTReader::ModuleMacroInfo {
1580 SubmoduleID SubModID;
1581 MacroInfo *MI;
1582 SubmoduleID *Overrides;
1583 // FIXME: Remove this.
1584 ModuleFile *F;
1585
1586 bool isDefine() const { return MI; }
1587
1588 SubmoduleID getSubmoduleID() const { return SubModID; }
1589
1590 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1591 if (!Overrides)
1592 return llvm::ArrayRef<SubmoduleID>();
1593 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1594 }
1595
1596 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1597 if (!MI)
1598 return 0;
1599 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1600 }
1601};
1602
1603ASTReader::ModuleMacroInfo *
1604ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1605 ModuleMacroInfo Info;
1606
1607 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1608 if (ID & 1) {
1609 // Macro undefinition.
1610 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1611 Info.MI = 0;
1612 } else {
1613 // Macro definition.
1614 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1615 assert(GMacID);
1616
1617 // If this macro has already been loaded, don't do so again.
1618 // FIXME: This is highly dubious. Multiple macro definitions can have the
1619 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1620 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1621 return 0;
1622
1623 Info.MI = getMacro(GMacID);
1624 Info.SubModID = Info.MI->getOwningModuleID();
1625 }
1626 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1627 Info.F = PMInfo.M;
1628
1629 return new (Context) ModuleMacroInfo(Info);
1630}
1631
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001632void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1633 const PendingMacroInfo &PMInfo) {
1634 assert(II);
1635
1636 if (PMInfo.M->Kind != MK_Module) {
1637 installPCHMacroDirectives(II, *PMInfo.M,
1638 PMInfo.PCHMacroData.MacroDirectivesOffset);
1639 return;
1640 }
Richard Smith49f906a2014-03-01 00:08:04 +00001641
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001642 // Module Macro.
1643
Richard Smith49f906a2014-03-01 00:08:04 +00001644 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1645 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001646 return;
1647
Richard Smith49f906a2014-03-01 00:08:04 +00001648 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1649 if (Owner && Owner->NameVisibility == Module::Hidden) {
1650 // Macros in the owning module are hidden. Just remember this macro to
1651 // install if we make this module visible.
1652 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1653 } else {
1654 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001655 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001656}
1657
1658void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1659 ModuleFile &M, uint64_t Offset) {
1660 assert(M.Kind != MK_Module);
1661
1662 BitstreamCursor &Cursor = M.MacroCursor;
1663 SavedStreamPosition SavedPosition(Cursor);
1664 Cursor.JumpToBit(Offset);
1665
1666 llvm::BitstreamEntry Entry =
1667 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1668 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1669 Error("malformed block record in AST file");
1670 return;
1671 }
1672
1673 RecordData Record;
1674 PreprocessorRecordTypes RecType =
1675 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1676 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1677 Error("malformed block record in AST file");
1678 return;
1679 }
1680
1681 // Deserialize the macro directives history in reverse source-order.
1682 MacroDirective *Latest = 0, *Earliest = 0;
1683 unsigned Idx = 0, N = Record.size();
1684 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001685 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001686 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001687 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1688 switch (K) {
1689 case MacroDirective::MD_Define: {
1690 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1691 MacroInfo *MI = getMacro(GMacID);
1692 bool isImported = Record[Idx++];
1693 bool isAmbiguous = Record[Idx++];
1694 DefMacroDirective *DefMD =
1695 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1696 DefMD->setAmbiguous(isAmbiguous);
1697 MD = DefMD;
1698 break;
1699 }
1700 case MacroDirective::MD_Undefine:
1701 MD = PP.AllocateUndefMacroDirective(Loc);
1702 break;
1703 case MacroDirective::MD_Visibility: {
1704 bool isPublic = Record[Idx++];
1705 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1706 break;
1707 }
1708 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001709
1710 if (!Latest)
1711 Latest = MD;
1712 if (Earliest)
1713 Earliest->setPrevious(MD);
1714 Earliest = MD;
1715 }
1716
1717 PP.setLoadedMacroDirective(II, Latest);
1718}
1719
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001720/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001721/// modules.
1722static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001723 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001724 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001725 Module *PrevOwner = 0;
1726 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1727 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001728 SourceManager &SrcMgr = Reader.getSourceManager();
1729 bool PrevInSystem
1730 = PrevOwner? PrevOwner->IsSystem
1731 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1732 bool NewInSystem
1733 = NewOwner? NewOwner->IsSystem
1734 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1735 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001736 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001737 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001738}
1739
Richard Smith49f906a2014-03-01 00:08:04 +00001740void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1741 AmbiguousMacros &Ambig,
1742 llvm::ArrayRef<SubmoduleID> Overrides) {
1743 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1744 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001745
Richard Smith49f906a2014-03-01 00:08:04 +00001746 // If this macro is not yet visible, remove it from the hidden names list.
1747 Module *Owner = getSubmodule(OwnerID);
1748 HiddenNames &Hidden = HiddenNamesMap[Owner];
1749 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1750 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001751 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001752 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001753 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001754 }
1755
1756 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001757 Ambig.erase(
1758 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1759 return MD->getInfo()->getOwningModuleID() == OwnerID;
1760 }),
1761 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001762 }
1763}
1764
1765ASTReader::AmbiguousMacros *
1766ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1767 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001768 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001769 if (!Prev && Overrides.empty())
1770 return 0;
1771
1772 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1773 if (PrevDef && PrevDef->isAmbiguous()) {
1774 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1775 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1776 Ambig.push_back(PrevDef);
1777
1778 removeOverriddenMacros(II, Ambig, Overrides);
1779
1780 if (!Ambig.empty())
1781 return &Ambig;
1782
1783 AmbiguousMacroDefs.erase(II);
1784 } else {
1785 // There's no ambiguity yet. Maybe we're introducing one.
1786 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1787 if (PrevDef)
1788 Ambig.push_back(PrevDef);
1789
1790 removeOverriddenMacros(II, Ambig, Overrides);
1791
1792 if (!Ambig.empty()) {
1793 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1794 Result.swap(Ambig);
1795 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001796 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797 }
Richard Smith49f906a2014-03-01 00:08:04 +00001798
1799 // We ended up with no ambiguity.
1800 return 0;
1801}
1802
1803void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1804 Module *Owner) {
1805 assert(II && Owner);
1806
1807 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1808 if (ImportLoc.isInvalid()) {
1809 // FIXME: If we made macros from this module visible but didn't provide a
1810 // source location for the import, we don't have a location for the macro.
1811 // Use the location at which the containing module file was first imported
1812 // for now.
1813 ImportLoc = MMI->F->DirectImportLoc;
1814 }
1815
1816 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1817 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1818
1819
1820 // Create a synthetic macro definition corresponding to the import (or null
1821 // if this was an undefinition of the macro).
1822 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1823
1824 // If there's no ambiguity, just install the macro.
1825 if (!Prev) {
1826 if (MD)
1827 PP.appendMacroDirective(II, MD);
1828 else
1829 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1830 return;
1831 }
1832 assert(!Prev->empty());
1833
1834 if (!MD) {
1835 // We imported a #undef that didn't remove all prior definitions. The most
1836 // recent prior definition remains, and we install it in the place of the
1837 // imported directive.
1838 MacroInfo *NewMI = Prev->back()->getInfo();
1839 Prev->pop_back();
1840 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1841 }
1842
1843 // We're introducing a macro definition that creates or adds to an ambiguity.
1844 // We can resolve that ambiguity if this macro is token-for-token identical to
1845 // all of the existing definitions.
1846 MacroInfo *NewMI = MD->getInfo();
1847 assert(NewMI && "macro definition with no MacroInfo?");
1848 while (!Prev->empty()) {
1849 MacroInfo *PrevMI = Prev->back()->getInfo();
1850 assert(PrevMI && "macro definition with no MacroInfo?");
1851
1852 // Before marking the macros as ambiguous, check if this is a case where
1853 // both macros are in system headers. If so, we trust that the system
1854 // did not get it wrong. This also handles cases where Clang's own
1855 // headers have a different spelling of certain system macros:
1856 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1857 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1858 //
1859 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1860 // overrides the system limits.h's macros, so there's no conflict here.
1861 if (NewMI != PrevMI &&
1862 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1863 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1864 break;
1865
1866 // The previous definition is the same as this one (or both are defined in
1867 // system modules so we can assume they're equivalent); we don't need to
1868 // track it any more.
1869 Prev->pop_back();
1870 }
1871
1872 if (!Prev->empty())
1873 MD->setAmbiguous(true);
1874
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001875 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876}
1877
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001878ASTReader::InputFileInfo
1879ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001880 // Go find this input file.
1881 BitstreamCursor &Cursor = F.InputFilesCursor;
1882 SavedStreamPosition SavedPosition(Cursor);
1883 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1884
1885 unsigned Code = Cursor.ReadCode();
1886 RecordData Record;
1887 StringRef Blob;
1888
1889 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1890 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1891 "invalid record type for input file");
1892 (void)Result;
1893
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001894 std::string Filename;
1895 off_t StoredSize;
1896 time_t StoredTime;
1897 bool Overridden;
1898
Ben Langmuir198c1682014-03-07 07:27:49 +00001899 assert(Record[0] == ID && "Bogus stored ID or offset");
1900 StoredSize = static_cast<off_t>(Record[1]);
1901 StoredTime = static_cast<time_t>(Record[2]);
1902 Overridden = static_cast<bool>(Record[3]);
1903 Filename = Blob;
1904 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001905
Hans Wennborg73945142014-03-14 17:45:06 +00001906 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1907 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001908}
1909
1910std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001911 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001912}
1913
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001914InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 // If this ID is bogus, just return an empty input file.
1916 if (ID == 0 || ID > F.InputFilesLoaded.size())
1917 return InputFile();
1918
1919 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001920 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 return F.InputFilesLoaded[ID-1];
1922
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001923 if (F.InputFilesLoaded[ID-1].isNotFound())
1924 return InputFile();
1925
Guy Benyei11169dd2012-12-18 14:30:41 +00001926 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001927 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001928 SavedStreamPosition SavedPosition(Cursor);
1929 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1930
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001931 InputFileInfo FI = readInputFileInfo(F, ID);
1932 off_t StoredSize = FI.StoredSize;
1933 time_t StoredTime = FI.StoredTime;
1934 bool Overridden = FI.Overridden;
1935 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001936
Ben Langmuir198c1682014-03-07 07:27:49 +00001937 const FileEntry *File
1938 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1939 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1940
1941 // If we didn't find the file, resolve it relative to the
1942 // original directory from which this AST file was created.
1943 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1944 F.OriginalDir != CurrentDir) {
1945 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1946 F.OriginalDir,
1947 CurrentDir);
1948 if (!Resolved.empty())
1949 File = FileMgr.getFile(Resolved);
1950 }
1951
1952 // For an overridden file, create a virtual file with the stored
1953 // size/timestamp.
1954 if (Overridden && File == 0) {
1955 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1956 }
1957
1958 if (File == 0) {
1959 if (Complain) {
1960 std::string ErrorStr = "could not find file '";
1961 ErrorStr += Filename;
1962 ErrorStr += "' referenced by AST file";
1963 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001964 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001965 // Record that we didn't find the file.
1966 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1967 return InputFile();
1968 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001969
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 // Check if there was a request to override the contents of the file
1971 // that was part of the precompiled header. Overridding such a file
1972 // can lead to problems when lexing using the source locations from the
1973 // PCH.
1974 SourceManager &SM = getSourceManager();
1975 if (!Overridden && SM.isFileOverridden(File)) {
1976 if (Complain)
1977 Error(diag::err_fe_pch_file_overridden, Filename);
1978 // After emitting the diagnostic, recover by disabling the override so
1979 // that the original file will be used.
1980 SM.disableFileContentsOverride(File);
1981 // The FileEntry is a virtual file entry with the size of the contents
1982 // that would override the original contents. Set it to the original's
1983 // size/time.
1984 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1985 StoredSize, StoredTime);
1986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001987
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 bool IsOutOfDate = false;
1989
1990 // For an overridden file, there is nothing to validate.
1991 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001992#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 // In our regression testing, the Windows file system seems to
1994 // have inconsistent modification times that sometimes
1995 // erroneously trigger this error-handling path.
1996 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00001997#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001998 )) {
1999 if (Complain) {
2000 // Build a list of the PCH imports that got us here (in reverse).
2001 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2002 while (ImportStack.back()->ImportedBy.size() > 0)
2003 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002004
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 // The top-level PCH is stale.
2006 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2007 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002008
Ben Langmuir198c1682014-03-07 07:27:49 +00002009 // Print the import stack.
2010 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2011 Diag(diag::note_pch_required_by)
2012 << Filename << ImportStack[0]->FileName;
2013 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002014 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002016 }
2017
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 if (!Diags.isDiagnosticInFlight())
2019 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002020 }
2021
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 }
2024
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2026
2027 // Note that we've loaded this input file.
2028 F.InputFilesLoaded[ID-1] = IF;
2029 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002030}
2031
2032const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2033 ModuleFile &M = ModuleMgr.getPrimaryModule();
2034 std::string Filename = filenameStrRef;
2035 MaybeAddSystemRootToFilename(M, Filename);
2036 const FileEntry *File = FileMgr.getFile(Filename);
2037 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2038 M.OriginalDir != CurrentDir) {
2039 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2040 M.OriginalDir,
2041 CurrentDir);
2042 if (!resolved.empty())
2043 File = FileMgr.getFile(resolved);
2044 }
2045
2046 return File;
2047}
2048
2049/// \brief If we are loading a relocatable PCH file, and the filename is
2050/// not an absolute path, add the system root to the beginning of the file
2051/// name.
2052void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2053 std::string &Filename) {
2054 // If this is not a relocatable PCH file, there's nothing to do.
2055 if (!M.RelocatablePCH)
2056 return;
2057
2058 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2059 return;
2060
2061 if (isysroot.empty()) {
2062 // If no system root was given, default to '/'
2063 Filename.insert(Filename.begin(), '/');
2064 return;
2065 }
2066
2067 unsigned Length = isysroot.size();
2068 if (isysroot[Length - 1] != '/')
2069 Filename.insert(Filename.begin(), '/');
2070
2071 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2072}
2073
2074ASTReader::ASTReadResult
2075ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002076 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002078 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002079
2080 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2081 Error("malformed block record in AST file");
2082 return Failure;
2083 }
2084
2085 // Read all of the records and blocks in the control block.
2086 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002087 while (1) {
2088 llvm::BitstreamEntry Entry = Stream.advance();
2089
2090 switch (Entry.Kind) {
2091 case llvm::BitstreamEntry::Error:
2092 Error("malformed block record in AST file");
2093 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002094 case llvm::BitstreamEntry::EndBlock: {
2095 // Validate input files.
2096 const HeaderSearchOptions &HSOpts =
2097 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002098
2099 // All user input files reside at the index range [0, Record[1]), and
2100 // system input files reside at [Record[1], Record[0]).
2101 // Record is the one from INPUT_FILE_OFFSETS.
2102 unsigned NumInputs = Record[0];
2103 unsigned NumUserInputs = Record[1];
2104
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002105 if (!DisableValidation &&
2106 (!HSOpts.ModulesValidateOncePerBuildSession ||
2107 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002109
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002110 // If we are reading a module, we will create a verification timestamp,
2111 // so we verify all input files. Otherwise, verify only user input
2112 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002113
2114 unsigned N = NumUserInputs;
2115 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002116 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2117 N = NumInputs;
2118
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002119 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002120 InputFile IF = getInputFile(F, I+1, Complain);
2121 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002125
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002126 if (Listener)
2127 Listener->visitModuleFile(F.FileName);
2128
Ben Langmuircb69b572014-03-07 06:40:32 +00002129 if (Listener && Listener->needsInputFileVisitation()) {
2130 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2131 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002132 for (unsigned I = 0; I < N; ++I) {
2133 bool IsSystem = I >= NumUserInputs;
2134 InputFileInfo FI = readInputFileInfo(F, I+1);
2135 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2136 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002137 }
2138
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002140 }
2141
Chris Lattnere7b154b2013-01-19 21:39:22 +00002142 case llvm::BitstreamEntry::SubBlock:
2143 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002144 case INPUT_FILES_BLOCK_ID:
2145 F.InputFilesCursor = Stream;
2146 if (Stream.SkipBlock() || // Skip with the main cursor
2147 // Read the abbreviations
2148 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2149 Error("malformed block record in AST file");
2150 return Failure;
2151 }
2152 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002153
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002155 if (Stream.SkipBlock()) {
2156 Error("malformed block record in AST file");
2157 return Failure;
2158 }
2159 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002160 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002161
2162 case llvm::BitstreamEntry::Record:
2163 // The interesting case.
2164 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002165 }
2166
2167 // Read and process a record.
2168 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002169 StringRef Blob;
2170 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 case METADATA: {
2172 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2173 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002174 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2175 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002176 return VersionMismatch;
2177 }
2178
2179 bool hasErrors = Record[5];
2180 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2181 Diag(diag::err_pch_with_compiler_errors);
2182 return HadErrors;
2183 }
2184
2185 F.RelocatablePCH = Record[4];
2186
2187 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002188 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002189 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2190 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002191 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 return VersionMismatch;
2193 }
2194 break;
2195 }
2196
2197 case IMPORTS: {
2198 // Load each of the imported PCH files.
2199 unsigned Idx = 0, N = Record.size();
2200 while (Idx < N) {
2201 // Read information about the AST file.
2202 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2203 // The import location will be the local one for now; we will adjust
2204 // all import locations of module imports after the global source
2205 // location info are setup.
2206 SourceLocation ImportLoc =
2207 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002208 off_t StoredSize = (off_t)Record[Idx++];
2209 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 unsigned Length = Record[Idx++];
2211 SmallString<128> ImportedFile(Record.begin() + Idx,
2212 Record.begin() + Idx + Length);
2213 Idx += Length;
2214
2215 // Load the AST file.
2216 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002217 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002218 ClientLoadCapabilities)) {
2219 case Failure: return Failure;
2220 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002221 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 case OutOfDate: return OutOfDate;
2223 case VersionMismatch: return VersionMismatch;
2224 case ConfigurationMismatch: return ConfigurationMismatch;
2225 case HadErrors: return HadErrors;
2226 case Success: break;
2227 }
2228 }
2229 break;
2230 }
2231
2232 case LANGUAGE_OPTIONS: {
2233 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2234 if (Listener && &F == *ModuleMgr.begin() &&
2235 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002236 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 return ConfigurationMismatch;
2238 break;
2239 }
2240
2241 case TARGET_OPTIONS: {
2242 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2243 if (Listener && &F == *ModuleMgr.begin() &&
2244 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002245 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 return ConfigurationMismatch;
2247 break;
2248 }
2249
2250 case DIAGNOSTIC_OPTIONS: {
2251 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2252 if (Listener && &F == *ModuleMgr.begin() &&
2253 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002254 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return ConfigurationMismatch;
2256 break;
2257 }
2258
2259 case FILE_SYSTEM_OPTIONS: {
2260 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2261 if (Listener && &F == *ModuleMgr.begin() &&
2262 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002263 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 return ConfigurationMismatch;
2265 break;
2266 }
2267
2268 case HEADER_SEARCH_OPTIONS: {
2269 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2270 if (Listener && &F == *ModuleMgr.begin() &&
2271 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002272 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 return ConfigurationMismatch;
2274 break;
2275 }
2276
2277 case PREPROCESSOR_OPTIONS: {
2278 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2279 if (Listener && &F == *ModuleMgr.begin() &&
2280 ParsePreprocessorOptions(Record, Complain, *Listener,
2281 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002282 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 return ConfigurationMismatch;
2284 break;
2285 }
2286
2287 case ORIGINAL_FILE:
2288 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002289 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2291 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2292 break;
2293
2294 case ORIGINAL_FILE_ID:
2295 F.OriginalSourceFileID = FileID::get(Record[0]);
2296 break;
2297
2298 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002299 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 break;
2301
2302 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002303 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 F.InputFilesLoaded.resize(Record[0]);
2305 break;
2306 }
2307 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002308}
2309
2310bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002311 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002312
2313 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2314 Error("malformed block record in AST file");
2315 return true;
2316 }
2317
2318 // Read all of the records and blocks for the AST file.
2319 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002320 while (1) {
2321 llvm::BitstreamEntry Entry = Stream.advance();
2322
2323 switch (Entry.Kind) {
2324 case llvm::BitstreamEntry::Error:
2325 Error("error at end of module block in AST file");
2326 return true;
2327 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002328 // Outside of C++, we do not store a lookup map for the translation unit.
2329 // Instead, mark it as needing a lookup map to be built if this module
2330 // contains any declarations lexically within it (which it always does!).
2331 // This usually has no cost, since we very rarely need the lookup map for
2332 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002334 if (DC->hasExternalLexicalStorage() &&
2335 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002336 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002337
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 return false;
2339 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002340 case llvm::BitstreamEntry::SubBlock:
2341 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 case DECLTYPES_BLOCK_ID:
2343 // We lazily load the decls block, but we want to set up the
2344 // DeclsCursor cursor to point into it. Clone our current bitcode
2345 // cursor to it, enter the block and read the abbrevs in that block.
2346 // With the main cursor, we just skip over it.
2347 F.DeclsCursor = Stream;
2348 if (Stream.SkipBlock() || // Skip with the main cursor.
2349 // Read the abbrevs.
2350 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2351 Error("malformed block record in AST file");
2352 return true;
2353 }
2354 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002355
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 case DECL_UPDATES_BLOCK_ID:
2357 if (Stream.SkipBlock()) {
2358 Error("malformed block record in AST file");
2359 return true;
2360 }
2361 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case PREPROCESSOR_BLOCK_ID:
2364 F.MacroCursor = Stream;
2365 if (!PP.getExternalSource())
2366 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 if (Stream.SkipBlock() ||
2369 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2370 Error("malformed block record in AST file");
2371 return true;
2372 }
2373 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2374 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 case PREPROCESSOR_DETAIL_BLOCK_ID:
2377 F.PreprocessorDetailCursor = Stream;
2378 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002379 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002381 Error("malformed preprocessor detail record in AST file");
2382 return true;
2383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2386
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 if (!PP.getPreprocessingRecord())
2388 PP.createPreprocessingRecord();
2389 if (!PP.getPreprocessingRecord()->getExternalSource())
2390 PP.getPreprocessingRecord()->SetExternalSource(*this);
2391 break;
2392
2393 case SOURCE_MANAGER_BLOCK_ID:
2394 if (ReadSourceManagerBlock(F))
2395 return true;
2396 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002397
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case SUBMODULE_BLOCK_ID:
2399 if (ReadSubmoduleBlock(F))
2400 return true;
2401 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002404 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 if (Stream.SkipBlock() ||
2406 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2407 Error("malformed comments block in AST file");
2408 return true;
2409 }
2410 CommentsCursors.push_back(std::make_pair(C, &F));
2411 break;
2412 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002413
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415 if (Stream.SkipBlock()) {
2416 Error("malformed block record in AST file");
2417 return true;
2418 }
2419 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 }
2421 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422
2423 case llvm::BitstreamEntry::Record:
2424 // The interesting case.
2425 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 }
2427
2428 // Read and process a record.
2429 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002430 StringRef Blob;
2431 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 default: // Default behavior: ignore.
2433 break;
2434
2435 case TYPE_OFFSET: {
2436 if (F.LocalNumTypes != 0) {
2437 Error("duplicate TYPE_OFFSET record in AST file");
2438 return true;
2439 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002440 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 F.LocalNumTypes = Record[0];
2442 unsigned LocalBaseTypeIndex = Record[1];
2443 F.BaseTypeIndex = getTotalNumTypes();
2444
2445 if (F.LocalNumTypes > 0) {
2446 // Introduce the global -> local mapping for types within this module.
2447 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2448
2449 // Introduce the local -> global mapping for types within this module.
2450 F.TypeRemap.insertOrReplace(
2451 std::make_pair(LocalBaseTypeIndex,
2452 F.BaseTypeIndex - LocalBaseTypeIndex));
2453
2454 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2455 }
2456 break;
2457 }
2458
2459 case DECL_OFFSET: {
2460 if (F.LocalNumDecls != 0) {
2461 Error("duplicate DECL_OFFSET record in AST file");
2462 return true;
2463 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002464 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 F.LocalNumDecls = Record[0];
2466 unsigned LocalBaseDeclID = Record[1];
2467 F.BaseDeclID = getTotalNumDecls();
2468
2469 if (F.LocalNumDecls > 0) {
2470 // Introduce the global -> local mapping for declarations within this
2471 // module.
2472 GlobalDeclMap.insert(
2473 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2474
2475 // Introduce the local -> global mapping for declarations within this
2476 // module.
2477 F.DeclRemap.insertOrReplace(
2478 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2479
2480 // Introduce the global -> local mapping for declarations within this
2481 // module.
2482 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2483
2484 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2485 }
2486 break;
2487 }
2488
2489 case TU_UPDATE_LEXICAL: {
2490 DeclContext *TU = Context.getTranslationUnitDecl();
2491 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002492 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002494 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 TU->setHasExternalLexicalStorage(true);
2496 break;
2497 }
2498
2499 case UPDATE_VISIBLE: {
2500 unsigned Idx = 0;
2501 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2502 ASTDeclContextNameLookupTable *Table =
2503 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002504 (const unsigned char *)Blob.data() + Record[Idx++],
2505 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 ASTDeclContextNameLookupTrait(*this, F));
2507 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2508 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith52e3fba2014-03-11 07:17:35 +00002509 F.DeclContextInfos[TU].NameLookupTableData = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 TU->setHasExternalVisibleStorage(true);
Richard Smithd9174792014-03-11 03:10:46 +00002511 } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2512 auto *DC = cast<DeclContext>(D);
2513 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002514 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2515 delete LookupTable;
2516 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 } else
2518 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2519 break;
2520 }
2521
2522 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002523 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 if (Record[0]) {
2525 F.IdentifierLookupTable
2526 = ASTIdentifierLookupTable::Create(
2527 (const unsigned char *)F.IdentifierTableData + Record[0],
2528 (const unsigned char *)F.IdentifierTableData,
2529 ASTIdentifierLookupTrait(*this, F));
2530
2531 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2532 }
2533 break;
2534
2535 case IDENTIFIER_OFFSET: {
2536 if (F.LocalNumIdentifiers != 0) {
2537 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2538 return true;
2539 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002540 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 F.LocalNumIdentifiers = Record[0];
2542 unsigned LocalBaseIdentifierID = Record[1];
2543 F.BaseIdentifierID = getTotalNumIdentifiers();
2544
2545 if (F.LocalNumIdentifiers > 0) {
2546 // Introduce the global -> local mapping for identifiers within this
2547 // module.
2548 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2549 &F));
2550
2551 // Introduce the local -> global mapping for identifiers within this
2552 // module.
2553 F.IdentifierRemap.insertOrReplace(
2554 std::make_pair(LocalBaseIdentifierID,
2555 F.BaseIdentifierID - LocalBaseIdentifierID));
2556
2557 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2558 + F.LocalNumIdentifiers);
2559 }
2560 break;
2561 }
2562
Ben Langmuir332aafe2014-01-31 01:06:56 +00002563 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002565 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
2567
2568 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002569 if (SpecialTypes.empty()) {
2570 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2571 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2572 break;
2573 }
2574
2575 if (SpecialTypes.size() != Record.size()) {
2576 Error("invalid special-types record");
2577 return true;
2578 }
2579
2580 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2581 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2582 if (!SpecialTypes[I])
2583 SpecialTypes[I] = ID;
2584 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2585 // merge step?
2586 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 break;
2588
2589 case STATISTICS:
2590 TotalNumStatements += Record[0];
2591 TotalNumMacros += Record[1];
2592 TotalLexicalDeclContexts += Record[2];
2593 TotalVisibleDeclContexts += Record[3];
2594 break;
2595
2596 case UNUSED_FILESCOPED_DECLS:
2597 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2598 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2599 break;
2600
2601 case DELEGATING_CTORS:
2602 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2603 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2604 break;
2605
2606 case WEAK_UNDECLARED_IDENTIFIERS:
2607 if (Record.size() % 4 != 0) {
2608 Error("invalid weak identifiers record");
2609 return true;
2610 }
2611
2612 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2613 // files. This isn't the way to do it :)
2614 WeakUndeclaredIdentifiers.clear();
2615
2616 // Translate the weak, undeclared identifiers into global IDs.
2617 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2618 WeakUndeclaredIdentifiers.push_back(
2619 getGlobalIdentifierID(F, Record[I++]));
2620 WeakUndeclaredIdentifiers.push_back(
2621 getGlobalIdentifierID(F, Record[I++]));
2622 WeakUndeclaredIdentifiers.push_back(
2623 ReadSourceLocation(F, Record, I).getRawEncoding());
2624 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2625 }
2626 break;
2627
Richard Smith78165b52013-01-10 23:43:47 +00002628 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002630 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 break;
2632
2633 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002634 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 F.LocalNumSelectors = Record[0];
2636 unsigned LocalBaseSelectorID = Record[1];
2637 F.BaseSelectorID = getTotalNumSelectors();
2638
2639 if (F.LocalNumSelectors > 0) {
2640 // Introduce the global -> local mapping for selectors within this
2641 // module.
2642 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2643
2644 // Introduce the local -> global mapping for selectors within this
2645 // module.
2646 F.SelectorRemap.insertOrReplace(
2647 std::make_pair(LocalBaseSelectorID,
2648 F.BaseSelectorID - LocalBaseSelectorID));
2649
2650 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2651 }
2652 break;
2653 }
2654
2655 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 if (Record[0])
2658 F.SelectorLookupTable
2659 = ASTSelectorLookupTable::Create(
2660 F.SelectorLookupTableData + Record[0],
2661 F.SelectorLookupTableData,
2662 ASTSelectorLookupTrait(*this, F));
2663 TotalNumMethodPoolEntries += Record[1];
2664 break;
2665
2666 case REFERENCED_SELECTOR_POOL:
2667 if (!Record.empty()) {
2668 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2669 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2670 Record[Idx++]));
2671 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2672 getRawEncoding());
2673 }
2674 }
2675 break;
2676
2677 case PP_COUNTER_VALUE:
2678 if (!Record.empty() && Listener)
2679 Listener->ReadCounter(F, Record[0]);
2680 break;
2681
2682 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002683 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 F.NumFileSortedDecls = Record[0];
2685 break;
2686
2687 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002688 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 F.LocalNumSLocEntries = Record[0];
2690 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002691 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2693 SLocSpaceSize);
2694 // Make our entry in the range map. BaseID is negative and growing, so
2695 // we invert it. Because we invert it, though, we need the other end of
2696 // the range.
2697 unsigned RangeStart =
2698 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2699 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2700 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2701
2702 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2703 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2704 GlobalSLocOffsetMap.insert(
2705 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2706 - SLocSpaceSize,&F));
2707
2708 // Initialize the remapping table.
2709 // Invalid stays invalid.
2710 F.SLocRemap.insert(std::make_pair(0U, 0));
2711 // This module. Base was 2 when being compiled.
2712 F.SLocRemap.insert(std::make_pair(2U,
2713 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2714
2715 TotalNumSLocEntries += F.LocalNumSLocEntries;
2716 break;
2717 }
2718
2719 case MODULE_OFFSET_MAP: {
2720 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002721 const unsigned char *Data = (const unsigned char*)Blob.data();
2722 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002723
2724 // Continuous range maps we may be updating in our module.
2725 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2726 ContinuousRangeMap<uint32_t, int, 2>::Builder
2727 IdentifierRemap(F.IdentifierRemap);
2728 ContinuousRangeMap<uint32_t, int, 2>::Builder
2729 MacroRemap(F.MacroRemap);
2730 ContinuousRangeMap<uint32_t, int, 2>::Builder
2731 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2732 ContinuousRangeMap<uint32_t, int, 2>::Builder
2733 SubmoduleRemap(F.SubmoduleRemap);
2734 ContinuousRangeMap<uint32_t, int, 2>::Builder
2735 SelectorRemap(F.SelectorRemap);
2736 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2737 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2738
2739 while(Data < DataEnd) {
2740 uint16_t Len = io::ReadUnalignedLE16(Data);
2741 StringRef Name = StringRef((const char*)Data, Len);
2742 Data += Len;
2743 ModuleFile *OM = ModuleMgr.lookup(Name);
2744 if (!OM) {
2745 Error("SourceLocation remap refers to unknown module");
2746 return true;
2747 }
2748
2749 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2750 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2751 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2752 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2753 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2754 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2755 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2756 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2757
2758 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2759 SLocRemap.insert(std::make_pair(SLocOffset,
2760 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2761 IdentifierRemap.insert(
2762 std::make_pair(IdentifierIDOffset,
2763 OM->BaseIdentifierID - IdentifierIDOffset));
2764 MacroRemap.insert(std::make_pair(MacroIDOffset,
2765 OM->BaseMacroID - MacroIDOffset));
2766 PreprocessedEntityRemap.insert(
2767 std::make_pair(PreprocessedEntityIDOffset,
2768 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2769 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2770 OM->BaseSubmoduleID - SubmoduleIDOffset));
2771 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2772 OM->BaseSelectorID - SelectorIDOffset));
2773 DeclRemap.insert(std::make_pair(DeclIDOffset,
2774 OM->BaseDeclID - DeclIDOffset));
2775
2776 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2777 OM->BaseTypeIndex - TypeIndexOffset));
2778
2779 // Global -> local mappings.
2780 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2781 }
2782 break;
2783 }
2784
2785 case SOURCE_MANAGER_LINE_TABLE:
2786 if (ParseLineTable(F, Record))
2787 return true;
2788 break;
2789
2790 case SOURCE_LOCATION_PRELOADS: {
2791 // Need to transform from the local view (1-based IDs) to the global view,
2792 // which is based off F.SLocEntryBaseID.
2793 if (!F.PreloadSLocEntries.empty()) {
2794 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2795 return true;
2796 }
2797
2798 F.PreloadSLocEntries.swap(Record);
2799 break;
2800 }
2801
2802 case EXT_VECTOR_DECLS:
2803 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2804 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2805 break;
2806
2807 case VTABLE_USES:
2808 if (Record.size() % 3 != 0) {
2809 Error("Invalid VTABLE_USES record");
2810 return true;
2811 }
2812
2813 // Later tables overwrite earlier ones.
2814 // FIXME: Modules will have some trouble with this. This is clearly not
2815 // the right way to do this.
2816 VTableUses.clear();
2817
2818 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2819 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2820 VTableUses.push_back(
2821 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2822 VTableUses.push_back(Record[Idx++]);
2823 }
2824 break;
2825
2826 case DYNAMIC_CLASSES:
2827 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2828 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2829 break;
2830
2831 case PENDING_IMPLICIT_INSTANTIATIONS:
2832 if (PendingInstantiations.size() % 2 != 0) {
2833 Error("Invalid existing PendingInstantiations");
2834 return true;
2835 }
2836
2837 if (Record.size() % 2 != 0) {
2838 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2839 return true;
2840 }
2841
2842 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2843 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2844 PendingInstantiations.push_back(
2845 ReadSourceLocation(F, Record, I).getRawEncoding());
2846 }
2847 break;
2848
2849 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002850 if (Record.size() != 2) {
2851 Error("Invalid SEMA_DECL_REFS block");
2852 return true;
2853 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2855 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2856 break;
2857
2858 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002859 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2860 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2861 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002862
2863 unsigned LocalBasePreprocessedEntityID = Record[0];
2864
2865 unsigned StartingID;
2866 if (!PP.getPreprocessingRecord())
2867 PP.createPreprocessingRecord();
2868 if (!PP.getPreprocessingRecord()->getExternalSource())
2869 PP.getPreprocessingRecord()->SetExternalSource(*this);
2870 StartingID
2871 = PP.getPreprocessingRecord()
2872 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2873 F.BasePreprocessedEntityID = StartingID;
2874
2875 if (F.NumPreprocessedEntities > 0) {
2876 // Introduce the global -> local mapping for preprocessed entities in
2877 // this module.
2878 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2879
2880 // Introduce the local -> global mapping for preprocessed entities in
2881 // this module.
2882 F.PreprocessedEntityRemap.insertOrReplace(
2883 std::make_pair(LocalBasePreprocessedEntityID,
2884 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2885 }
2886
2887 break;
2888 }
2889
2890 case DECL_UPDATE_OFFSETS: {
2891 if (Record.size() % 2 != 0) {
2892 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2893 return true;
2894 }
2895 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2896 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2897 .push_back(std::make_pair(&F, Record[I+1]));
2898 break;
2899 }
2900
2901 case DECL_REPLACEMENTS: {
2902 if (Record.size() % 3 != 0) {
2903 Error("invalid DECL_REPLACEMENTS block in AST file");
2904 return true;
2905 }
2906 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2907 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2908 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2909 break;
2910 }
2911
2912 case OBJC_CATEGORIES_MAP: {
2913 if (F.LocalNumObjCCategoriesInMap != 0) {
2914 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2915 return true;
2916 }
2917
2918 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002919 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 break;
2921 }
2922
2923 case OBJC_CATEGORIES:
2924 F.ObjCCategories.swap(Record);
2925 break;
2926
2927 case CXX_BASE_SPECIFIER_OFFSETS: {
2928 if (F.LocalNumCXXBaseSpecifiers != 0) {
2929 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2930 return true;
2931 }
2932
2933 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2936 break;
2937 }
2938
2939 case DIAG_PRAGMA_MAPPINGS:
2940 if (F.PragmaDiagMappings.empty())
2941 F.PragmaDiagMappings.swap(Record);
2942 else
2943 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2944 Record.begin(), Record.end());
2945 break;
2946
2947 case CUDA_SPECIAL_DECL_REFS:
2948 // Later tables overwrite earlier ones.
2949 // FIXME: Modules will have trouble with this.
2950 CUDASpecialDeclRefs.clear();
2951 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2952 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2953 break;
2954
2955 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002956 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 if (Record[0]) {
2959 F.HeaderFileInfoTable
2960 = HeaderFileInfoLookupTable::Create(
2961 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2962 (const unsigned char *)F.HeaderFileInfoTableData,
2963 HeaderFileInfoTrait(*this, F,
2964 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002965 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002966
2967 PP.getHeaderSearchInfo().SetExternalSource(this);
2968 if (!PP.getHeaderSearchInfo().getExternalLookup())
2969 PP.getHeaderSearchInfo().SetExternalLookup(this);
2970 }
2971 break;
2972 }
2973
2974 case FP_PRAGMA_OPTIONS:
2975 // Later tables overwrite earlier ones.
2976 FPPragmaOptions.swap(Record);
2977 break;
2978
2979 case OPENCL_EXTENSIONS:
2980 // Later tables overwrite earlier ones.
2981 OpenCLExtensions.swap(Record);
2982 break;
2983
2984 case TENTATIVE_DEFINITIONS:
2985 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2986 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2987 break;
2988
2989 case KNOWN_NAMESPACES:
2990 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2991 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2992 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002993
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002994 case UNDEFINED_BUT_USED:
2995 if (UndefinedButUsed.size() % 2 != 0) {
2996 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002997 return true;
2998 }
2999
3000 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003001 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00003002 return true;
3003 }
3004 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003005 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3006 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003007 ReadSourceLocation(F, Record, I).getRawEncoding());
3008 }
3009 break;
3010
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 case IMPORTED_MODULES: {
3012 if (F.Kind != MK_Module) {
3013 // If we aren't loading a module (which has its own exports), make
3014 // all of the imported modules visible.
3015 // FIXME: Deal with macros-only imports.
3016 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3017 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
3018 ImportedModules.push_back(GlobalID);
3019 }
3020 }
3021 break;
3022 }
3023
3024 case LOCAL_REDECLARATIONS: {
3025 F.RedeclarationChains.swap(Record);
3026 break;
3027 }
3028
3029 case LOCAL_REDECLARATIONS_MAP: {
3030 if (F.LocalNumRedeclarationsInMap != 0) {
3031 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3032 return true;
3033 }
3034
3035 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003036 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 break;
3038 }
3039
3040 case MERGED_DECLARATIONS: {
3041 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3042 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3043 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3044 for (unsigned N = Record[Idx++]; N > 0; --N)
3045 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3046 }
3047 break;
3048 }
3049
3050 case MACRO_OFFSET: {
3051 if (F.LocalNumMacros != 0) {
3052 Error("duplicate MACRO_OFFSET record in AST file");
3053 return true;
3054 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003055 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 F.LocalNumMacros = Record[0];
3057 unsigned LocalBaseMacroID = Record[1];
3058 F.BaseMacroID = getTotalNumMacros();
3059
3060 if (F.LocalNumMacros > 0) {
3061 // Introduce the global -> local mapping for macros within this module.
3062 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3063
3064 // Introduce the local -> global mapping for macros within this module.
3065 F.MacroRemap.insertOrReplace(
3066 std::make_pair(LocalBaseMacroID,
3067 F.BaseMacroID - LocalBaseMacroID));
3068
3069 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3070 }
3071 break;
3072 }
3073
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003074 case MACRO_TABLE: {
3075 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 break;
3077 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003078
3079 case LATE_PARSED_TEMPLATE: {
3080 LateParsedTemplates.append(Record.begin(), Record.end());
3081 break;
3082 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 }
3084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003085}
3086
Douglas Gregorc1489562013-02-12 23:36:21 +00003087/// \brief Move the given method to the back of the global list of methods.
3088static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3089 // Find the entry for this selector in the method pool.
3090 Sema::GlobalMethodPool::iterator Known
3091 = S.MethodPool.find(Method->getSelector());
3092 if (Known == S.MethodPool.end())
3093 return;
3094
3095 // Retrieve the appropriate method list.
3096 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3097 : Known->second.second;
3098 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003099 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003100 if (!Found) {
3101 if (List->Method == Method) {
3102 Found = true;
3103 } else {
3104 // Keep searching.
3105 continue;
3106 }
3107 }
3108
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003109 if (List->getNext())
3110 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003111 else
3112 List->Method = Method;
3113 }
3114}
3115
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003116void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003117 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3118 Decl *D = Names.HiddenDecls[I];
3119 bool wasHidden = D->Hidden;
3120 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121
Richard Smith49f906a2014-03-01 00:08:04 +00003122 if (wasHidden && SemaObj) {
3123 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3124 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003125 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 }
3127 }
Richard Smith49f906a2014-03-01 00:08:04 +00003128
3129 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3130 E = Names.HiddenMacros.end();
3131 I != E; ++I)
3132 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003133}
3134
Richard Smith49f906a2014-03-01 00:08:04 +00003135void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003136 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003137 SourceLocation ImportLoc,
3138 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003140 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003141 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003143 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003144
3145 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003146 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 // there is nothing more to do.
3148 continue;
3149 }
Richard Smith49f906a2014-03-01 00:08:04 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 if (!Mod->isAvailable()) {
3152 // Modules that aren't available cannot be made visible.
3153 continue;
3154 }
3155
3156 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003157 if (NameVisibility >= Module::MacrosVisible &&
3158 Mod->NameVisibility < Module::MacrosVisible)
3159 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 // If we've already deserialized any names from this module,
3163 // mark them as visible.
3164 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3165 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003166 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 HiddenNamesMap.erase(Hidden);
3168 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003169
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003171 SmallVector<Module *, 16> Exports;
3172 Mod->getExportedModules(Exports);
3173 for (SmallVectorImpl<Module *>::iterator
3174 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3175 Module *Exported = *I;
3176 if (Visited.insert(Exported))
3177 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003179
3180 // Detect any conflicts.
3181 if (Complain) {
3182 assert(ImportLoc.isValid() && "Missing import location");
3183 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3184 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3185 Diag(ImportLoc, diag::warn_module_conflict)
3186 << Mod->getFullModuleName()
3187 << Mod->Conflicts[I].Other->getFullModuleName()
3188 << Mod->Conflicts[I].Message;
3189 // FIXME: Need note where the other module was imported.
3190 }
3191 }
3192 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
3194}
3195
Douglas Gregore060e572013-01-25 01:03:03 +00003196bool ASTReader::loadGlobalIndex() {
3197 if (GlobalIndex)
3198 return false;
3199
3200 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3201 !Context.getLangOpts().Modules)
3202 return true;
3203
3204 // Try to load the global index.
3205 TriedLoadingGlobalIndex = true;
3206 StringRef ModuleCachePath
3207 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3208 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003209 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003210 if (!Result.first)
3211 return true;
3212
3213 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003214 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003215 return false;
3216}
3217
3218bool ASTReader::isGlobalIndexUnavailable() const {
3219 return Context.getLangOpts().Modules && UseGlobalIndex &&
3220 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3221}
3222
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003223static void updateModuleTimestamp(ModuleFile &MF) {
3224 // Overwrite the timestamp file contents so that file's mtime changes.
3225 std::string TimestampFilename = MF.getTimestampFilename();
3226 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003227 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003228 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003229 if (!ErrorInfo.empty())
3230 return;
3231 OS << "Timestamp file\n";
3232}
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3235 ModuleKind Type,
3236 SourceLocation ImportLoc,
3237 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003238 llvm::SaveAndRestore<SourceLocation>
3239 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3240
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 // Bump the generation number.
3242 unsigned PreviousGeneration = CurrentGeneration++;
3243
3244 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003245 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3247 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003248 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 ClientLoadCapabilities)) {
3250 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003251 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 case OutOfDate:
3253 case VersionMismatch:
3254 case ConfigurationMismatch:
3255 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003256 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3257 Context.getLangOpts().Modules
3258 ? &PP.getHeaderSearchInfo().getModuleMap()
3259 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003260
3261 // If we find that any modules are unusable, the global index is going
3262 // to be out-of-date. Just remove it.
3263 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003264 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 return ReadResult;
3266
3267 case Success:
3268 break;
3269 }
3270
3271 // Here comes stuff that we only do once the entire chain is loaded.
3272
3273 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003274 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3275 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 M != MEnd; ++M) {
3277 ModuleFile &F = *M->Mod;
3278
3279 // Read the AST block.
3280 if (ReadASTBlock(F))
3281 return Failure;
3282
3283 // Once read, set the ModuleFile bit base offset and update the size in
3284 // bits of all files we've seen.
3285 F.GlobalBitOffset = TotalModulesSizeInBits;
3286 TotalModulesSizeInBits += F.SizeInBits;
3287 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3288
3289 // Preload SLocEntries.
3290 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3291 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3292 // Load it through the SourceManager and don't call ReadSLocEntry()
3293 // directly because the entry may have already been loaded in which case
3294 // calling ReadSLocEntry() directly would trigger an assertion in
3295 // SourceManager.
3296 SourceMgr.getLoadedSLocEntryByID(Index);
3297 }
3298 }
3299
Douglas Gregor603cd862013-03-22 18:50:14 +00003300 // Setup the import locations and notify the module manager that we've
3301 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003302 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3303 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 M != MEnd; ++M) {
3305 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003306
3307 ModuleMgr.moduleFileAccepted(&F);
3308
3309 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003310 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 if (!M->ImportedBy)
3312 F.ImportLoc = M->ImportLoc;
3313 else
3314 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3315 M->ImportLoc.getRawEncoding());
3316 }
3317
3318 // Mark all of the identifiers in the identifier table as being out of date,
3319 // so that various accessors know to check the loaded modules when the
3320 // identifier is used.
3321 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3322 IdEnd = PP.getIdentifierTable().end();
3323 Id != IdEnd; ++Id)
3324 Id->second->setOutOfDate(true);
3325
3326 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003327 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3328 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003329 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3330 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003331
3332 switch (Unresolved.Kind) {
3333 case UnresolvedModuleRef::Conflict:
3334 if (ResolvedMod) {
3335 Module::Conflict Conflict;
3336 Conflict.Other = ResolvedMod;
3337 Conflict.Message = Unresolved.String.str();
3338 Unresolved.Mod->Conflicts.push_back(Conflict);
3339 }
3340 continue;
3341
3342 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 if (ResolvedMod)
3344 Unresolved.Mod->Imports.push_back(ResolvedMod);
3345 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003346
Douglas Gregorfb912652013-03-20 21:10:35 +00003347 case UnresolvedModuleRef::Export:
3348 if (ResolvedMod || Unresolved.IsWildcard)
3349 Unresolved.Mod->Exports.push_back(
3350 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3351 continue;
3352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003354 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003355
3356 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3357 // Might be unnecessary as use declarations are only used to build the
3358 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003359
3360 InitializeContext();
3361
Richard Smith3d8e97e2013-10-18 06:54:39 +00003362 if (SemaObj)
3363 UpdateSema();
3364
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 if (DeserializationListener)
3366 DeserializationListener->ReaderInitialized(this);
3367
3368 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3369 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3370 PrimaryModule.OriginalSourceFileID
3371 = FileID::get(PrimaryModule.SLocEntryBaseID
3372 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3373
3374 // If this AST file is a precompiled preamble, then set the
3375 // preamble file ID of the source manager to the file source file
3376 // from which the preamble was built.
3377 if (Type == MK_Preamble) {
3378 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3379 } else if (Type == MK_MainFile) {
3380 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3381 }
3382 }
3383
3384 // For any Objective-C class definitions we have already loaded, make sure
3385 // that we load any additional categories.
3386 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3387 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3388 ObjCClassesLoaded[I],
3389 PreviousGeneration);
3390 }
Douglas Gregore060e572013-01-25 01:03:03 +00003391
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003392 if (PP.getHeaderSearchInfo()
3393 .getHeaderSearchOpts()
3394 .ModulesValidateOncePerBuildSession) {
3395 // Now we are certain that the module and all modules it depends on are
3396 // up to date. Create or update timestamp files for modules that are
3397 // located in the module cache (not for PCH files that could be anywhere
3398 // in the filesystem).
3399 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3400 ImportedModule &M = Loaded[I];
3401 if (M.Mod->Kind == MK_Module) {
3402 updateModuleTimestamp(*M.Mod);
3403 }
3404 }
3405 }
3406
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 return Success;
3408}
3409
3410ASTReader::ASTReadResult
3411ASTReader::ReadASTCore(StringRef FileName,
3412 ModuleKind Type,
3413 SourceLocation ImportLoc,
3414 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003415 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003416 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003417 unsigned ClientLoadCapabilities) {
3418 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003419 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003420 ModuleManager::AddModuleResult AddResult
3421 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3422 CurrentGeneration, ExpectedSize, ExpectedModTime,
3423 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003424
Douglas Gregor7029ce12013-03-19 00:28:20 +00003425 switch (AddResult) {
3426 case ModuleManager::AlreadyLoaded:
3427 return Success;
3428
3429 case ModuleManager::NewlyLoaded:
3430 // Load module file below.
3431 break;
3432
3433 case ModuleManager::Missing:
3434 // The module file was missing; if the client handle handle, that, return
3435 // it.
3436 if (ClientLoadCapabilities & ARR_Missing)
3437 return Missing;
3438
3439 // Otherwise, return an error.
3440 {
3441 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3442 + ErrorStr;
3443 Error(Msg);
3444 }
3445 return Failure;
3446
3447 case ModuleManager::OutOfDate:
3448 // We couldn't load the module file because it is out-of-date. If the
3449 // client can handle out-of-date, return it.
3450 if (ClientLoadCapabilities & ARR_OutOfDate)
3451 return OutOfDate;
3452
3453 // Otherwise, return an error.
3454 {
3455 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3456 + ErrorStr;
3457 Error(Msg);
3458 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 return Failure;
3460 }
3461
Douglas Gregor7029ce12013-03-19 00:28:20 +00003462 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003463
3464 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3465 // module?
3466 if (FileName != "-") {
3467 CurrentDir = llvm::sys::path::parent_path(FileName);
3468 if (CurrentDir.empty()) CurrentDir = ".";
3469 }
3470
3471 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003472 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 Stream.init(F.StreamFile);
3474 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3475
3476 // Sniff for the signature.
3477 if (Stream.Read(8) != 'C' ||
3478 Stream.Read(8) != 'P' ||
3479 Stream.Read(8) != 'C' ||
3480 Stream.Read(8) != 'H') {
3481 Diag(diag::err_not_a_pch_file) << FileName;
3482 return Failure;
3483 }
3484
3485 // This is used for compatibility with older PCH formats.
3486 bool HaveReadControlBlock = false;
3487
Chris Lattnerefa77172013-01-20 00:00:22 +00003488 while (1) {
3489 llvm::BitstreamEntry Entry = Stream.advance();
3490
3491 switch (Entry.Kind) {
3492 case llvm::BitstreamEntry::Error:
3493 case llvm::BitstreamEntry::EndBlock:
3494 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 Error("invalid record at top-level of AST file");
3496 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003497
3498 case llvm::BitstreamEntry::SubBlock:
3499 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 }
3501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003503 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3505 if (Stream.ReadBlockInfoBlock()) {
3506 Error("malformed BlockInfoBlock in AST file");
3507 return Failure;
3508 }
3509 break;
3510 case CONTROL_BLOCK_ID:
3511 HaveReadControlBlock = true;
3512 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3513 case Success:
3514 break;
3515
3516 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003517 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 case OutOfDate: return OutOfDate;
3519 case VersionMismatch: return VersionMismatch;
3520 case ConfigurationMismatch: return ConfigurationMismatch;
3521 case HadErrors: return HadErrors;
3522 }
3523 break;
3524 case AST_BLOCK_ID:
3525 if (!HaveReadControlBlock) {
3526 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003527 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 return VersionMismatch;
3529 }
3530
3531 // Record that we've loaded this module.
3532 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3533 return Success;
3534
3535 default:
3536 if (Stream.SkipBlock()) {
3537 Error("malformed block record in AST file");
3538 return Failure;
3539 }
3540 break;
3541 }
3542 }
3543
3544 return Success;
3545}
3546
3547void ASTReader::InitializeContext() {
3548 // If there's a listener, notify them that we "read" the translation unit.
3549 if (DeserializationListener)
3550 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3551 Context.getTranslationUnitDecl());
3552
3553 // Make sure we load the declaration update records for the translation unit,
3554 // if there are any.
3555 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3556 Context.getTranslationUnitDecl());
3557
3558 // FIXME: Find a better way to deal with collisions between these
3559 // built-in types. Right now, we just ignore the problem.
3560
3561 // Load the special types.
3562 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3563 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3564 if (!Context.CFConstantStringTypeDecl)
3565 Context.setCFConstantStringType(GetType(String));
3566 }
3567
3568 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3569 QualType FileType = GetType(File);
3570 if (FileType.isNull()) {
3571 Error("FILE type is NULL");
3572 return;
3573 }
3574
3575 if (!Context.FILEDecl) {
3576 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3577 Context.setFILEDecl(Typedef->getDecl());
3578 else {
3579 const TagType *Tag = FileType->getAs<TagType>();
3580 if (!Tag) {
3581 Error("Invalid FILE type in AST file");
3582 return;
3583 }
3584 Context.setFILEDecl(Tag->getDecl());
3585 }
3586 }
3587 }
3588
3589 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3590 QualType Jmp_bufType = GetType(Jmp_buf);
3591 if (Jmp_bufType.isNull()) {
3592 Error("jmp_buf type is NULL");
3593 return;
3594 }
3595
3596 if (!Context.jmp_bufDecl) {
3597 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3598 Context.setjmp_bufDecl(Typedef->getDecl());
3599 else {
3600 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3601 if (!Tag) {
3602 Error("Invalid jmp_buf type in AST file");
3603 return;
3604 }
3605 Context.setjmp_bufDecl(Tag->getDecl());
3606 }
3607 }
3608 }
3609
3610 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3611 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3612 if (Sigjmp_bufType.isNull()) {
3613 Error("sigjmp_buf type is NULL");
3614 return;
3615 }
3616
3617 if (!Context.sigjmp_bufDecl) {
3618 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3619 Context.setsigjmp_bufDecl(Typedef->getDecl());
3620 else {
3621 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3622 assert(Tag && "Invalid sigjmp_buf type in AST file");
3623 Context.setsigjmp_bufDecl(Tag->getDecl());
3624 }
3625 }
3626 }
3627
3628 if (unsigned ObjCIdRedef
3629 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3630 if (Context.ObjCIdRedefinitionType.isNull())
3631 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3632 }
3633
3634 if (unsigned ObjCClassRedef
3635 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3636 if (Context.ObjCClassRedefinitionType.isNull())
3637 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3638 }
3639
3640 if (unsigned ObjCSelRedef
3641 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3642 if (Context.ObjCSelRedefinitionType.isNull())
3643 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3644 }
3645
3646 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3647 QualType Ucontext_tType = GetType(Ucontext_t);
3648 if (Ucontext_tType.isNull()) {
3649 Error("ucontext_t type is NULL");
3650 return;
3651 }
3652
3653 if (!Context.ucontext_tDecl) {
3654 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3655 Context.setucontext_tDecl(Typedef->getDecl());
3656 else {
3657 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3658 assert(Tag && "Invalid ucontext_t type in AST file");
3659 Context.setucontext_tDecl(Tag->getDecl());
3660 }
3661 }
3662 }
3663 }
3664
3665 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3666
3667 // If there were any CUDA special declarations, deserialize them.
3668 if (!CUDASpecialDeclRefs.empty()) {
3669 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3670 Context.setcudaConfigureCallDecl(
3671 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3672 }
3673
3674 // Re-export any modules that were imported by a non-module AST file.
3675 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3676 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003677 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003678 /*ImportLoc=*/SourceLocation(),
3679 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 }
3681 ImportedModules.clear();
3682}
3683
3684void ASTReader::finalizeForWriting() {
3685 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3686 HiddenEnd = HiddenNamesMap.end();
3687 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003688 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 }
3690 HiddenNamesMap.clear();
3691}
3692
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003693/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3694/// cursor into the start of the given block ID, returning false on success and
3695/// true on failure.
3696static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003697 while (1) {
3698 llvm::BitstreamEntry Entry = Cursor.advance();
3699 switch (Entry.Kind) {
3700 case llvm::BitstreamEntry::Error:
3701 case llvm::BitstreamEntry::EndBlock:
3702 return true;
3703
3704 case llvm::BitstreamEntry::Record:
3705 // Ignore top-level records.
3706 Cursor.skipRecord(Entry.ID);
3707 break;
3708
3709 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003710 if (Entry.ID == BlockID) {
3711 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003712 return true;
3713 // Found it!
3714 return false;
3715 }
3716
3717 if (Cursor.SkipBlock())
3718 return true;
3719 }
3720 }
3721}
3722
Guy Benyei11169dd2012-12-18 14:30:41 +00003723/// \brief Retrieve the name of the original source file name
3724/// directly from the AST file, without actually loading the AST
3725/// file.
3726std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3727 FileManager &FileMgr,
3728 DiagnosticsEngine &Diags) {
3729 // Open the AST file.
3730 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003731 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3733 if (!Buffer) {
3734 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3735 return std::string();
3736 }
3737
3738 // Initialize the stream
3739 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003740 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3742 (const unsigned char *)Buffer->getBufferEnd());
3743 Stream.init(StreamFile);
3744
3745 // Sniff for the signature.
3746 if (Stream.Read(8) != 'C' ||
3747 Stream.Read(8) != 'P' ||
3748 Stream.Read(8) != 'C' ||
3749 Stream.Read(8) != 'H') {
3750 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3751 return std::string();
3752 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003753
Chris Lattnere7b154b2013-01-19 21:39:22 +00003754 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003755 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003756 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3757 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003758 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003759
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003760 // Scan for ORIGINAL_FILE inside the control block.
3761 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003762 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003763 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003764 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3765 return std::string();
3766
3767 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3768 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3769 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003771
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003773 StringRef Blob;
3774 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3775 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003777}
3778
3779namespace {
3780 class SimplePCHValidator : public ASTReaderListener {
3781 const LangOptions &ExistingLangOpts;
3782 const TargetOptions &ExistingTargetOpts;
3783 const PreprocessorOptions &ExistingPPOpts;
3784 FileManager &FileMgr;
3785
3786 public:
3787 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3788 const TargetOptions &ExistingTargetOpts,
3789 const PreprocessorOptions &ExistingPPOpts,
3790 FileManager &FileMgr)
3791 : ExistingLangOpts(ExistingLangOpts),
3792 ExistingTargetOpts(ExistingTargetOpts),
3793 ExistingPPOpts(ExistingPPOpts),
3794 FileMgr(FileMgr)
3795 {
3796 }
3797
Craig Topper3e89dfe2014-03-13 02:13:41 +00003798 bool ReadLanguageOptions(const LangOptions &LangOpts,
3799 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3801 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003802 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3803 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3805 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003806 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3807 bool Complain,
3808 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003810 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003811 }
3812 };
3813}
3814
3815bool ASTReader::readASTFileControlBlock(StringRef Filename,
3816 FileManager &FileMgr,
3817 ASTReaderListener &Listener) {
3818 // Open the AST file.
3819 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003820 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3822 if (!Buffer) {
3823 return true;
3824 }
3825
3826 // Initialize the stream
3827 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003828 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3830 (const unsigned char *)Buffer->getBufferEnd());
3831 Stream.init(StreamFile);
3832
3833 // Sniff for the signature.
3834 if (Stream.Read(8) != 'C' ||
3835 Stream.Read(8) != 'P' ||
3836 Stream.Read(8) != 'C' ||
3837 Stream.Read(8) != 'H') {
3838 return true;
3839 }
3840
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003841 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003842 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003843 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003844
3845 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003846 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003847 BitstreamCursor InputFilesCursor;
3848 if (NeedsInputFiles) {
3849 InputFilesCursor = Stream;
3850 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3851 return true;
3852
3853 // Read the abbreviations
3854 while (true) {
3855 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3856 unsigned Code = InputFilesCursor.ReadCode();
3857
3858 // We expect all abbrevs to be at the start of the block.
3859 if (Code != llvm::bitc::DEFINE_ABBREV) {
3860 InputFilesCursor.JumpToBit(Offset);
3861 break;
3862 }
3863 InputFilesCursor.ReadAbbrevRecord();
3864 }
3865 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003866
3867 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003869 while (1) {
3870 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3871 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3872 return false;
3873
3874 if (Entry.Kind != llvm::BitstreamEntry::Record)
3875 return true;
3876
Guy Benyei11169dd2012-12-18 14:30:41 +00003877 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003878 StringRef Blob;
3879 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003880 switch ((ControlRecordTypes)RecCode) {
3881 case METADATA: {
3882 if (Record[0] != VERSION_MAJOR)
3883 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003884
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003885 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003886 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003887
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003888 break;
3889 }
3890 case LANGUAGE_OPTIONS:
3891 if (ParseLanguageOptions(Record, false, Listener))
3892 return true;
3893 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003894
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003895 case TARGET_OPTIONS:
3896 if (ParseTargetOptions(Record, false, Listener))
3897 return true;
3898 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003899
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003900 case DIAGNOSTIC_OPTIONS:
3901 if (ParseDiagnosticOptions(Record, false, Listener))
3902 return true;
3903 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003904
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003905 case FILE_SYSTEM_OPTIONS:
3906 if (ParseFileSystemOptions(Record, false, Listener))
3907 return true;
3908 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003909
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003910 case HEADER_SEARCH_OPTIONS:
3911 if (ParseHeaderSearchOptions(Record, false, Listener))
3912 return true;
3913 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003914
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003915 case PREPROCESSOR_OPTIONS: {
3916 std::string IgnoredSuggestedPredefines;
3917 if (ParsePreprocessorOptions(Record, false, Listener,
3918 IgnoredSuggestedPredefines))
3919 return true;
3920 break;
3921 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003922
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003923 case INPUT_FILE_OFFSETS: {
3924 if (!NeedsInputFiles)
3925 break;
3926
3927 unsigned NumInputFiles = Record[0];
3928 unsigned NumUserFiles = Record[1];
3929 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3930 for (unsigned I = 0; I != NumInputFiles; ++I) {
3931 // Go find this input file.
3932 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00003933
3934 if (isSystemFile && !NeedsSystemInputFiles)
3935 break; // the rest are system input files
3936
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003937 BitstreamCursor &Cursor = InputFilesCursor;
3938 SavedStreamPosition SavedPosition(Cursor);
3939 Cursor.JumpToBit(InputFileOffs[I]);
3940
3941 unsigned Code = Cursor.ReadCode();
3942 RecordData Record;
3943 StringRef Blob;
3944 bool shouldContinue = false;
3945 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3946 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00003947 bool Overridden = static_cast<bool>(Record[3]);
3948 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003949 break;
3950 }
3951 if (!shouldContinue)
3952 break;
3953 }
3954 break;
3955 }
3956
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003957 default:
3958 // No other validation to perform.
3959 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 }
3961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003962}
3963
3964
3965bool ASTReader::isAcceptableASTFile(StringRef Filename,
3966 FileManager &FileMgr,
3967 const LangOptions &LangOpts,
3968 const TargetOptions &TargetOpts,
3969 const PreprocessorOptions &PPOpts) {
3970 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3971 return !readASTFileControlBlock(Filename, FileMgr, validator);
3972}
3973
3974bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3975 // Enter the submodule block.
3976 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3977 Error("malformed submodule block record in AST file");
3978 return true;
3979 }
3980
3981 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3982 bool First = true;
3983 Module *CurrentModule = 0;
3984 RecordData Record;
3985 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003986 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3987
3988 switch (Entry.Kind) {
3989 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3990 case llvm::BitstreamEntry::Error:
3991 Error("malformed block record in AST file");
3992 return true;
3993 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003995 case llvm::BitstreamEntry::Record:
3996 // The interesting case.
3997 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003999
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004001 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004003 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 default: // Default behavior: ignore.
4005 break;
4006
4007 case SUBMODULE_DEFINITION: {
4008 if (First) {
4009 Error("missing submodule metadata record at beginning of block");
4010 return true;
4011 }
4012
Douglas Gregor8d932422013-03-20 03:59:18 +00004013 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 Error("malformed module definition");
4015 return true;
4016 }
4017
Chris Lattner0e6c9402013-01-20 02:38:54 +00004018 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004019 unsigned Idx = 0;
4020 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4021 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4022 bool IsFramework = Record[Idx++];
4023 bool IsExplicit = Record[Idx++];
4024 bool IsSystem = Record[Idx++];
4025 bool IsExternC = Record[Idx++];
4026 bool InferSubmodules = Record[Idx++];
4027 bool InferExplicitSubmodules = Record[Idx++];
4028 bool InferExportWildcard = Record[Idx++];
4029 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004030
Guy Benyei11169dd2012-12-18 14:30:41 +00004031 Module *ParentModule = 0;
4032 if (Parent)
4033 ParentModule = getSubmodule(Parent);
4034
4035 // Retrieve this (sub)module from the module map, creating it if
4036 // necessary.
4037 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4038 IsFramework,
4039 IsExplicit).first;
4040 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4041 if (GlobalIndex >= SubmodulesLoaded.size() ||
4042 SubmodulesLoaded[GlobalIndex]) {
4043 Error("too many submodules");
4044 return true;
4045 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004046
Douglas Gregor7029ce12013-03-19 00:28:20 +00004047 if (!ParentModule) {
4048 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4049 if (CurFile != F.File) {
4050 if (!Diags.isDiagnosticInFlight()) {
4051 Diag(diag::err_module_file_conflict)
4052 << CurrentModule->getTopLevelModuleName()
4053 << CurFile->getName()
4054 << F.File->getName();
4055 }
4056 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004057 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004058 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004059
4060 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004061 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004062
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 CurrentModule->IsFromModuleFile = true;
4064 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004065 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 CurrentModule->InferSubmodules = InferSubmodules;
4067 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4068 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004069 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 if (DeserializationListener)
4071 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4072
4073 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004074
Douglas Gregorfb912652013-03-20 21:10:35 +00004075 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004076 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004077 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004078 CurrentModule->UnresolvedConflicts.clear();
4079 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004080 break;
4081 }
4082
4083 case SUBMODULE_UMBRELLA_HEADER: {
4084 if (First) {
4085 Error("missing submodule metadata record at beginning of block");
4086 return true;
4087 }
4088
4089 if (!CurrentModule)
4090 break;
4091
Chris Lattner0e6c9402013-01-20 02:38:54 +00004092 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 if (!CurrentModule->getUmbrellaHeader())
4094 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4095 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4096 Error("mismatched umbrella headers in submodule");
4097 return true;
4098 }
4099 }
4100 break;
4101 }
4102
4103 case SUBMODULE_HEADER: {
4104 if (First) {
4105 Error("missing submodule metadata record at beginning of block");
4106 return true;
4107 }
4108
4109 if (!CurrentModule)
4110 break;
4111
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004112 // We lazily associate headers with their modules via the HeaderInfoTable.
4113 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4114 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 break;
4116 }
4117
4118 case SUBMODULE_EXCLUDED_HEADER: {
4119 if (First) {
4120 Error("missing submodule metadata record at beginning of block");
4121 return true;
4122 }
4123
4124 if (!CurrentModule)
4125 break;
4126
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004127 // We lazily associate headers with their modules via the HeaderInfoTable.
4128 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4129 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 break;
4131 }
4132
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004133 case SUBMODULE_PRIVATE_HEADER: {
4134 if (First) {
4135 Error("missing submodule metadata record at beginning of block");
4136 return true;
4137 }
4138
4139 if (!CurrentModule)
4140 break;
4141
4142 // We lazily associate headers with their modules via the HeaderInfoTable.
4143 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4144 // of complete filenames or remove it entirely.
4145 break;
4146 }
4147
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 case SUBMODULE_TOPHEADER: {
4149 if (First) {
4150 Error("missing submodule metadata record at beginning of block");
4151 return true;
4152 }
4153
4154 if (!CurrentModule)
4155 break;
4156
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004157 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 break;
4159 }
4160
4161 case SUBMODULE_UMBRELLA_DIR: {
4162 if (First) {
4163 Error("missing submodule metadata record at beginning of block");
4164 return true;
4165 }
4166
4167 if (!CurrentModule)
4168 break;
4169
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004171 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 if (!CurrentModule->getUmbrellaDir())
4173 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4174 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4175 Error("mismatched umbrella directories in submodule");
4176 return true;
4177 }
4178 }
4179 break;
4180 }
4181
4182 case SUBMODULE_METADATA: {
4183 if (!First) {
4184 Error("submodule metadata record not at beginning of block");
4185 return true;
4186 }
4187 First = false;
4188
4189 F.BaseSubmoduleID = getTotalNumSubmodules();
4190 F.LocalNumSubmodules = Record[0];
4191 unsigned LocalBaseSubmoduleID = Record[1];
4192 if (F.LocalNumSubmodules > 0) {
4193 // Introduce the global -> local mapping for submodules within this
4194 // module.
4195 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4196
4197 // Introduce the local -> global mapping for submodules within this
4198 // module.
4199 F.SubmoduleRemap.insertOrReplace(
4200 std::make_pair(LocalBaseSubmoduleID,
4201 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4202
4203 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4204 }
4205 break;
4206 }
4207
4208 case SUBMODULE_IMPORTS: {
4209 if (First) {
4210 Error("missing submodule metadata record at beginning of block");
4211 return true;
4212 }
4213
4214 if (!CurrentModule)
4215 break;
4216
4217 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004218 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 Unresolved.File = &F;
4220 Unresolved.Mod = CurrentModule;
4221 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004222 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004224 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 }
4226 break;
4227 }
4228
4229 case SUBMODULE_EXPORTS: {
4230 if (First) {
4231 Error("missing submodule metadata record at beginning of block");
4232 return true;
4233 }
4234
4235 if (!CurrentModule)
4236 break;
4237
4238 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004239 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 Unresolved.File = &F;
4241 Unresolved.Mod = CurrentModule;
4242 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004243 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004245 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 }
4247
4248 // Once we've loaded the set of exports, there's no reason to keep
4249 // the parsed, unresolved exports around.
4250 CurrentModule->UnresolvedExports.clear();
4251 break;
4252 }
4253 case SUBMODULE_REQUIRES: {
4254 if (First) {
4255 Error("missing submodule metadata record at beginning of block");
4256 return true;
4257 }
4258
4259 if (!CurrentModule)
4260 break;
4261
Richard Smitha3feee22013-10-28 22:18:19 +00004262 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 Context.getTargetInfo());
4264 break;
4265 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004266
4267 case SUBMODULE_LINK_LIBRARY:
4268 if (First) {
4269 Error("missing submodule metadata record at beginning of block");
4270 return true;
4271 }
4272
4273 if (!CurrentModule)
4274 break;
4275
4276 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004277 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004278 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004279
4280 case SUBMODULE_CONFIG_MACRO:
4281 if (First) {
4282 Error("missing submodule metadata record at beginning of block");
4283 return true;
4284 }
4285
4286 if (!CurrentModule)
4287 break;
4288
4289 CurrentModule->ConfigMacros.push_back(Blob.str());
4290 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004291
4292 case SUBMODULE_CONFLICT: {
4293 if (First) {
4294 Error("missing submodule metadata record at beginning of block");
4295 return true;
4296 }
4297
4298 if (!CurrentModule)
4299 break;
4300
4301 UnresolvedModuleRef Unresolved;
4302 Unresolved.File = &F;
4303 Unresolved.Mod = CurrentModule;
4304 Unresolved.ID = Record[0];
4305 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4306 Unresolved.IsWildcard = false;
4307 Unresolved.String = Blob;
4308 UnresolvedModuleRefs.push_back(Unresolved);
4309 break;
4310 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 }
4312 }
4313}
4314
4315/// \brief Parse the record that corresponds to a LangOptions data
4316/// structure.
4317///
4318/// This routine parses the language options from the AST file and then gives
4319/// them to the AST listener if one is set.
4320///
4321/// \returns true if the listener deems the file unacceptable, false otherwise.
4322bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4323 bool Complain,
4324 ASTReaderListener &Listener) {
4325 LangOptions LangOpts;
4326 unsigned Idx = 0;
4327#define LANGOPT(Name, Bits, Default, Description) \
4328 LangOpts.Name = Record[Idx++];
4329#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4330 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4331#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004332#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4333#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004334
4335 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4336 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4337 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4338
4339 unsigned Length = Record[Idx++];
4340 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4341 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004342
4343 Idx += Length;
4344
4345 // Comment options.
4346 for (unsigned N = Record[Idx++]; N; --N) {
4347 LangOpts.CommentOpts.BlockCommandNames.push_back(
4348 ReadString(Record, Idx));
4349 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004350 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004351
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 return Listener.ReadLanguageOptions(LangOpts, Complain);
4353}
4354
4355bool ASTReader::ParseTargetOptions(const RecordData &Record,
4356 bool Complain,
4357 ASTReaderListener &Listener) {
4358 unsigned Idx = 0;
4359 TargetOptions TargetOpts;
4360 TargetOpts.Triple = ReadString(Record, Idx);
4361 TargetOpts.CPU = ReadString(Record, Idx);
4362 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4364 for (unsigned N = Record[Idx++]; N; --N) {
4365 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4366 }
4367 for (unsigned N = Record[Idx++]; N; --N) {
4368 TargetOpts.Features.push_back(ReadString(Record, Idx));
4369 }
4370
4371 return Listener.ReadTargetOptions(TargetOpts, Complain);
4372}
4373
4374bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4375 ASTReaderListener &Listener) {
4376 DiagnosticOptions DiagOpts;
4377 unsigned Idx = 0;
4378#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4379#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4380 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4381#include "clang/Basic/DiagnosticOptions.def"
4382
4383 for (unsigned N = Record[Idx++]; N; --N) {
4384 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4385 }
4386
4387 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4388}
4389
4390bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4391 ASTReaderListener &Listener) {
4392 FileSystemOptions FSOpts;
4393 unsigned Idx = 0;
4394 FSOpts.WorkingDir = ReadString(Record, Idx);
4395 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4396}
4397
4398bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4399 bool Complain,
4400 ASTReaderListener &Listener) {
4401 HeaderSearchOptions HSOpts;
4402 unsigned Idx = 0;
4403 HSOpts.Sysroot = ReadString(Record, Idx);
4404
4405 // Include entries.
4406 for (unsigned N = Record[Idx++]; N; --N) {
4407 std::string Path = ReadString(Record, Idx);
4408 frontend::IncludeDirGroup Group
4409 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 bool IsFramework = Record[Idx++];
4411 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004413 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 }
4415
4416 // System header prefixes.
4417 for (unsigned N = Record[Idx++]; N; --N) {
4418 std::string Prefix = ReadString(Record, Idx);
4419 bool IsSystemHeader = Record[Idx++];
4420 HSOpts.SystemHeaderPrefixes.push_back(
4421 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4422 }
4423
4424 HSOpts.ResourceDir = ReadString(Record, Idx);
4425 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004426 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 HSOpts.DisableModuleHash = Record[Idx++];
4428 HSOpts.UseBuiltinIncludes = Record[Idx++];
4429 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4430 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4431 HSOpts.UseLibcxx = Record[Idx++];
4432
4433 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4434}
4435
4436bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4437 bool Complain,
4438 ASTReaderListener &Listener,
4439 std::string &SuggestedPredefines) {
4440 PreprocessorOptions PPOpts;
4441 unsigned Idx = 0;
4442
4443 // Macro definitions/undefs
4444 for (unsigned N = Record[Idx++]; N; --N) {
4445 std::string Macro = ReadString(Record, Idx);
4446 bool IsUndef = Record[Idx++];
4447 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4448 }
4449
4450 // Includes
4451 for (unsigned N = Record[Idx++]; N; --N) {
4452 PPOpts.Includes.push_back(ReadString(Record, Idx));
4453 }
4454
4455 // Macro Includes
4456 for (unsigned N = Record[Idx++]; N; --N) {
4457 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4458 }
4459
4460 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004461 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4463 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4464 PPOpts.ObjCXXARCStandardLibrary =
4465 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4466 SuggestedPredefines.clear();
4467 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4468 SuggestedPredefines);
4469}
4470
4471std::pair<ModuleFile *, unsigned>
4472ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4473 GlobalPreprocessedEntityMapType::iterator
4474 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4475 assert(I != GlobalPreprocessedEntityMap.end() &&
4476 "Corrupted global preprocessed entity map");
4477 ModuleFile *M = I->second;
4478 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4479 return std::make_pair(M, LocalIndex);
4480}
4481
4482std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4483ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4484 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4485 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4486 Mod.NumPreprocessedEntities);
4487
4488 return std::make_pair(PreprocessingRecord::iterator(),
4489 PreprocessingRecord::iterator());
4490}
4491
4492std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4493ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4494 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4495 ModuleDeclIterator(this, &Mod,
4496 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4497}
4498
4499PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4500 PreprocessedEntityID PPID = Index+1;
4501 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4502 ModuleFile &M = *PPInfo.first;
4503 unsigned LocalIndex = PPInfo.second;
4504 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4505
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 if (!PP.getPreprocessingRecord()) {
4507 Error("no preprocessing record");
4508 return 0;
4509 }
4510
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004511 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4512 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4513
4514 llvm::BitstreamEntry Entry =
4515 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4516 if (Entry.Kind != llvm::BitstreamEntry::Record)
4517 return 0;
4518
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 // Read the record.
4520 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4521 ReadSourceLocation(M, PPOffs.End));
4522 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004523 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 RecordData Record;
4525 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004526 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4527 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 switch (RecType) {
4529 case PPD_MACRO_EXPANSION: {
4530 bool isBuiltin = Record[0];
4531 IdentifierInfo *Name = 0;
4532 MacroDefinition *Def = 0;
4533 if (isBuiltin)
4534 Name = getLocalIdentifier(M, Record[1]);
4535 else {
4536 PreprocessedEntityID
4537 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4538 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4539 }
4540
4541 MacroExpansion *ME;
4542 if (isBuiltin)
4543 ME = new (PPRec) MacroExpansion(Name, Range);
4544 else
4545 ME = new (PPRec) MacroExpansion(Def, Range);
4546
4547 return ME;
4548 }
4549
4550 case PPD_MACRO_DEFINITION: {
4551 // Decode the identifier info and then check again; if the macro is
4552 // still defined and associated with the identifier,
4553 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4554 MacroDefinition *MD
4555 = new (PPRec) MacroDefinition(II, Range);
4556
4557 if (DeserializationListener)
4558 DeserializationListener->MacroDefinitionRead(PPID, MD);
4559
4560 return MD;
4561 }
4562
4563 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004564 const char *FullFileNameStart = Blob.data() + Record[0];
4565 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 const FileEntry *File = 0;
4567 if (!FullFileName.empty())
4568 File = PP.getFileManager().getFile(FullFileName);
4569
4570 // FIXME: Stable encoding
4571 InclusionDirective::InclusionKind Kind
4572 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4573 InclusionDirective *ID
4574 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004575 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 Record[1], Record[3],
4577 File,
4578 Range);
4579 return ID;
4580 }
4581 }
4582
4583 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4584}
4585
4586/// \brief \arg SLocMapI points at a chunk of a module that contains no
4587/// preprocessed entities or the entities it contains are not the ones we are
4588/// looking for. Find the next module that contains entities and return the ID
4589/// of the first entry.
4590PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4591 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4592 ++SLocMapI;
4593 for (GlobalSLocOffsetMapType::const_iterator
4594 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4595 ModuleFile &M = *SLocMapI->second;
4596 if (M.NumPreprocessedEntities)
4597 return M.BasePreprocessedEntityID;
4598 }
4599
4600 return getTotalNumPreprocessedEntities();
4601}
4602
4603namespace {
4604
4605template <unsigned PPEntityOffset::*PPLoc>
4606struct PPEntityComp {
4607 const ASTReader &Reader;
4608 ModuleFile &M;
4609
4610 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4611
4612 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4613 SourceLocation LHS = getLoc(L);
4614 SourceLocation RHS = getLoc(R);
4615 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4616 }
4617
4618 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4619 SourceLocation LHS = getLoc(L);
4620 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4621 }
4622
4623 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4624 SourceLocation RHS = getLoc(R);
4625 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4626 }
4627
4628 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4629 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4630 }
4631};
4632
4633}
4634
4635/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4636PreprocessedEntityID
4637ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4638 if (SourceMgr.isLocalSourceLocation(BLoc))
4639 return getTotalNumPreprocessedEntities();
4640
4641 GlobalSLocOffsetMapType::const_iterator
4642 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004643 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4645 "Corrupted global sloc offset map");
4646
4647 if (SLocMapI->second->NumPreprocessedEntities == 0)
4648 return findNextPreprocessedEntity(SLocMapI);
4649
4650 ModuleFile &M = *SLocMapI->second;
4651 typedef const PPEntityOffset *pp_iterator;
4652 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4653 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4654
4655 size_t Count = M.NumPreprocessedEntities;
4656 size_t Half;
4657 pp_iterator First = pp_begin;
4658 pp_iterator PPI;
4659
4660 // Do a binary search manually instead of using std::lower_bound because
4661 // The end locations of entities may be unordered (when a macro expansion
4662 // is inside another macro argument), but for this case it is not important
4663 // whether we get the first macro expansion or its containing macro.
4664 while (Count > 0) {
4665 Half = Count/2;
4666 PPI = First;
4667 std::advance(PPI, Half);
4668 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4669 BLoc)){
4670 First = PPI;
4671 ++First;
4672 Count = Count - Half - 1;
4673 } else
4674 Count = Half;
4675 }
4676
4677 if (PPI == pp_end)
4678 return findNextPreprocessedEntity(SLocMapI);
4679
4680 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4681}
4682
4683/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4684PreprocessedEntityID
4685ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4686 if (SourceMgr.isLocalSourceLocation(ELoc))
4687 return getTotalNumPreprocessedEntities();
4688
4689 GlobalSLocOffsetMapType::const_iterator
4690 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004691 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4693 "Corrupted global sloc offset map");
4694
4695 if (SLocMapI->second->NumPreprocessedEntities == 0)
4696 return findNextPreprocessedEntity(SLocMapI);
4697
4698 ModuleFile &M = *SLocMapI->second;
4699 typedef const PPEntityOffset *pp_iterator;
4700 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4701 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4702 pp_iterator PPI =
4703 std::upper_bound(pp_begin, pp_end, ELoc,
4704 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4705
4706 if (PPI == pp_end)
4707 return findNextPreprocessedEntity(SLocMapI);
4708
4709 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4710}
4711
4712/// \brief Returns a pair of [Begin, End) indices of preallocated
4713/// preprocessed entities that \arg Range encompasses.
4714std::pair<unsigned, unsigned>
4715 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4716 if (Range.isInvalid())
4717 return std::make_pair(0,0);
4718 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4719
4720 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4721 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4722 return std::make_pair(BeginID, EndID);
4723}
4724
4725/// \brief Optionally returns true or false if the preallocated preprocessed
4726/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004727Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004728 FileID FID) {
4729 if (FID.isInvalid())
4730 return false;
4731
4732 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4733 ModuleFile &M = *PPInfo.first;
4734 unsigned LocalIndex = PPInfo.second;
4735 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4736
4737 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4738 if (Loc.isInvalid())
4739 return false;
4740
4741 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4742 return true;
4743 else
4744 return false;
4745}
4746
4747namespace {
4748 /// \brief Visitor used to search for information about a header file.
4749 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 const FileEntry *FE;
4751
David Blaikie05785d12013-02-20 22:23:23 +00004752 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004753
4754 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004755 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4756 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004757
4758 static bool visit(ModuleFile &M, void *UserData) {
4759 HeaderFileInfoVisitor *This
4760 = static_cast<HeaderFileInfoVisitor *>(UserData);
4761
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 HeaderFileInfoLookupTable *Table
4763 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4764 if (!Table)
4765 return false;
4766
4767 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004768 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 if (Pos == Table->end())
4770 return false;
4771
4772 This->HFI = *Pos;
4773 return true;
4774 }
4775
David Blaikie05785d12013-02-20 22:23:23 +00004776 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004777 };
4778}
4779
4780HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004781 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004783 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004785
4786 return HeaderFileInfo();
4787}
4788
4789void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4790 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004791 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4793 ModuleFile &F = *(*I);
4794 unsigned Idx = 0;
4795 DiagStates.clear();
4796 assert(!Diag.DiagStates.empty());
4797 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4798 while (Idx < F.PragmaDiagMappings.size()) {
4799 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4800 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4801 if (DiagStateID != 0) {
4802 Diag.DiagStatePoints.push_back(
4803 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4804 FullSourceLoc(Loc, SourceMgr)));
4805 continue;
4806 }
4807
4808 assert(DiagStateID == 0);
4809 // A new DiagState was created here.
4810 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4811 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4812 DiagStates.push_back(NewState);
4813 Diag.DiagStatePoints.push_back(
4814 DiagnosticsEngine::DiagStatePoint(NewState,
4815 FullSourceLoc(Loc, SourceMgr)));
4816 while (1) {
4817 assert(Idx < F.PragmaDiagMappings.size() &&
4818 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4819 if (Idx >= F.PragmaDiagMappings.size()) {
4820 break; // Something is messed up but at least avoid infinite loop in
4821 // release build.
4822 }
4823 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4824 if (DiagID == (unsigned)-1) {
4825 break; // no more diag/map pairs for this location.
4826 }
4827 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4828 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4829 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4830 }
4831 }
4832 }
4833}
4834
4835/// \brief Get the correct cursor and offset for loading a type.
4836ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4837 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4838 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4839 ModuleFile *M = I->second;
4840 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4841}
4842
4843/// \brief Read and return the type with the given index..
4844///
4845/// The index is the type ID, shifted and minus the number of predefs. This
4846/// routine actually reads the record corresponding to the type at the given
4847/// location. It is a helper routine for GetType, which deals with reading type
4848/// IDs.
4849QualType ASTReader::readTypeRecord(unsigned Index) {
4850 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004851 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004852
4853 // Keep track of where we are in the stream, then jump back there
4854 // after reading this type.
4855 SavedStreamPosition SavedPosition(DeclsCursor);
4856
4857 ReadingKindTracker ReadingKind(Read_Type, *this);
4858
4859 // Note that we are loading a type record.
4860 Deserializing AType(this);
4861
4862 unsigned Idx = 0;
4863 DeclsCursor.JumpToBit(Loc.Offset);
4864 RecordData Record;
4865 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004866 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 case TYPE_EXT_QUAL: {
4868 if (Record.size() != 2) {
4869 Error("Incorrect encoding of extended qualifier type");
4870 return QualType();
4871 }
4872 QualType Base = readType(*Loc.F, Record, Idx);
4873 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4874 return Context.getQualifiedType(Base, Quals);
4875 }
4876
4877 case TYPE_COMPLEX: {
4878 if (Record.size() != 1) {
4879 Error("Incorrect encoding of complex type");
4880 return QualType();
4881 }
4882 QualType ElemType = readType(*Loc.F, Record, Idx);
4883 return Context.getComplexType(ElemType);
4884 }
4885
4886 case TYPE_POINTER: {
4887 if (Record.size() != 1) {
4888 Error("Incorrect encoding of pointer type");
4889 return QualType();
4890 }
4891 QualType PointeeType = readType(*Loc.F, Record, Idx);
4892 return Context.getPointerType(PointeeType);
4893 }
4894
Reid Kleckner8a365022013-06-24 17:51:48 +00004895 case TYPE_DECAYED: {
4896 if (Record.size() != 1) {
4897 Error("Incorrect encoding of decayed type");
4898 return QualType();
4899 }
4900 QualType OriginalType = readType(*Loc.F, Record, Idx);
4901 QualType DT = Context.getAdjustedParameterType(OriginalType);
4902 if (!isa<DecayedType>(DT))
4903 Error("Decayed type does not decay");
4904 return DT;
4905 }
4906
Reid Kleckner0503a872013-12-05 01:23:43 +00004907 case TYPE_ADJUSTED: {
4908 if (Record.size() != 2) {
4909 Error("Incorrect encoding of adjusted type");
4910 return QualType();
4911 }
4912 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4913 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4914 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4915 }
4916
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 case TYPE_BLOCK_POINTER: {
4918 if (Record.size() != 1) {
4919 Error("Incorrect encoding of block pointer type");
4920 return QualType();
4921 }
4922 QualType PointeeType = readType(*Loc.F, Record, Idx);
4923 return Context.getBlockPointerType(PointeeType);
4924 }
4925
4926 case TYPE_LVALUE_REFERENCE: {
4927 if (Record.size() != 2) {
4928 Error("Incorrect encoding of lvalue reference type");
4929 return QualType();
4930 }
4931 QualType PointeeType = readType(*Loc.F, Record, Idx);
4932 return Context.getLValueReferenceType(PointeeType, Record[1]);
4933 }
4934
4935 case TYPE_RVALUE_REFERENCE: {
4936 if (Record.size() != 1) {
4937 Error("Incorrect encoding of rvalue reference type");
4938 return QualType();
4939 }
4940 QualType PointeeType = readType(*Loc.F, Record, Idx);
4941 return Context.getRValueReferenceType(PointeeType);
4942 }
4943
4944 case TYPE_MEMBER_POINTER: {
4945 if (Record.size() != 2) {
4946 Error("Incorrect encoding of member pointer type");
4947 return QualType();
4948 }
4949 QualType PointeeType = readType(*Loc.F, Record, Idx);
4950 QualType ClassType = readType(*Loc.F, Record, Idx);
4951 if (PointeeType.isNull() || ClassType.isNull())
4952 return QualType();
4953
4954 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4955 }
4956
4957 case TYPE_CONSTANT_ARRAY: {
4958 QualType ElementType = readType(*Loc.F, Record, Idx);
4959 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4960 unsigned IndexTypeQuals = Record[2];
4961 unsigned Idx = 3;
4962 llvm::APInt Size = ReadAPInt(Record, Idx);
4963 return Context.getConstantArrayType(ElementType, Size,
4964 ASM, IndexTypeQuals);
4965 }
4966
4967 case TYPE_INCOMPLETE_ARRAY: {
4968 QualType ElementType = readType(*Loc.F, Record, Idx);
4969 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4970 unsigned IndexTypeQuals = Record[2];
4971 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4972 }
4973
4974 case TYPE_VARIABLE_ARRAY: {
4975 QualType ElementType = readType(*Loc.F, Record, Idx);
4976 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4977 unsigned IndexTypeQuals = Record[2];
4978 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4979 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4980 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4981 ASM, IndexTypeQuals,
4982 SourceRange(LBLoc, RBLoc));
4983 }
4984
4985 case TYPE_VECTOR: {
4986 if (Record.size() != 3) {
4987 Error("incorrect encoding of vector type in AST file");
4988 return QualType();
4989 }
4990
4991 QualType ElementType = readType(*Loc.F, Record, Idx);
4992 unsigned NumElements = Record[1];
4993 unsigned VecKind = Record[2];
4994 return Context.getVectorType(ElementType, NumElements,
4995 (VectorType::VectorKind)VecKind);
4996 }
4997
4998 case TYPE_EXT_VECTOR: {
4999 if (Record.size() != 3) {
5000 Error("incorrect encoding of extended vector type in AST file");
5001 return QualType();
5002 }
5003
5004 QualType ElementType = readType(*Loc.F, Record, Idx);
5005 unsigned NumElements = Record[1];
5006 return Context.getExtVectorType(ElementType, NumElements);
5007 }
5008
5009 case TYPE_FUNCTION_NO_PROTO: {
5010 if (Record.size() != 6) {
5011 Error("incorrect encoding of no-proto function type");
5012 return QualType();
5013 }
5014 QualType ResultType = readType(*Loc.F, Record, Idx);
5015 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5016 (CallingConv)Record[4], Record[5]);
5017 return Context.getFunctionNoProtoType(ResultType, Info);
5018 }
5019
5020 case TYPE_FUNCTION_PROTO: {
5021 QualType ResultType = readType(*Loc.F, Record, Idx);
5022
5023 FunctionProtoType::ExtProtoInfo EPI;
5024 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5025 /*hasregparm*/ Record[2],
5026 /*regparm*/ Record[3],
5027 static_cast<CallingConv>(Record[4]),
5028 /*produces*/ Record[5]);
5029
5030 unsigned Idx = 6;
5031 unsigned NumParams = Record[Idx++];
5032 SmallVector<QualType, 16> ParamTypes;
5033 for (unsigned I = 0; I != NumParams; ++I)
5034 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5035
5036 EPI.Variadic = Record[Idx++];
5037 EPI.HasTrailingReturn = Record[Idx++];
5038 EPI.TypeQuals = Record[Idx++];
5039 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5040 ExceptionSpecificationType EST =
5041 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5042 EPI.ExceptionSpecType = EST;
5043 SmallVector<QualType, 2> Exceptions;
5044 if (EST == EST_Dynamic) {
5045 EPI.NumExceptions = Record[Idx++];
5046 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5047 Exceptions.push_back(readType(*Loc.F, Record, Idx));
5048 EPI.Exceptions = Exceptions.data();
5049 } else if (EST == EST_ComputedNoexcept) {
5050 EPI.NoexceptExpr = ReadExpr(*Loc.F);
5051 } else if (EST == EST_Uninstantiated) {
5052 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5053 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5054 } else if (EST == EST_Unevaluated) {
5055 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5056 }
Jordan Rose5c382722013-03-08 21:51:21 +00005057 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 }
5059
5060 case TYPE_UNRESOLVED_USING: {
5061 unsigned Idx = 0;
5062 return Context.getTypeDeclType(
5063 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5064 }
5065
5066 case TYPE_TYPEDEF: {
5067 if (Record.size() != 2) {
5068 Error("incorrect encoding of typedef type");
5069 return QualType();
5070 }
5071 unsigned Idx = 0;
5072 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5073 QualType Canonical = readType(*Loc.F, Record, Idx);
5074 if (!Canonical.isNull())
5075 Canonical = Context.getCanonicalType(Canonical);
5076 return Context.getTypedefType(Decl, Canonical);
5077 }
5078
5079 case TYPE_TYPEOF_EXPR:
5080 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5081
5082 case TYPE_TYPEOF: {
5083 if (Record.size() != 1) {
5084 Error("incorrect encoding of typeof(type) in AST file");
5085 return QualType();
5086 }
5087 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5088 return Context.getTypeOfType(UnderlyingType);
5089 }
5090
5091 case TYPE_DECLTYPE: {
5092 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5093 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5094 }
5095
5096 case TYPE_UNARY_TRANSFORM: {
5097 QualType BaseType = readType(*Loc.F, Record, Idx);
5098 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5099 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5100 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5101 }
5102
Richard Smith74aeef52013-04-26 16:15:35 +00005103 case TYPE_AUTO: {
5104 QualType Deduced = readType(*Loc.F, Record, Idx);
5105 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005106 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005107 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005109
5110 case TYPE_RECORD: {
5111 if (Record.size() != 2) {
5112 Error("incorrect encoding of record type");
5113 return QualType();
5114 }
5115 unsigned Idx = 0;
5116 bool IsDependent = Record[Idx++];
5117 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5118 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5119 QualType T = Context.getRecordType(RD);
5120 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5121 return T;
5122 }
5123
5124 case TYPE_ENUM: {
5125 if (Record.size() != 2) {
5126 Error("incorrect encoding of enum type");
5127 return QualType();
5128 }
5129 unsigned Idx = 0;
5130 bool IsDependent = Record[Idx++];
5131 QualType T
5132 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5133 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5134 return T;
5135 }
5136
5137 case TYPE_ATTRIBUTED: {
5138 if (Record.size() != 3) {
5139 Error("incorrect encoding of attributed type");
5140 return QualType();
5141 }
5142 QualType modifiedType = readType(*Loc.F, Record, Idx);
5143 QualType equivalentType = readType(*Loc.F, Record, Idx);
5144 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5145 return Context.getAttributedType(kind, modifiedType, equivalentType);
5146 }
5147
5148 case TYPE_PAREN: {
5149 if (Record.size() != 1) {
5150 Error("incorrect encoding of paren type");
5151 return QualType();
5152 }
5153 QualType InnerType = readType(*Loc.F, Record, Idx);
5154 return Context.getParenType(InnerType);
5155 }
5156
5157 case TYPE_PACK_EXPANSION: {
5158 if (Record.size() != 2) {
5159 Error("incorrect encoding of pack expansion type");
5160 return QualType();
5161 }
5162 QualType Pattern = readType(*Loc.F, Record, Idx);
5163 if (Pattern.isNull())
5164 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005165 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 if (Record[1])
5167 NumExpansions = Record[1] - 1;
5168 return Context.getPackExpansionType(Pattern, NumExpansions);
5169 }
5170
5171 case TYPE_ELABORATED: {
5172 unsigned Idx = 0;
5173 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5174 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5175 QualType NamedType = readType(*Loc.F, Record, Idx);
5176 return Context.getElaboratedType(Keyword, NNS, NamedType);
5177 }
5178
5179 case TYPE_OBJC_INTERFACE: {
5180 unsigned Idx = 0;
5181 ObjCInterfaceDecl *ItfD
5182 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5183 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5184 }
5185
5186 case TYPE_OBJC_OBJECT: {
5187 unsigned Idx = 0;
5188 QualType Base = readType(*Loc.F, Record, Idx);
5189 unsigned NumProtos = Record[Idx++];
5190 SmallVector<ObjCProtocolDecl*, 4> Protos;
5191 for (unsigned I = 0; I != NumProtos; ++I)
5192 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5193 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5194 }
5195
5196 case TYPE_OBJC_OBJECT_POINTER: {
5197 unsigned Idx = 0;
5198 QualType Pointee = readType(*Loc.F, Record, Idx);
5199 return Context.getObjCObjectPointerType(Pointee);
5200 }
5201
5202 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5203 unsigned Idx = 0;
5204 QualType Parm = readType(*Loc.F, Record, Idx);
5205 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005206 return Context.getSubstTemplateTypeParmType(
5207 cast<TemplateTypeParmType>(Parm),
5208 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 }
5210
5211 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5212 unsigned Idx = 0;
5213 QualType Parm = readType(*Loc.F, Record, Idx);
5214 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5215 return Context.getSubstTemplateTypeParmPackType(
5216 cast<TemplateTypeParmType>(Parm),
5217 ArgPack);
5218 }
5219
5220 case TYPE_INJECTED_CLASS_NAME: {
5221 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5222 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5223 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5224 // for AST reading, too much interdependencies.
5225 return
5226 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5227 }
5228
5229 case TYPE_TEMPLATE_TYPE_PARM: {
5230 unsigned Idx = 0;
5231 unsigned Depth = Record[Idx++];
5232 unsigned Index = Record[Idx++];
5233 bool Pack = Record[Idx++];
5234 TemplateTypeParmDecl *D
5235 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5236 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5237 }
5238
5239 case TYPE_DEPENDENT_NAME: {
5240 unsigned Idx = 0;
5241 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5242 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5243 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5244 QualType Canon = readType(*Loc.F, Record, Idx);
5245 if (!Canon.isNull())
5246 Canon = Context.getCanonicalType(Canon);
5247 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5248 }
5249
5250 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5251 unsigned Idx = 0;
5252 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5253 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5254 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5255 unsigned NumArgs = Record[Idx++];
5256 SmallVector<TemplateArgument, 8> Args;
5257 Args.reserve(NumArgs);
5258 while (NumArgs--)
5259 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5260 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5261 Args.size(), Args.data());
5262 }
5263
5264 case TYPE_DEPENDENT_SIZED_ARRAY: {
5265 unsigned Idx = 0;
5266
5267 // ArrayType
5268 QualType ElementType = readType(*Loc.F, Record, Idx);
5269 ArrayType::ArraySizeModifier ASM
5270 = (ArrayType::ArraySizeModifier)Record[Idx++];
5271 unsigned IndexTypeQuals = Record[Idx++];
5272
5273 // DependentSizedArrayType
5274 Expr *NumElts = ReadExpr(*Loc.F);
5275 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5276
5277 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5278 IndexTypeQuals, Brackets);
5279 }
5280
5281 case TYPE_TEMPLATE_SPECIALIZATION: {
5282 unsigned Idx = 0;
5283 bool IsDependent = Record[Idx++];
5284 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5285 SmallVector<TemplateArgument, 8> Args;
5286 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5287 QualType Underlying = readType(*Loc.F, Record, Idx);
5288 QualType T;
5289 if (Underlying.isNull())
5290 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5291 Args.size());
5292 else
5293 T = Context.getTemplateSpecializationType(Name, Args.data(),
5294 Args.size(), Underlying);
5295 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5296 return T;
5297 }
5298
5299 case TYPE_ATOMIC: {
5300 if (Record.size() != 1) {
5301 Error("Incorrect encoding of atomic type");
5302 return QualType();
5303 }
5304 QualType ValueType = readType(*Loc.F, Record, Idx);
5305 return Context.getAtomicType(ValueType);
5306 }
5307 }
5308 llvm_unreachable("Invalid TypeCode!");
5309}
5310
5311class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5312 ASTReader &Reader;
5313 ModuleFile &F;
5314 const ASTReader::RecordData &Record;
5315 unsigned &Idx;
5316
5317 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5318 unsigned &I) {
5319 return Reader.ReadSourceLocation(F, R, I);
5320 }
5321
5322 template<typename T>
5323 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5324 return Reader.ReadDeclAs<T>(F, Record, Idx);
5325 }
5326
5327public:
5328 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5329 const ASTReader::RecordData &Record, unsigned &Idx)
5330 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5331 { }
5332
5333 // We want compile-time assurance that we've enumerated all of
5334 // these, so unfortunately we have to declare them first, then
5335 // define them out-of-line.
5336#define ABSTRACT_TYPELOC(CLASS, PARENT)
5337#define TYPELOC(CLASS, PARENT) \
5338 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5339#include "clang/AST/TypeLocNodes.def"
5340
5341 void VisitFunctionTypeLoc(FunctionTypeLoc);
5342 void VisitArrayTypeLoc(ArrayTypeLoc);
5343};
5344
5345void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5346 // nothing to do
5347}
5348void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5349 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5350 if (TL.needsExtraLocalData()) {
5351 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5352 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5353 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5354 TL.setModeAttr(Record[Idx++]);
5355 }
5356}
5357void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5358 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5359}
5360void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5361 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5362}
Reid Kleckner8a365022013-06-24 17:51:48 +00005363void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5364 // nothing to do
5365}
Reid Kleckner0503a872013-12-05 01:23:43 +00005366void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5367 // nothing to do
5368}
Guy Benyei11169dd2012-12-18 14:30:41 +00005369void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5370 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5371}
5372void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5373 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5374}
5375void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5376 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5377}
5378void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5379 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5380 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5381}
5382void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5383 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5384 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5385 if (Record[Idx++])
5386 TL.setSizeExpr(Reader.ReadExpr(F));
5387 else
5388 TL.setSizeExpr(0);
5389}
5390void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5391 VisitArrayTypeLoc(TL);
5392}
5393void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5394 VisitArrayTypeLoc(TL);
5395}
5396void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5397 VisitArrayTypeLoc(TL);
5398}
5399void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5400 DependentSizedArrayTypeLoc TL) {
5401 VisitArrayTypeLoc(TL);
5402}
5403void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5404 DependentSizedExtVectorTypeLoc TL) {
5405 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5406}
5407void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5408 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5409}
5410void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5411 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5412}
5413void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5414 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5415 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5416 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5417 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005418 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5419 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 }
5421}
5422void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5423 VisitFunctionTypeLoc(TL);
5424}
5425void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5426 VisitFunctionTypeLoc(TL);
5427}
5428void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5429 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5430}
5431void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5432 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5433}
5434void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5435 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5436 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5437 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5438}
5439void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5440 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5441 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5442 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5443 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5444}
5445void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5446 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5447}
5448void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5449 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5450 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5451 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5452 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5453}
5454void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5455 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5456}
5457void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5458 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5459}
5460void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5461 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5462}
5463void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5464 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5465 if (TL.hasAttrOperand()) {
5466 SourceRange range;
5467 range.setBegin(ReadSourceLocation(Record, Idx));
5468 range.setEnd(ReadSourceLocation(Record, Idx));
5469 TL.setAttrOperandParensRange(range);
5470 }
5471 if (TL.hasAttrExprOperand()) {
5472 if (Record[Idx++])
5473 TL.setAttrExprOperand(Reader.ReadExpr(F));
5474 else
5475 TL.setAttrExprOperand(0);
5476 } else if (TL.hasAttrEnumOperand())
5477 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5478}
5479void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5480 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5481}
5482void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5483 SubstTemplateTypeParmTypeLoc TL) {
5484 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5485}
5486void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5487 SubstTemplateTypeParmPackTypeLoc TL) {
5488 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5489}
5490void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5491 TemplateSpecializationTypeLoc TL) {
5492 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5493 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5494 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5495 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5496 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5497 TL.setArgLocInfo(i,
5498 Reader.GetTemplateArgumentLocInfo(F,
5499 TL.getTypePtr()->getArg(i).getKind(),
5500 Record, Idx));
5501}
5502void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5503 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5504 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5505}
5506void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5507 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5508 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5509}
5510void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5511 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5512}
5513void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5514 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5515 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5516 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5517}
5518void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5519 DependentTemplateSpecializationTypeLoc TL) {
5520 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5521 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5522 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5523 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5524 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5525 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5526 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5527 TL.setArgLocInfo(I,
5528 Reader.GetTemplateArgumentLocInfo(F,
5529 TL.getTypePtr()->getArg(I).getKind(),
5530 Record, Idx));
5531}
5532void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5533 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5534}
5535void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5536 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5537}
5538void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5539 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5540 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5541 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5542 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5543 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5544}
5545void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5546 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5549 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5550 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5551 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5552}
5553
5554TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5555 const RecordData &Record,
5556 unsigned &Idx) {
5557 QualType InfoTy = readType(F, Record, Idx);
5558 if (InfoTy.isNull())
5559 return 0;
5560
5561 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5562 TypeLocReader TLR(*this, F, Record, Idx);
5563 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5564 TLR.Visit(TL);
5565 return TInfo;
5566}
5567
5568QualType ASTReader::GetType(TypeID ID) {
5569 unsigned FastQuals = ID & Qualifiers::FastMask;
5570 unsigned Index = ID >> Qualifiers::FastWidth;
5571
5572 if (Index < NUM_PREDEF_TYPE_IDS) {
5573 QualType T;
5574 switch ((PredefinedTypeIDs)Index) {
5575 case PREDEF_TYPE_NULL_ID: return QualType();
5576 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5577 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5578
5579 case PREDEF_TYPE_CHAR_U_ID:
5580 case PREDEF_TYPE_CHAR_S_ID:
5581 // FIXME: Check that the signedness of CharTy is correct!
5582 T = Context.CharTy;
5583 break;
5584
5585 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5586 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5587 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5588 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5589 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5590 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5591 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5592 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5593 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5594 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5595 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5596 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5597 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5598 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5599 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5600 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5601 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5602 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5603 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5604 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5605 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5606 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5607 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5608 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5609 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5610 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5611 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5612 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005613 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5614 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5615 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5616 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5617 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5618 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005619 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005620 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005621 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5622
5623 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5624 T = Context.getAutoRRefDeductType();
5625 break;
5626
5627 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5628 T = Context.ARCUnbridgedCastTy;
5629 break;
5630
5631 case PREDEF_TYPE_VA_LIST_TAG:
5632 T = Context.getVaListTagType();
5633 break;
5634
5635 case PREDEF_TYPE_BUILTIN_FN:
5636 T = Context.BuiltinFnTy;
5637 break;
5638 }
5639
5640 assert(!T.isNull() && "Unknown predefined type");
5641 return T.withFastQualifiers(FastQuals);
5642 }
5643
5644 Index -= NUM_PREDEF_TYPE_IDS;
5645 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5646 if (TypesLoaded[Index].isNull()) {
5647 TypesLoaded[Index] = readTypeRecord(Index);
5648 if (TypesLoaded[Index].isNull())
5649 return QualType();
5650
5651 TypesLoaded[Index]->setFromAST();
5652 if (DeserializationListener)
5653 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5654 TypesLoaded[Index]);
5655 }
5656
5657 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5658}
5659
5660QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5661 return GetType(getGlobalTypeID(F, LocalID));
5662}
5663
5664serialization::TypeID
5665ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5666 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5667 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5668
5669 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5670 return LocalID;
5671
5672 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5673 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5674 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5675
5676 unsigned GlobalIndex = LocalIndex + I->second;
5677 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5678}
5679
5680TemplateArgumentLocInfo
5681ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5682 TemplateArgument::ArgKind Kind,
5683 const RecordData &Record,
5684 unsigned &Index) {
5685 switch (Kind) {
5686 case TemplateArgument::Expression:
5687 return ReadExpr(F);
5688 case TemplateArgument::Type:
5689 return GetTypeSourceInfo(F, Record, Index);
5690 case TemplateArgument::Template: {
5691 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5692 Index);
5693 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5694 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5695 SourceLocation());
5696 }
5697 case TemplateArgument::TemplateExpansion: {
5698 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5699 Index);
5700 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5701 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5702 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5703 EllipsisLoc);
5704 }
5705 case TemplateArgument::Null:
5706 case TemplateArgument::Integral:
5707 case TemplateArgument::Declaration:
5708 case TemplateArgument::NullPtr:
5709 case TemplateArgument::Pack:
5710 // FIXME: Is this right?
5711 return TemplateArgumentLocInfo();
5712 }
5713 llvm_unreachable("unexpected template argument loc");
5714}
5715
5716TemplateArgumentLoc
5717ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5718 const RecordData &Record, unsigned &Index) {
5719 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5720
5721 if (Arg.getKind() == TemplateArgument::Expression) {
5722 if (Record[Index++]) // bool InfoHasSameExpr.
5723 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5724 }
5725 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5726 Record, Index));
5727}
5728
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005729const ASTTemplateArgumentListInfo*
5730ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5731 const RecordData &Record,
5732 unsigned &Index) {
5733 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5734 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5735 unsigned NumArgsAsWritten = Record[Index++];
5736 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5737 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5738 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5739 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5740}
5741
Guy Benyei11169dd2012-12-18 14:30:41 +00005742Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5743 return GetDecl(ID);
5744}
5745
5746uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5747 unsigned &Idx){
5748 if (Idx >= Record.size())
5749 return 0;
5750
5751 unsigned LocalID = Record[Idx++];
5752 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5753}
5754
5755CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5756 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005757 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 SavedStreamPosition SavedPosition(Cursor);
5759 Cursor.JumpToBit(Loc.Offset);
5760 ReadingKindTracker ReadingKind(Read_Decl, *this);
5761 RecordData Record;
5762 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005763 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5765 Error("Malformed AST file: missing C++ base specifiers");
5766 return 0;
5767 }
5768
5769 unsigned Idx = 0;
5770 unsigned NumBases = Record[Idx++];
5771 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5772 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5773 for (unsigned I = 0; I != NumBases; ++I)
5774 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5775 return Bases;
5776}
5777
5778serialization::DeclID
5779ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5780 if (LocalID < NUM_PREDEF_DECL_IDS)
5781 return LocalID;
5782
5783 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5784 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5785 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5786
5787 return LocalID + I->second;
5788}
5789
5790bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5791 ModuleFile &M) const {
5792 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5793 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5794 return &M == I->second;
5795}
5796
Douglas Gregor9f782892013-01-21 15:25:38 +00005797ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005798 if (!D->isFromASTFile())
5799 return 0;
5800 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5801 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5802 return I->second;
5803}
5804
5805SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5806 if (ID < NUM_PREDEF_DECL_IDS)
5807 return SourceLocation();
5808
5809 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5810
5811 if (Index > DeclsLoaded.size()) {
5812 Error("declaration ID out-of-range for AST file");
5813 return SourceLocation();
5814 }
5815
5816 if (Decl *D = DeclsLoaded[Index])
5817 return D->getLocation();
5818
5819 unsigned RawLocation = 0;
5820 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5821 return ReadSourceLocation(*Rec.F, RawLocation);
5822}
5823
5824Decl *ASTReader::GetDecl(DeclID ID) {
5825 if (ID < NUM_PREDEF_DECL_IDS) {
5826 switch ((PredefinedDeclIDs)ID) {
5827 case PREDEF_DECL_NULL_ID:
5828 return 0;
5829
5830 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5831 return Context.getTranslationUnitDecl();
5832
5833 case PREDEF_DECL_OBJC_ID_ID:
5834 return Context.getObjCIdDecl();
5835
5836 case PREDEF_DECL_OBJC_SEL_ID:
5837 return Context.getObjCSelDecl();
5838
5839 case PREDEF_DECL_OBJC_CLASS_ID:
5840 return Context.getObjCClassDecl();
5841
5842 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5843 return Context.getObjCProtocolDecl();
5844
5845 case PREDEF_DECL_INT_128_ID:
5846 return Context.getInt128Decl();
5847
5848 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5849 return Context.getUInt128Decl();
5850
5851 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5852 return Context.getObjCInstanceTypeDecl();
5853
5854 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5855 return Context.getBuiltinVaListDecl();
5856 }
5857 }
5858
5859 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5860
5861 if (Index >= DeclsLoaded.size()) {
5862 assert(0 && "declaration ID out-of-range for AST file");
5863 Error("declaration ID out-of-range for AST file");
5864 return 0;
5865 }
5866
5867 if (!DeclsLoaded[Index]) {
5868 ReadDeclRecord(ID);
5869 if (DeserializationListener)
5870 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5871 }
5872
5873 return DeclsLoaded[Index];
5874}
5875
5876DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5877 DeclID GlobalID) {
5878 if (GlobalID < NUM_PREDEF_DECL_IDS)
5879 return GlobalID;
5880
5881 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5882 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5883 ModuleFile *Owner = I->second;
5884
5885 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5886 = M.GlobalToLocalDeclIDs.find(Owner);
5887 if (Pos == M.GlobalToLocalDeclIDs.end())
5888 return 0;
5889
5890 return GlobalID - Owner->BaseDeclID + Pos->second;
5891}
5892
5893serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5894 const RecordData &Record,
5895 unsigned &Idx) {
5896 if (Idx >= Record.size()) {
5897 Error("Corrupted AST file");
5898 return 0;
5899 }
5900
5901 return getGlobalDeclID(F, Record[Idx++]);
5902}
5903
5904/// \brief Resolve the offset of a statement into a statement.
5905///
5906/// This operation will read a new statement from the external
5907/// source each time it is called, and is meant to be used via a
5908/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5909Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5910 // Switch case IDs are per Decl.
5911 ClearSwitchCaseIDs();
5912
5913 // Offset here is a global offset across the entire chain.
5914 RecordLocation Loc = getLocalBitOffset(Offset);
5915 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5916 return ReadStmtFromStream(*Loc.F);
5917}
5918
5919namespace {
5920 class FindExternalLexicalDeclsVisitor {
5921 ASTReader &Reader;
5922 const DeclContext *DC;
5923 bool (*isKindWeWant)(Decl::Kind);
5924
5925 SmallVectorImpl<Decl*> &Decls;
5926 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5927
5928 public:
5929 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5930 bool (*isKindWeWant)(Decl::Kind),
5931 SmallVectorImpl<Decl*> &Decls)
5932 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5933 {
5934 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5935 PredefsVisited[I] = false;
5936 }
5937
5938 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5939 if (Preorder)
5940 return false;
5941
5942 FindExternalLexicalDeclsVisitor *This
5943 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5944
5945 ModuleFile::DeclContextInfosMap::iterator Info
5946 = M.DeclContextInfos.find(This->DC);
5947 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5948 return false;
5949
5950 // Load all of the declaration IDs
5951 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5952 *IDE = ID + Info->second.NumLexicalDecls;
5953 ID != IDE; ++ID) {
5954 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5955 continue;
5956
5957 // Don't add predefined declarations to the lexical context more
5958 // than once.
5959 if (ID->second < NUM_PREDEF_DECL_IDS) {
5960 if (This->PredefsVisited[ID->second])
5961 continue;
5962
5963 This->PredefsVisited[ID->second] = true;
5964 }
5965
5966 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5967 if (!This->DC->isDeclInLexicalTraversal(D))
5968 This->Decls.push_back(D);
5969 }
5970 }
5971
5972 return false;
5973 }
5974 };
5975}
5976
5977ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5978 bool (*isKindWeWant)(Decl::Kind),
5979 SmallVectorImpl<Decl*> &Decls) {
5980 // There might be lexical decls in multiple modules, for the TU at
5981 // least. Walk all of the modules in the order they were loaded.
5982 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5983 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5984 ++NumLexicalDeclContextsRead;
5985 return ELR_Success;
5986}
5987
5988namespace {
5989
5990class DeclIDComp {
5991 ASTReader &Reader;
5992 ModuleFile &Mod;
5993
5994public:
5995 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5996
5997 bool operator()(LocalDeclID L, LocalDeclID R) const {
5998 SourceLocation LHS = getLocation(L);
5999 SourceLocation RHS = getLocation(R);
6000 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6001 }
6002
6003 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6004 SourceLocation RHS = getLocation(R);
6005 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6006 }
6007
6008 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6009 SourceLocation LHS = getLocation(L);
6010 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6011 }
6012
6013 SourceLocation getLocation(LocalDeclID ID) const {
6014 return Reader.getSourceManager().getFileLoc(
6015 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6016 }
6017};
6018
6019}
6020
6021void ASTReader::FindFileRegionDecls(FileID File,
6022 unsigned Offset, unsigned Length,
6023 SmallVectorImpl<Decl *> &Decls) {
6024 SourceManager &SM = getSourceManager();
6025
6026 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6027 if (I == FileDeclIDs.end())
6028 return;
6029
6030 FileDeclsInfo &DInfo = I->second;
6031 if (DInfo.Decls.empty())
6032 return;
6033
6034 SourceLocation
6035 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6036 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6037
6038 DeclIDComp DIDComp(*this, *DInfo.Mod);
6039 ArrayRef<serialization::LocalDeclID>::iterator
6040 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6041 BeginLoc, DIDComp);
6042 if (BeginIt != DInfo.Decls.begin())
6043 --BeginIt;
6044
6045 // If we are pointing at a top-level decl inside an objc container, we need
6046 // to backtrack until we find it otherwise we will fail to report that the
6047 // region overlaps with an objc container.
6048 while (BeginIt != DInfo.Decls.begin() &&
6049 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6050 ->isTopLevelDeclInObjCContainer())
6051 --BeginIt;
6052
6053 ArrayRef<serialization::LocalDeclID>::iterator
6054 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6055 EndLoc, DIDComp);
6056 if (EndIt != DInfo.Decls.end())
6057 ++EndIt;
6058
6059 for (ArrayRef<serialization::LocalDeclID>::iterator
6060 DIt = BeginIt; DIt != EndIt; ++DIt)
6061 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6062}
6063
6064namespace {
6065 /// \brief ModuleFile visitor used to perform name lookup into a
6066 /// declaration context.
6067 class DeclContextNameLookupVisitor {
6068 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006069 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 DeclarationName Name;
6071 SmallVectorImpl<NamedDecl *> &Decls;
6072
6073 public:
6074 DeclContextNameLookupVisitor(ASTReader &Reader,
6075 SmallVectorImpl<const DeclContext *> &Contexts,
6076 DeclarationName Name,
6077 SmallVectorImpl<NamedDecl *> &Decls)
6078 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6079
6080 static bool visit(ModuleFile &M, void *UserData) {
6081 DeclContextNameLookupVisitor *This
6082 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6083
6084 // Check whether we have any visible declaration information for
6085 // this context in this module.
6086 ModuleFile::DeclContextInfosMap::iterator Info;
6087 bool FoundInfo = false;
6088 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6089 Info = M.DeclContextInfos.find(This->Contexts[I]);
6090 if (Info != M.DeclContextInfos.end() &&
6091 Info->second.NameLookupTableData) {
6092 FoundInfo = true;
6093 break;
6094 }
6095 }
6096
6097 if (!FoundInfo)
6098 return false;
6099
6100 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006101 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 Info->second.NameLookupTableData;
6103 ASTDeclContextNameLookupTable::iterator Pos
6104 = LookupTable->find(This->Name);
6105 if (Pos == LookupTable->end())
6106 return false;
6107
6108 bool FoundAnything = false;
6109 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6110 for (; Data.first != Data.second; ++Data.first) {
6111 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6112 if (!ND)
6113 continue;
6114
6115 if (ND->getDeclName() != This->Name) {
6116 // A name might be null because the decl's redeclarable part is
6117 // currently read before reading its name. The lookup is triggered by
6118 // building that decl (likely indirectly), and so it is later in the
6119 // sense of "already existing" and can be ignored here.
6120 continue;
6121 }
6122
6123 // Record this declaration.
6124 FoundAnything = true;
6125 This->Decls.push_back(ND);
6126 }
6127
6128 return FoundAnything;
6129 }
6130 };
6131}
6132
Douglas Gregor9f782892013-01-21 15:25:38 +00006133/// \brief Retrieve the "definitive" module file for the definition of the
6134/// given declaration context, if there is one.
6135///
6136/// The "definitive" module file is the only place where we need to look to
6137/// find information about the declarations within the given declaration
6138/// context. For example, C++ and Objective-C classes, C structs/unions, and
6139/// Objective-C protocols, categories, and extensions are all defined in a
6140/// single place in the source code, so they have definitive module files
6141/// associated with them. C++ namespaces, on the other hand, can have
6142/// definitions in multiple different module files.
6143///
6144/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6145/// NDEBUG checking.
6146static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6147 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006148 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6149 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006150
6151 return 0;
6152}
6153
Richard Smith9ce12e32013-02-07 03:30:24 +00006154bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006155ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6156 DeclarationName Name) {
6157 assert(DC->hasExternalVisibleStorage() &&
6158 "DeclContext has no visible decls in storage");
6159 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006160 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006161
6162 SmallVector<NamedDecl *, 64> Decls;
6163
6164 // Compute the declaration contexts we need to look into. Multiple such
6165 // declaration contexts occur when two declaration contexts from disjoint
6166 // modules get merged, e.g., when two namespaces with the same name are
6167 // independently defined in separate modules.
6168 SmallVector<const DeclContext *, 2> Contexts;
6169 Contexts.push_back(DC);
6170
6171 if (DC->isNamespace()) {
6172 MergedDeclsMap::iterator Merged
6173 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6174 if (Merged != MergedDecls.end()) {
6175 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6176 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6177 }
6178 }
6179
6180 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006181
6182 // If we can definitively determine which module file to look into,
6183 // only look there. Otherwise, look in all module files.
6184 ModuleFile *Definitive;
6185 if (Contexts.size() == 1 &&
6186 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6187 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6188 } else {
6189 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6190 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 ++NumVisibleDeclContextsRead;
6192 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006193 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006194}
6195
6196namespace {
6197 /// \brief ModuleFile visitor used to retrieve all visible names in a
6198 /// declaration context.
6199 class DeclContextAllNamesVisitor {
6200 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006201 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006202 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006203 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006204
6205 public:
6206 DeclContextAllNamesVisitor(ASTReader &Reader,
6207 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006208 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006209 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006210
6211 static bool visit(ModuleFile &M, void *UserData) {
6212 DeclContextAllNamesVisitor *This
6213 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6214
6215 // Check whether we have any visible declaration information for
6216 // this context in this module.
6217 ModuleFile::DeclContextInfosMap::iterator Info;
6218 bool FoundInfo = false;
6219 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6220 Info = M.DeclContextInfos.find(This->Contexts[I]);
6221 if (Info != M.DeclContextInfos.end() &&
6222 Info->second.NameLookupTableData) {
6223 FoundInfo = true;
6224 break;
6225 }
6226 }
6227
6228 if (!FoundInfo)
6229 return false;
6230
Richard Smith52e3fba2014-03-11 07:17:35 +00006231 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 Info->second.NameLookupTableData;
6233 bool FoundAnything = false;
6234 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006235 I = LookupTable->data_begin(), E = LookupTable->data_end();
6236 I != E;
6237 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 ASTDeclContextNameLookupTrait::data_type Data = *I;
6239 for (; Data.first != Data.second; ++Data.first) {
6240 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6241 *Data.first);
6242 if (!ND)
6243 continue;
6244
6245 // Record this declaration.
6246 FoundAnything = true;
6247 This->Decls[ND->getDeclName()].push_back(ND);
6248 }
6249 }
6250
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006251 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 }
6253 };
6254}
6255
6256void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6257 if (!DC->hasExternalVisibleStorage())
6258 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006259 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006260
6261 // Compute the declaration contexts we need to look into. Multiple such
6262 // declaration contexts occur when two declaration contexts from disjoint
6263 // modules get merged, e.g., when two namespaces with the same name are
6264 // independently defined in separate modules.
6265 SmallVector<const DeclContext *, 2> Contexts;
6266 Contexts.push_back(DC);
6267
6268 if (DC->isNamespace()) {
6269 MergedDeclsMap::iterator Merged
6270 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6271 if (Merged != MergedDecls.end()) {
6272 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6273 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6274 }
6275 }
6276
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006277 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6278 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6280 ++NumVisibleDeclContextsRead;
6281
Craig Topper79be4cd2013-07-05 04:33:53 +00006282 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6284 }
6285 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6286}
6287
6288/// \brief Under non-PCH compilation the consumer receives the objc methods
6289/// before receiving the implementation, and codegen depends on this.
6290/// We simulate this by deserializing and passing to consumer the methods of the
6291/// implementation before passing the deserialized implementation decl.
6292static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6293 ASTConsumer *Consumer) {
6294 assert(ImplD && Consumer);
6295
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006296 for (auto *I : ImplD->methods())
6297 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006298
6299 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6300}
6301
6302void ASTReader::PassInterestingDeclsToConsumer() {
6303 assert(Consumer);
6304 while (!InterestingDecls.empty()) {
6305 Decl *D = InterestingDecls.front();
6306 InterestingDecls.pop_front();
6307
6308 PassInterestingDeclToConsumer(D);
6309 }
6310}
6311
6312void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6313 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6314 PassObjCImplDeclToConsumer(ImplD, Consumer);
6315 else
6316 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6317}
6318
6319void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6320 this->Consumer = Consumer;
6321
6322 if (!Consumer)
6323 return;
6324
Ben Langmuir332aafe2014-01-31 01:06:56 +00006325 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 // Force deserialization of this decl, which will cause it to be queued for
6327 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006328 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006330 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006331
6332 PassInterestingDeclsToConsumer();
6333}
6334
6335void ASTReader::PrintStats() {
6336 std::fprintf(stderr, "*** AST File Statistics:\n");
6337
6338 unsigned NumTypesLoaded
6339 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6340 QualType());
6341 unsigned NumDeclsLoaded
6342 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6343 (Decl *)0);
6344 unsigned NumIdentifiersLoaded
6345 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6346 IdentifiersLoaded.end(),
6347 (IdentifierInfo *)0);
6348 unsigned NumMacrosLoaded
6349 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6350 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006351 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006352 unsigned NumSelectorsLoaded
6353 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6354 SelectorsLoaded.end(),
6355 Selector());
6356
6357 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6358 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6359 NumSLocEntriesRead, TotalNumSLocEntries,
6360 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6361 if (!TypesLoaded.empty())
6362 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6363 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6364 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6365 if (!DeclsLoaded.empty())
6366 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6367 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6368 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6369 if (!IdentifiersLoaded.empty())
6370 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6371 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6372 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6373 if (!MacrosLoaded.empty())
6374 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6375 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6376 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6377 if (!SelectorsLoaded.empty())
6378 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6379 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6380 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6381 if (TotalNumStatements)
6382 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6383 NumStatementsRead, TotalNumStatements,
6384 ((float)NumStatementsRead/TotalNumStatements * 100));
6385 if (TotalNumMacros)
6386 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6387 NumMacrosRead, TotalNumMacros,
6388 ((float)NumMacrosRead/TotalNumMacros * 100));
6389 if (TotalLexicalDeclContexts)
6390 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6391 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6392 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6393 * 100));
6394 if (TotalVisibleDeclContexts)
6395 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6396 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6397 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6398 * 100));
6399 if (TotalNumMethodPoolEntries) {
6400 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6401 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6402 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6403 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006405 if (NumMethodPoolLookups) {
6406 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6407 NumMethodPoolHits, NumMethodPoolLookups,
6408 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6409 }
6410 if (NumMethodPoolTableLookups) {
6411 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6412 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6413 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6414 * 100.0));
6415 }
6416
Douglas Gregor00a50f72013-01-25 00:38:33 +00006417 if (NumIdentifierLookupHits) {
6418 std::fprintf(stderr,
6419 " %u / %u identifier table lookups succeeded (%f%%)\n",
6420 NumIdentifierLookupHits, NumIdentifierLookups,
6421 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6422 }
6423
Douglas Gregore060e572013-01-25 01:03:03 +00006424 if (GlobalIndex) {
6425 std::fprintf(stderr, "\n");
6426 GlobalIndex->printStats();
6427 }
6428
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 std::fprintf(stderr, "\n");
6430 dump();
6431 std::fprintf(stderr, "\n");
6432}
6433
6434template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6435static void
6436dumpModuleIDMap(StringRef Name,
6437 const ContinuousRangeMap<Key, ModuleFile *,
6438 InitialCapacity> &Map) {
6439 if (Map.begin() == Map.end())
6440 return;
6441
6442 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6443 llvm::errs() << Name << ":\n";
6444 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6445 I != IEnd; ++I) {
6446 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6447 << "\n";
6448 }
6449}
6450
6451void ASTReader::dump() {
6452 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6453 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6454 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6455 dumpModuleIDMap("Global type map", GlobalTypeMap);
6456 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6457 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6458 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6459 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6460 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6461 dumpModuleIDMap("Global preprocessed entity map",
6462 GlobalPreprocessedEntityMap);
6463
6464 llvm::errs() << "\n*** PCH/Modules Loaded:";
6465 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6466 MEnd = ModuleMgr.end();
6467 M != MEnd; ++M)
6468 (*M)->dump();
6469}
6470
6471/// Return the amount of memory used by memory buffers, breaking down
6472/// by heap-backed versus mmap'ed memory.
6473void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6474 for (ModuleConstIterator I = ModuleMgr.begin(),
6475 E = ModuleMgr.end(); I != E; ++I) {
6476 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6477 size_t bytes = buf->getBufferSize();
6478 switch (buf->getBufferKind()) {
6479 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6480 sizes.malloc_bytes += bytes;
6481 break;
6482 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6483 sizes.mmap_bytes += bytes;
6484 break;
6485 }
6486 }
6487 }
6488}
6489
6490void ASTReader::InitializeSema(Sema &S) {
6491 SemaObj = &S;
6492 S.addExternalSource(this);
6493
6494 // Makes sure any declarations that were deserialized "too early"
6495 // still get added to the identifier's declaration chains.
6496 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006497 pushExternalDeclIntoScope(PreloadedDecls[I],
6498 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 }
6500 PreloadedDecls.clear();
6501
Richard Smith3d8e97e2013-10-18 06:54:39 +00006502 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 if (!FPPragmaOptions.empty()) {
6504 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6505 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6506 }
6507
Richard Smith3d8e97e2013-10-18 06:54:39 +00006508 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006509 if (!OpenCLExtensions.empty()) {
6510 unsigned I = 0;
6511#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6512#include "clang/Basic/OpenCLExtensions.def"
6513
6514 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6515 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006516
6517 UpdateSema();
6518}
6519
6520void ASTReader::UpdateSema() {
6521 assert(SemaObj && "no Sema to update");
6522
6523 // Load the offsets of the declarations that Sema references.
6524 // They will be lazily deserialized when needed.
6525 if (!SemaDeclRefs.empty()) {
6526 assert(SemaDeclRefs.size() % 2 == 0);
6527 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6528 if (!SemaObj->StdNamespace)
6529 SemaObj->StdNamespace = SemaDeclRefs[I];
6530 if (!SemaObj->StdBadAlloc)
6531 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6532 }
6533 SemaDeclRefs.clear();
6534 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006535}
6536
6537IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6538 // Note that we are loading an identifier.
6539 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006540 StringRef Name(NameStart, NameEnd - NameStart);
6541
6542 // If there is a global index, look there first to determine which modules
6543 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006544 GlobalModuleIndex::HitSet Hits;
6545 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006546 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006547 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6548 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006549 }
6550 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006551 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006552 NumIdentifierLookups,
6553 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006554 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 IdentifierInfo *II = Visitor.getIdentifierInfo();
6556 markIdentifierUpToDate(II);
6557 return II;
6558}
6559
6560namespace clang {
6561 /// \brief An identifier-lookup iterator that enumerates all of the
6562 /// identifiers stored within a set of AST files.
6563 class ASTIdentifierIterator : public IdentifierIterator {
6564 /// \brief The AST reader whose identifiers are being enumerated.
6565 const ASTReader &Reader;
6566
6567 /// \brief The current index into the chain of AST files stored in
6568 /// the AST reader.
6569 unsigned Index;
6570
6571 /// \brief The current position within the identifier lookup table
6572 /// of the current AST file.
6573 ASTIdentifierLookupTable::key_iterator Current;
6574
6575 /// \brief The end position within the identifier lookup table of
6576 /// the current AST file.
6577 ASTIdentifierLookupTable::key_iterator End;
6578
6579 public:
6580 explicit ASTIdentifierIterator(const ASTReader &Reader);
6581
Craig Topper3e89dfe2014-03-13 02:13:41 +00006582 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006583 };
6584}
6585
6586ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6587 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6588 ASTIdentifierLookupTable *IdTable
6589 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6590 Current = IdTable->key_begin();
6591 End = IdTable->key_end();
6592}
6593
6594StringRef ASTIdentifierIterator::Next() {
6595 while (Current == End) {
6596 // If we have exhausted all of our AST files, we're done.
6597 if (Index == 0)
6598 return StringRef();
6599
6600 --Index;
6601 ASTIdentifierLookupTable *IdTable
6602 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6603 IdentifierLookupTable;
6604 Current = IdTable->key_begin();
6605 End = IdTable->key_end();
6606 }
6607
6608 // We have any identifiers remaining in the current AST file; return
6609 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006610 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006612 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006613}
6614
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006615IdentifierIterator *ASTReader::getIdentifiers() {
6616 if (!loadGlobalIndex())
6617 return GlobalIndex->createIdentifierIterator();
6618
Guy Benyei11169dd2012-12-18 14:30:41 +00006619 return new ASTIdentifierIterator(*this);
6620}
6621
6622namespace clang { namespace serialization {
6623 class ReadMethodPoolVisitor {
6624 ASTReader &Reader;
6625 Selector Sel;
6626 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006627 unsigned InstanceBits;
6628 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006629 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6630 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006631
6632 public:
6633 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6634 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006635 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6636 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006637
6638 static bool visit(ModuleFile &M, void *UserData) {
6639 ReadMethodPoolVisitor *This
6640 = static_cast<ReadMethodPoolVisitor *>(UserData);
6641
6642 if (!M.SelectorLookupTable)
6643 return false;
6644
6645 // If we've already searched this module file, skip it now.
6646 if (M.Generation <= This->PriorGeneration)
6647 return true;
6648
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006649 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 ASTSelectorLookupTable *PoolTable
6651 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6652 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6653 if (Pos == PoolTable->end())
6654 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006655
6656 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 ++This->Reader.NumSelectorsRead;
6658 // FIXME: Not quite happy with the statistics here. We probably should
6659 // disable this tracking when called via LoadSelector.
6660 // Also, should entries without methods count as misses?
6661 ++This->Reader.NumMethodPoolEntriesRead;
6662 ASTSelectorLookupTrait::data_type Data = *Pos;
6663 if (This->Reader.DeserializationListener)
6664 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6665 This->Sel);
6666
6667 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6668 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006669 This->InstanceBits = Data.InstanceBits;
6670 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 return true;
6672 }
6673
6674 /// \brief Retrieve the instance methods found by this visitor.
6675 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6676 return InstanceMethods;
6677 }
6678
6679 /// \brief Retrieve the instance methods found by this visitor.
6680 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6681 return FactoryMethods;
6682 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006683
6684 unsigned getInstanceBits() const { return InstanceBits; }
6685 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006686 };
6687} } // end namespace clang::serialization
6688
6689/// \brief Add the given set of methods to the method list.
6690static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6691 ObjCMethodList &List) {
6692 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6693 S.addMethodToGlobalList(&List, Methods[I]);
6694 }
6695}
6696
6697void ASTReader::ReadMethodPool(Selector Sel) {
6698 // Get the selector generation and update it to the current generation.
6699 unsigned &Generation = SelectorGeneration[Sel];
6700 unsigned PriorGeneration = Generation;
6701 Generation = CurrentGeneration;
6702
6703 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006704 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6706 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6707
6708 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006709 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006710 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006711
6712 ++NumMethodPoolHits;
6713
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 if (!getSema())
6715 return;
6716
6717 Sema &S = *getSema();
6718 Sema::GlobalMethodPool::iterator Pos
6719 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6720
6721 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6722 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006723 Pos->second.first.setBits(Visitor.getInstanceBits());
6724 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006725}
6726
6727void ASTReader::ReadKnownNamespaces(
6728 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6729 Namespaces.clear();
6730
6731 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6732 if (NamespaceDecl *Namespace
6733 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6734 Namespaces.push_back(Namespace);
6735 }
6736}
6737
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006738void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006739 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006740 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6741 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006742 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006743 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006744 Undefined.insert(std::make_pair(D, Loc));
6745 }
6746}
Nick Lewycky8334af82013-01-26 00:35:08 +00006747
Guy Benyei11169dd2012-12-18 14:30:41 +00006748void ASTReader::ReadTentativeDefinitions(
6749 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6750 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6751 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6752 if (Var)
6753 TentativeDefs.push_back(Var);
6754 }
6755 TentativeDefinitions.clear();
6756}
6757
6758void ASTReader::ReadUnusedFileScopedDecls(
6759 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6760 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6761 DeclaratorDecl *D
6762 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6763 if (D)
6764 Decls.push_back(D);
6765 }
6766 UnusedFileScopedDecls.clear();
6767}
6768
6769void ASTReader::ReadDelegatingConstructors(
6770 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6771 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6772 CXXConstructorDecl *D
6773 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6774 if (D)
6775 Decls.push_back(D);
6776 }
6777 DelegatingCtorDecls.clear();
6778}
6779
6780void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6781 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6782 TypedefNameDecl *D
6783 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6784 if (D)
6785 Decls.push_back(D);
6786 }
6787 ExtVectorDecls.clear();
6788}
6789
6790void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6791 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6792 CXXRecordDecl *D
6793 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6794 if (D)
6795 Decls.push_back(D);
6796 }
6797 DynamicClasses.clear();
6798}
6799
6800void
Richard Smith78165b52013-01-10 23:43:47 +00006801ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6802 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6803 NamedDecl *D
6804 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006805 if (D)
6806 Decls.push_back(D);
6807 }
Richard Smith78165b52013-01-10 23:43:47 +00006808 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006809}
6810
6811void ASTReader::ReadReferencedSelectors(
6812 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6813 if (ReferencedSelectorsData.empty())
6814 return;
6815
6816 // If there are @selector references added them to its pool. This is for
6817 // implementation of -Wselector.
6818 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6819 unsigned I = 0;
6820 while (I < DataSize) {
6821 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6822 SourceLocation SelLoc
6823 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6824 Sels.push_back(std::make_pair(Sel, SelLoc));
6825 }
6826 ReferencedSelectorsData.clear();
6827}
6828
6829void ASTReader::ReadWeakUndeclaredIdentifiers(
6830 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6831 if (WeakUndeclaredIdentifiers.empty())
6832 return;
6833
6834 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6835 IdentifierInfo *WeakId
6836 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6837 IdentifierInfo *AliasId
6838 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6839 SourceLocation Loc
6840 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6841 bool Used = WeakUndeclaredIdentifiers[I++];
6842 WeakInfo WI(AliasId, Loc);
6843 WI.setUsed(Used);
6844 WeakIDs.push_back(std::make_pair(WeakId, WI));
6845 }
6846 WeakUndeclaredIdentifiers.clear();
6847}
6848
6849void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6850 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6851 ExternalVTableUse VT;
6852 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6853 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6854 VT.DefinitionRequired = VTableUses[Idx++];
6855 VTables.push_back(VT);
6856 }
6857
6858 VTableUses.clear();
6859}
6860
6861void ASTReader::ReadPendingInstantiations(
6862 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6863 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6864 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6865 SourceLocation Loc
6866 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6867
6868 Pending.push_back(std::make_pair(D, Loc));
6869 }
6870 PendingInstantiations.clear();
6871}
6872
Richard Smithe40f2ba2013-08-07 21:41:30 +00006873void ASTReader::ReadLateParsedTemplates(
6874 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6875 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6876 /* In loop */) {
6877 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6878
6879 LateParsedTemplate *LT = new LateParsedTemplate;
6880 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6881
6882 ModuleFile *F = getOwningModuleFile(LT->D);
6883 assert(F && "No module");
6884
6885 unsigned TokN = LateParsedTemplates[Idx++];
6886 LT->Toks.reserve(TokN);
6887 for (unsigned T = 0; T < TokN; ++T)
6888 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6889
6890 LPTMap[FD] = LT;
6891 }
6892
6893 LateParsedTemplates.clear();
6894}
6895
Guy Benyei11169dd2012-12-18 14:30:41 +00006896void ASTReader::LoadSelector(Selector Sel) {
6897 // It would be complicated to avoid reading the methods anyway. So don't.
6898 ReadMethodPool(Sel);
6899}
6900
6901void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6902 assert(ID && "Non-zero identifier ID required");
6903 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6904 IdentifiersLoaded[ID - 1] = II;
6905 if (DeserializationListener)
6906 DeserializationListener->IdentifierRead(ID, II);
6907}
6908
6909/// \brief Set the globally-visible declarations associated with the given
6910/// identifier.
6911///
6912/// If the AST reader is currently in a state where the given declaration IDs
6913/// cannot safely be resolved, they are queued until it is safe to resolve
6914/// them.
6915///
6916/// \param II an IdentifierInfo that refers to one or more globally-visible
6917/// declarations.
6918///
6919/// \param DeclIDs the set of declaration IDs with the name @p II that are
6920/// visible at global scope.
6921///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006922/// \param Decls if non-null, this vector will be populated with the set of
6923/// deserialized declarations. These declarations will not be pushed into
6924/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006925void
6926ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6927 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006928 SmallVectorImpl<Decl *> *Decls) {
6929 if (NumCurrentElementsDeserializing && !Decls) {
6930 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 return;
6932 }
6933
6934 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6935 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6936 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006937 // If we're simply supposed to record the declarations, do so now.
6938 if (Decls) {
6939 Decls->push_back(D);
6940 continue;
6941 }
6942
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 // Introduce this declaration into the translation-unit scope
6944 // and add it to the declaration chain for this identifier, so
6945 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006946 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 } else {
6948 // Queue this declaration so that it will be added to the
6949 // translation unit scope and identifier's declaration chain
6950 // once a Sema object is known.
6951 PreloadedDecls.push_back(D);
6952 }
6953 }
6954}
6955
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006956IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006957 if (ID == 0)
6958 return 0;
6959
6960 if (IdentifiersLoaded.empty()) {
6961 Error("no identifier table in AST file");
6962 return 0;
6963 }
6964
6965 ID -= 1;
6966 if (!IdentifiersLoaded[ID]) {
6967 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6968 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6969 ModuleFile *M = I->second;
6970 unsigned Index = ID - M->BaseIdentifierID;
6971 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6972
6973 // All of the strings in the AST file are preceded by a 16-bit length.
6974 // Extract that 16-bit length to avoid having to execute strlen().
6975 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6976 // unsigned integers. This is important to avoid integer overflow when
6977 // we cast them to 'unsigned'.
6978 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6979 unsigned StrLen = (((unsigned) StrLenPtr[0])
6980 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006981 IdentifiersLoaded[ID]
6982 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 if (DeserializationListener)
6984 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6985 }
6986
6987 return IdentifiersLoaded[ID];
6988}
6989
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006990IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6991 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006992}
6993
6994IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6995 if (LocalID < NUM_PREDEF_IDENT_IDS)
6996 return LocalID;
6997
6998 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6999 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7000 assert(I != M.IdentifierRemap.end()
7001 && "Invalid index into identifier index remap");
7002
7003 return LocalID + I->second;
7004}
7005
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007006MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 if (ID == 0)
7008 return 0;
7009
7010 if (MacrosLoaded.empty()) {
7011 Error("no macro table in AST file");
7012 return 0;
7013 }
7014
7015 ID -= NUM_PREDEF_MACRO_IDS;
7016 if (!MacrosLoaded[ID]) {
7017 GlobalMacroMapType::iterator I
7018 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7019 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7020 ModuleFile *M = I->second;
7021 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007022 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7023
7024 if (DeserializationListener)
7025 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7026 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 }
7028
7029 return MacrosLoaded[ID];
7030}
7031
7032MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7033 if (LocalID < NUM_PREDEF_MACRO_IDS)
7034 return LocalID;
7035
7036 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7037 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7038 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7039
7040 return LocalID + I->second;
7041}
7042
7043serialization::SubmoduleID
7044ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7045 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7046 return LocalID;
7047
7048 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7049 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7050 assert(I != M.SubmoduleRemap.end()
7051 && "Invalid index into submodule index remap");
7052
7053 return LocalID + I->second;
7054}
7055
7056Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7057 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7058 assert(GlobalID == 0 && "Unhandled global submodule ID");
7059 return 0;
7060 }
7061
7062 if (GlobalID > SubmodulesLoaded.size()) {
7063 Error("submodule ID out of range in AST file");
7064 return 0;
7065 }
7066
7067 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7068}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007069
7070Module *ASTReader::getModule(unsigned ID) {
7071 return getSubmodule(ID);
7072}
7073
Guy Benyei11169dd2012-12-18 14:30:41 +00007074Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7075 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7076}
7077
7078Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7079 if (ID == 0)
7080 return Selector();
7081
7082 if (ID > SelectorsLoaded.size()) {
7083 Error("selector ID out of range in AST file");
7084 return Selector();
7085 }
7086
7087 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7088 // Load this selector from the selector table.
7089 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7090 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7091 ModuleFile &M = *I->second;
7092 ASTSelectorLookupTrait Trait(*this, M);
7093 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7094 SelectorsLoaded[ID - 1] =
7095 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7096 if (DeserializationListener)
7097 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7098 }
7099
7100 return SelectorsLoaded[ID - 1];
7101}
7102
7103Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7104 return DecodeSelector(ID);
7105}
7106
7107uint32_t ASTReader::GetNumExternalSelectors() {
7108 // ID 0 (the null selector) is considered an external selector.
7109 return getTotalNumSelectors() + 1;
7110}
7111
7112serialization::SelectorID
7113ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7114 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7115 return LocalID;
7116
7117 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7118 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7119 assert(I != M.SelectorRemap.end()
7120 && "Invalid index into selector index remap");
7121
7122 return LocalID + I->second;
7123}
7124
7125DeclarationName
7126ASTReader::ReadDeclarationName(ModuleFile &F,
7127 const RecordData &Record, unsigned &Idx) {
7128 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7129 switch (Kind) {
7130 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007131 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007132
7133 case DeclarationName::ObjCZeroArgSelector:
7134 case DeclarationName::ObjCOneArgSelector:
7135 case DeclarationName::ObjCMultiArgSelector:
7136 return DeclarationName(ReadSelector(F, Record, Idx));
7137
7138 case DeclarationName::CXXConstructorName:
7139 return Context.DeclarationNames.getCXXConstructorName(
7140 Context.getCanonicalType(readType(F, Record, Idx)));
7141
7142 case DeclarationName::CXXDestructorName:
7143 return Context.DeclarationNames.getCXXDestructorName(
7144 Context.getCanonicalType(readType(F, Record, Idx)));
7145
7146 case DeclarationName::CXXConversionFunctionName:
7147 return Context.DeclarationNames.getCXXConversionFunctionName(
7148 Context.getCanonicalType(readType(F, Record, Idx)));
7149
7150 case DeclarationName::CXXOperatorName:
7151 return Context.DeclarationNames.getCXXOperatorName(
7152 (OverloadedOperatorKind)Record[Idx++]);
7153
7154 case DeclarationName::CXXLiteralOperatorName:
7155 return Context.DeclarationNames.getCXXLiteralOperatorName(
7156 GetIdentifierInfo(F, Record, Idx));
7157
7158 case DeclarationName::CXXUsingDirective:
7159 return DeclarationName::getUsingDirectiveName();
7160 }
7161
7162 llvm_unreachable("Invalid NameKind!");
7163}
7164
7165void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7166 DeclarationNameLoc &DNLoc,
7167 DeclarationName Name,
7168 const RecordData &Record, unsigned &Idx) {
7169 switch (Name.getNameKind()) {
7170 case DeclarationName::CXXConstructorName:
7171 case DeclarationName::CXXDestructorName:
7172 case DeclarationName::CXXConversionFunctionName:
7173 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7174 break;
7175
7176 case DeclarationName::CXXOperatorName:
7177 DNLoc.CXXOperatorName.BeginOpNameLoc
7178 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7179 DNLoc.CXXOperatorName.EndOpNameLoc
7180 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7181 break;
7182
7183 case DeclarationName::CXXLiteralOperatorName:
7184 DNLoc.CXXLiteralOperatorName.OpNameLoc
7185 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7186 break;
7187
7188 case DeclarationName::Identifier:
7189 case DeclarationName::ObjCZeroArgSelector:
7190 case DeclarationName::ObjCOneArgSelector:
7191 case DeclarationName::ObjCMultiArgSelector:
7192 case DeclarationName::CXXUsingDirective:
7193 break;
7194 }
7195}
7196
7197void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7198 DeclarationNameInfo &NameInfo,
7199 const RecordData &Record, unsigned &Idx) {
7200 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7201 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7202 DeclarationNameLoc DNLoc;
7203 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7204 NameInfo.setInfo(DNLoc);
7205}
7206
7207void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7208 const RecordData &Record, unsigned &Idx) {
7209 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7210 unsigned NumTPLists = Record[Idx++];
7211 Info.NumTemplParamLists = NumTPLists;
7212 if (NumTPLists) {
7213 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7214 for (unsigned i=0; i != NumTPLists; ++i)
7215 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7216 }
7217}
7218
7219TemplateName
7220ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7221 unsigned &Idx) {
7222 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7223 switch (Kind) {
7224 case TemplateName::Template:
7225 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7226
7227 case TemplateName::OverloadedTemplate: {
7228 unsigned size = Record[Idx++];
7229 UnresolvedSet<8> Decls;
7230 while (size--)
7231 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7232
7233 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7234 }
7235
7236 case TemplateName::QualifiedTemplate: {
7237 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7238 bool hasTemplKeyword = Record[Idx++];
7239 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7240 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7241 }
7242
7243 case TemplateName::DependentTemplate: {
7244 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7245 if (Record[Idx++]) // isIdentifier
7246 return Context.getDependentTemplateName(NNS,
7247 GetIdentifierInfo(F, Record,
7248 Idx));
7249 return Context.getDependentTemplateName(NNS,
7250 (OverloadedOperatorKind)Record[Idx++]);
7251 }
7252
7253 case TemplateName::SubstTemplateTemplateParm: {
7254 TemplateTemplateParmDecl *param
7255 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7256 if (!param) return TemplateName();
7257 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7258 return Context.getSubstTemplateTemplateParm(param, replacement);
7259 }
7260
7261 case TemplateName::SubstTemplateTemplateParmPack: {
7262 TemplateTemplateParmDecl *Param
7263 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7264 if (!Param)
7265 return TemplateName();
7266
7267 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7268 if (ArgPack.getKind() != TemplateArgument::Pack)
7269 return TemplateName();
7270
7271 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7272 }
7273 }
7274
7275 llvm_unreachable("Unhandled template name kind!");
7276}
7277
7278TemplateArgument
7279ASTReader::ReadTemplateArgument(ModuleFile &F,
7280 const RecordData &Record, unsigned &Idx) {
7281 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7282 switch (Kind) {
7283 case TemplateArgument::Null:
7284 return TemplateArgument();
7285 case TemplateArgument::Type:
7286 return TemplateArgument(readType(F, Record, Idx));
7287 case TemplateArgument::Declaration: {
7288 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7289 bool ForReferenceParam = Record[Idx++];
7290 return TemplateArgument(D, ForReferenceParam);
7291 }
7292 case TemplateArgument::NullPtr:
7293 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7294 case TemplateArgument::Integral: {
7295 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7296 QualType T = readType(F, Record, Idx);
7297 return TemplateArgument(Context, Value, T);
7298 }
7299 case TemplateArgument::Template:
7300 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7301 case TemplateArgument::TemplateExpansion: {
7302 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007303 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 if (unsigned NumExpansions = Record[Idx++])
7305 NumTemplateExpansions = NumExpansions - 1;
7306 return TemplateArgument(Name, NumTemplateExpansions);
7307 }
7308 case TemplateArgument::Expression:
7309 return TemplateArgument(ReadExpr(F));
7310 case TemplateArgument::Pack: {
7311 unsigned NumArgs = Record[Idx++];
7312 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7313 for (unsigned I = 0; I != NumArgs; ++I)
7314 Args[I] = ReadTemplateArgument(F, Record, Idx);
7315 return TemplateArgument(Args, NumArgs);
7316 }
7317 }
7318
7319 llvm_unreachable("Unhandled template argument kind!");
7320}
7321
7322TemplateParameterList *
7323ASTReader::ReadTemplateParameterList(ModuleFile &F,
7324 const RecordData &Record, unsigned &Idx) {
7325 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7326 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7327 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7328
7329 unsigned NumParams = Record[Idx++];
7330 SmallVector<NamedDecl *, 16> Params;
7331 Params.reserve(NumParams);
7332 while (NumParams--)
7333 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7334
7335 TemplateParameterList* TemplateParams =
7336 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7337 Params.data(), Params.size(), RAngleLoc);
7338 return TemplateParams;
7339}
7340
7341void
7342ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007343ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007344 ModuleFile &F, const RecordData &Record,
7345 unsigned &Idx) {
7346 unsigned NumTemplateArgs = Record[Idx++];
7347 TemplArgs.reserve(NumTemplateArgs);
7348 while (NumTemplateArgs--)
7349 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7350}
7351
7352/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007353void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 const RecordData &Record, unsigned &Idx) {
7355 unsigned NumDecls = Record[Idx++];
7356 Set.reserve(Context, NumDecls);
7357 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007358 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007360 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007361 }
7362}
7363
7364CXXBaseSpecifier
7365ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7366 const RecordData &Record, unsigned &Idx) {
7367 bool isVirtual = static_cast<bool>(Record[Idx++]);
7368 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7369 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7370 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7371 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7372 SourceRange Range = ReadSourceRange(F, Record, Idx);
7373 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7374 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7375 EllipsisLoc);
7376 Result.setInheritConstructors(inheritConstructors);
7377 return Result;
7378}
7379
7380std::pair<CXXCtorInitializer **, unsigned>
7381ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7382 unsigned &Idx) {
7383 CXXCtorInitializer **CtorInitializers = 0;
7384 unsigned NumInitializers = Record[Idx++];
7385 if (NumInitializers) {
7386 CtorInitializers
7387 = new (Context) CXXCtorInitializer*[NumInitializers];
7388 for (unsigned i=0; i != NumInitializers; ++i) {
7389 TypeSourceInfo *TInfo = 0;
7390 bool IsBaseVirtual = false;
7391 FieldDecl *Member = 0;
7392 IndirectFieldDecl *IndirectMember = 0;
7393
7394 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7395 switch (Type) {
7396 case CTOR_INITIALIZER_BASE:
7397 TInfo = GetTypeSourceInfo(F, Record, Idx);
7398 IsBaseVirtual = Record[Idx++];
7399 break;
7400
7401 case CTOR_INITIALIZER_DELEGATING:
7402 TInfo = GetTypeSourceInfo(F, Record, Idx);
7403 break;
7404
7405 case CTOR_INITIALIZER_MEMBER:
7406 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7407 break;
7408
7409 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7410 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7411 break;
7412 }
7413
7414 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7415 Expr *Init = ReadExpr(F);
7416 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7417 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7418 bool IsWritten = Record[Idx++];
7419 unsigned SourceOrderOrNumArrayIndices;
7420 SmallVector<VarDecl *, 8> Indices;
7421 if (IsWritten) {
7422 SourceOrderOrNumArrayIndices = Record[Idx++];
7423 } else {
7424 SourceOrderOrNumArrayIndices = Record[Idx++];
7425 Indices.reserve(SourceOrderOrNumArrayIndices);
7426 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7427 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7428 }
7429
7430 CXXCtorInitializer *BOMInit;
7431 if (Type == CTOR_INITIALIZER_BASE) {
7432 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7433 LParenLoc, Init, RParenLoc,
7434 MemberOrEllipsisLoc);
7435 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7436 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7437 Init, RParenLoc);
7438 } else if (IsWritten) {
7439 if (Member)
7440 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7441 LParenLoc, Init, RParenLoc);
7442 else
7443 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7444 MemberOrEllipsisLoc, LParenLoc,
7445 Init, RParenLoc);
7446 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007447 if (IndirectMember) {
7448 assert(Indices.empty() && "Indirect field improperly initialized");
7449 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7450 MemberOrEllipsisLoc, LParenLoc,
7451 Init, RParenLoc);
7452 } else {
7453 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7454 LParenLoc, Init, RParenLoc,
7455 Indices.data(), Indices.size());
7456 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 }
7458
7459 if (IsWritten)
7460 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7461 CtorInitializers[i] = BOMInit;
7462 }
7463 }
7464
7465 return std::make_pair(CtorInitializers, NumInitializers);
7466}
7467
7468NestedNameSpecifier *
7469ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7470 const RecordData &Record, unsigned &Idx) {
7471 unsigned N = Record[Idx++];
7472 NestedNameSpecifier *NNS = 0, *Prev = 0;
7473 for (unsigned I = 0; I != N; ++I) {
7474 NestedNameSpecifier::SpecifierKind Kind
7475 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7476 switch (Kind) {
7477 case NestedNameSpecifier::Identifier: {
7478 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7479 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7480 break;
7481 }
7482
7483 case NestedNameSpecifier::Namespace: {
7484 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7485 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7486 break;
7487 }
7488
7489 case NestedNameSpecifier::NamespaceAlias: {
7490 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7491 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7492 break;
7493 }
7494
7495 case NestedNameSpecifier::TypeSpec:
7496 case NestedNameSpecifier::TypeSpecWithTemplate: {
7497 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7498 if (!T)
7499 return 0;
7500
7501 bool Template = Record[Idx++];
7502 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7503 break;
7504 }
7505
7506 case NestedNameSpecifier::Global: {
7507 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7508 // No associated value, and there can't be a prefix.
7509 break;
7510 }
7511 }
7512 Prev = NNS;
7513 }
7514 return NNS;
7515}
7516
7517NestedNameSpecifierLoc
7518ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7519 unsigned &Idx) {
7520 unsigned N = Record[Idx++];
7521 NestedNameSpecifierLocBuilder Builder;
7522 for (unsigned I = 0; I != N; ++I) {
7523 NestedNameSpecifier::SpecifierKind Kind
7524 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7525 switch (Kind) {
7526 case NestedNameSpecifier::Identifier: {
7527 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7528 SourceRange Range = ReadSourceRange(F, Record, Idx);
7529 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7530 break;
7531 }
7532
7533 case NestedNameSpecifier::Namespace: {
7534 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7535 SourceRange Range = ReadSourceRange(F, Record, Idx);
7536 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7537 break;
7538 }
7539
7540 case NestedNameSpecifier::NamespaceAlias: {
7541 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7542 SourceRange Range = ReadSourceRange(F, Record, Idx);
7543 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7544 break;
7545 }
7546
7547 case NestedNameSpecifier::TypeSpec:
7548 case NestedNameSpecifier::TypeSpecWithTemplate: {
7549 bool Template = Record[Idx++];
7550 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7551 if (!T)
7552 return NestedNameSpecifierLoc();
7553 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7554
7555 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7556 Builder.Extend(Context,
7557 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7558 T->getTypeLoc(), ColonColonLoc);
7559 break;
7560 }
7561
7562 case NestedNameSpecifier::Global: {
7563 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7564 Builder.MakeGlobal(Context, ColonColonLoc);
7565 break;
7566 }
7567 }
7568 }
7569
7570 return Builder.getWithLocInContext(Context);
7571}
7572
7573SourceRange
7574ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7575 unsigned &Idx) {
7576 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7577 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7578 return SourceRange(beg, end);
7579}
7580
7581/// \brief Read an integral value
7582llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7583 unsigned BitWidth = Record[Idx++];
7584 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7585 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7586 Idx += NumWords;
7587 return Result;
7588}
7589
7590/// \brief Read a signed integral value
7591llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7592 bool isUnsigned = Record[Idx++];
7593 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7594}
7595
7596/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007597llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7598 const llvm::fltSemantics &Sem,
7599 unsigned &Idx) {
7600 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007601}
7602
7603// \brief Read a string
7604std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7605 unsigned Len = Record[Idx++];
7606 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7607 Idx += Len;
7608 return Result;
7609}
7610
7611VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7612 unsigned &Idx) {
7613 unsigned Major = Record[Idx++];
7614 unsigned Minor = Record[Idx++];
7615 unsigned Subminor = Record[Idx++];
7616 if (Minor == 0)
7617 return VersionTuple(Major);
7618 if (Subminor == 0)
7619 return VersionTuple(Major, Minor - 1);
7620 return VersionTuple(Major, Minor - 1, Subminor - 1);
7621}
7622
7623CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7624 const RecordData &Record,
7625 unsigned &Idx) {
7626 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7627 return CXXTemporary::Create(Context, Decl);
7628}
7629
7630DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007631 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007632}
7633
7634DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7635 return Diags.Report(Loc, DiagID);
7636}
7637
7638/// \brief Retrieve the identifier table associated with the
7639/// preprocessor.
7640IdentifierTable &ASTReader::getIdentifierTable() {
7641 return PP.getIdentifierTable();
7642}
7643
7644/// \brief Record that the given ID maps to the given switch-case
7645/// statement.
7646void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7647 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7648 "Already have a SwitchCase with this ID");
7649 (*CurrSwitchCaseStmts)[ID] = SC;
7650}
7651
7652/// \brief Retrieve the switch-case statement with the given ID.
7653SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7654 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7655 return (*CurrSwitchCaseStmts)[ID];
7656}
7657
7658void ASTReader::ClearSwitchCaseIDs() {
7659 CurrSwitchCaseStmts->clear();
7660}
7661
7662void ASTReader::ReadComments() {
7663 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007664 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007665 serialization::ModuleFile *> >::iterator
7666 I = CommentsCursors.begin(),
7667 E = CommentsCursors.end();
7668 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007669 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007670 serialization::ModuleFile &F = *I->second;
7671 SavedStreamPosition SavedPosition(Cursor);
7672
7673 RecordData Record;
7674 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007675 llvm::BitstreamEntry Entry =
7676 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7677
7678 switch (Entry.Kind) {
7679 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7680 case llvm::BitstreamEntry::Error:
7681 Error("malformed block record in AST file");
7682 return;
7683 case llvm::BitstreamEntry::EndBlock:
7684 goto NextCursor;
7685 case llvm::BitstreamEntry::Record:
7686 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 }
7689
7690 // Read a record.
7691 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007692 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 case COMMENTS_RAW_COMMENT: {
7694 unsigned Idx = 0;
7695 SourceRange SR = ReadSourceRange(F, Record, Idx);
7696 RawComment::CommentKind Kind =
7697 (RawComment::CommentKind) Record[Idx++];
7698 bool IsTrailingComment = Record[Idx++];
7699 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007700 Comments.push_back(new (Context) RawComment(
7701 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7702 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007703 break;
7704 }
7705 }
7706 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007707 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 }
7709 Context.Comments.addCommentsToFront(Comments);
7710}
7711
7712void ASTReader::finishPendingActions() {
7713 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007714 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7715 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 // If any identifiers with corresponding top-level declarations have
7717 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007718 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7719 TopLevelDeclsMap;
7720 TopLevelDeclsMap TopLevelDecls;
7721
Guy Benyei11169dd2012-12-18 14:30:41 +00007722 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007723 // FIXME: std::move
7724 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7725 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007726 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007727
7728 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 }
7730
7731 // Load pending declaration chains.
7732 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7733 loadPendingDeclChain(PendingDeclChains[I]);
7734 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7735 }
7736 PendingDeclChains.clear();
7737
Douglas Gregor6168bd22013-02-18 15:53:43 +00007738 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007739 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7740 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007741 IdentifierInfo *II = TLD->first;
7742 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007743 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007744 }
7745 }
7746
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 // Load any pending macro definitions.
7748 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007749 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7750 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7751 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7752 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007753 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007754 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007755 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7756 if (Info.M->Kind != MK_Module)
7757 resolvePendingMacro(II, Info);
7758 }
7759 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007760 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007761 ++IDIdx) {
7762 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7763 if (Info.M->Kind == MK_Module)
7764 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007765 }
7766 }
7767 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007768
7769 // Wire up the DeclContexts for Decls that we delayed setting until
7770 // recursive loading is completed.
7771 while (!PendingDeclContextInfos.empty()) {
7772 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7773 PendingDeclContextInfos.pop_front();
7774 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7775 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7776 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7777 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007778
7779 // For each declaration from a merged context, check that the canonical
7780 // definition of that context also contains a declaration of the same
7781 // entity.
7782 while (!PendingOdrMergeChecks.empty()) {
7783 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7784
7785 // FIXME: Skip over implicit declarations for now. This matters for things
7786 // like implicitly-declared special member functions. This isn't entirely
7787 // correct; we can end up with multiple unmerged declarations of the same
7788 // implicit entity.
7789 if (D->isImplicit())
7790 continue;
7791
7792 DeclContext *CanonDef = D->getDeclContext();
7793 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7794
7795 bool Found = false;
7796 const Decl *DCanon = D->getCanonicalDecl();
7797
7798 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7799 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7800 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007801 for (auto RI : (*I)->redecls()) {
7802 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007803 // This declaration is present in the canonical definition. If it's
7804 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007805 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007806 Found = true;
7807 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007808 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007809 break;
7810 }
7811 }
7812 }
7813
7814 if (!Found) {
7815 D->setInvalidDecl();
7816
7817 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7818 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7819 << D << D->getOwningModule()->getFullModuleName()
7820 << CanonDef << !CanonDefModule
7821 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7822
7823 if (Candidates.empty())
7824 Diag(cast<Decl>(CanonDef)->getLocation(),
7825 diag::note_module_odr_violation_no_possible_decls) << D;
7826 else {
7827 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7828 Diag(Candidates[I]->getLocation(),
7829 diag::note_module_odr_violation_possible_decl)
7830 << Candidates[I];
7831 }
7832 }
7833 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 }
7835
7836 // If we deserialized any C++ or Objective-C class definitions, any
7837 // Objective-C protocol definitions, or any redeclarable templates, make sure
7838 // that all redeclarations point to the definitions. Note that this can only
7839 // happen now, after the redeclaration chains have been fully wired.
7840 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7841 DEnd = PendingDefinitions.end();
7842 D != DEnd; ++D) {
7843 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7844 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7845 // Make sure that the TagType points at the definition.
7846 const_cast<TagType*>(TagT)->decl = TD;
7847 }
7848
Aaron Ballman86c93902014-03-06 23:45:36 +00007849 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7850 for (auto R : RD->redecls())
7851 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00007852
7853 }
7854
7855 continue;
7856 }
7857
Aaron Ballman86c93902014-03-06 23:45:36 +00007858 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007859 // Make sure that the ObjCInterfaceType points at the definition.
7860 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7861 ->Decl = ID;
7862
Aaron Ballman86c93902014-03-06 23:45:36 +00007863 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007864 R->Data = ID->Data;
7865
7866 continue;
7867 }
7868
Aaron Ballman86c93902014-03-06 23:45:36 +00007869 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7870 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 R->Data = PD->Data;
7872
7873 continue;
7874 }
7875
Aaron Ballman86c93902014-03-06 23:45:36 +00007876 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7877 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 R->Common = RTD->Common;
7879 }
7880 PendingDefinitions.clear();
7881
7882 // Load the bodies of any functions or methods we've encountered. We do
7883 // this now (delayed) so that we can be sure that the declaration chains
7884 // have been fully wired up.
7885 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7886 PBEnd = PendingBodies.end();
7887 PB != PBEnd; ++PB) {
7888 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7889 // FIXME: Check for =delete/=default?
7890 // FIXME: Complain about ODR violations here?
7891 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7892 FD->setLazyBody(PB->second);
7893 continue;
7894 }
7895
7896 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7897 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7898 MD->setLazyBody(PB->second);
7899 }
7900 PendingBodies.clear();
7901}
7902
7903void ASTReader::FinishedDeserializing() {
7904 assert(NumCurrentElementsDeserializing &&
7905 "FinishedDeserializing not paired with StartedDeserializing");
7906 if (NumCurrentElementsDeserializing == 1) {
7907 // We decrease NumCurrentElementsDeserializing only after pending actions
7908 // are finished, to avoid recursively re-calling finishPendingActions().
7909 finishPendingActions();
7910 }
7911 --NumCurrentElementsDeserializing;
7912
7913 if (NumCurrentElementsDeserializing == 0 &&
7914 Consumer && !PassingDeclsToConsumer) {
7915 // Guard variable to avoid recursively redoing the process of passing
7916 // decls to consumer.
7917 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7918 true);
7919
7920 while (!InterestingDecls.empty()) {
7921 // We are not in recursive loading, so it's safe to pass the "interesting"
7922 // decls to the consumer.
7923 Decl *D = InterestingDecls.front();
7924 InterestingDecls.pop_front();
7925 PassInterestingDeclToConsumer(D);
7926 }
7927 }
7928}
7929
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007930void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007931 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007932
7933 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7934 SemaObj->TUScope->AddDecl(D);
7935 } else if (SemaObj->TUScope) {
7936 // Adding the decl to IdResolver may have failed because it was already in
7937 // (even though it was not added in scope). If it is already in, make sure
7938 // it gets in the scope as well.
7939 if (std::find(SemaObj->IdResolver.begin(Name),
7940 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7941 SemaObj->TUScope->AddDecl(D);
7942 }
7943}
7944
Guy Benyei11169dd2012-12-18 14:30:41 +00007945ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7946 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007947 bool AllowASTWithCompilerErrors,
7948 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007949 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007950 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007951 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7952 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7953 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7954 Consumer(0), ModuleMgr(PP.getFileManager()),
7955 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007956 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007957 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007958 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007959 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007960 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7961 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007962 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7963 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7964 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007965 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7966 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7967 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7969 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7970 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7971 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007972 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007973{
7974 SourceMgr.setExternalSLocEntrySource(this);
7975}
7976
7977ASTReader::~ASTReader() {
7978 for (DeclContextVisibleUpdatesPending::iterator
7979 I = PendingVisibleUpdates.begin(),
7980 E = PendingVisibleUpdates.end();
7981 I != E; ++I) {
7982 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7983 F = I->second.end();
7984 J != F; ++J)
7985 delete J->first;
7986 }
7987}