blob: cc425c5695a99852c476e6938779048052cce0a8 [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}
121bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000122 bool isSystem,
123 bool isOverridden) {
124 return First->visitInputFile(Filename, isSystem, isOverridden) ||
125 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000126}
127
Guy Benyei11169dd2012-12-18 14:30:41 +0000128//===----------------------------------------------------------------------===//
129// PCH validator implementation
130//===----------------------------------------------------------------------===//
131
132ASTReaderListener::~ASTReaderListener() {}
133
134/// \brief Compare the given set of language options against an existing set of
135/// language options.
136///
137/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
138///
139/// \returns true if the languagae options mis-match, false otherwise.
140static bool checkLanguageOptions(const LangOptions &LangOpts,
141 const LangOptions &ExistingLangOpts,
142 DiagnosticsEngine *Diags) {
143#define LANGOPT(Name, Bits, Default, Description) \
144 if (ExistingLangOpts.Name != LangOpts.Name) { \
145 if (Diags) \
146 Diags->Report(diag::err_pch_langopt_mismatch) \
147 << Description << LangOpts.Name << ExistingLangOpts.Name; \
148 return true; \
149 }
150
151#define VALUE_LANGOPT(Name, Bits, Default, Description) \
152 if (ExistingLangOpts.Name != LangOpts.Name) { \
153 if (Diags) \
154 Diags->Report(diag::err_pch_langopt_value_mismatch) \
155 << Description; \
156 return true; \
157 }
158
159#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
160 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
161 if (Diags) \
162 Diags->Report(diag::err_pch_langopt_value_mismatch) \
163 << Description; \
164 return true; \
165 }
166
167#define BENIGN_LANGOPT(Name, Bits, Default, Description)
168#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
169#include "clang/Basic/LangOptions.def"
170
171 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
172 if (Diags)
173 Diags->Report(diag::err_pch_langopt_value_mismatch)
174 << "target Objective-C runtime";
175 return true;
176 }
177
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000178 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
179 LangOpts.CommentOpts.BlockCommandNames) {
180 if (Diags)
181 Diags->Report(diag::err_pch_langopt_value_mismatch)
182 << "block command names";
183 return true;
184 }
185
Guy Benyei11169dd2012-12-18 14:30:41 +0000186 return false;
187}
188
189/// \brief Compare the given set of target options against an existing set of
190/// target options.
191///
192/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
193///
194/// \returns true if the target options mis-match, false otherwise.
195static bool checkTargetOptions(const TargetOptions &TargetOpts,
196 const TargetOptions &ExistingTargetOpts,
197 DiagnosticsEngine *Diags) {
198#define CHECK_TARGET_OPT(Field, Name) \
199 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
200 if (Diags) \
201 Diags->Report(diag::err_pch_targetopt_mismatch) \
202 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
203 return true; \
204 }
205
206 CHECK_TARGET_OPT(Triple, "target");
207 CHECK_TARGET_OPT(CPU, "target CPU");
208 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000209 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
210#undef CHECK_TARGET_OPT
211
212 // Compare feature sets.
213 SmallVector<StringRef, 4> ExistingFeatures(
214 ExistingTargetOpts.FeaturesAsWritten.begin(),
215 ExistingTargetOpts.FeaturesAsWritten.end());
216 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
217 TargetOpts.FeaturesAsWritten.end());
218 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
219 std::sort(ReadFeatures.begin(), ReadFeatures.end());
220
221 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
222 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
223 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
224 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
225 ++ExistingIdx;
226 ++ReadIdx;
227 continue;
228 }
229
230 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
231 if (Diags)
232 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
233 << false << ReadFeatures[ReadIdx];
234 return true;
235 }
236
237 if (Diags)
238 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
239 << true << ExistingFeatures[ExistingIdx];
240 return true;
241 }
242
243 if (ExistingIdx < ExistingN) {
244 if (Diags)
245 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
246 << true << ExistingFeatures[ExistingIdx];
247 return true;
248 }
249
250 if (ReadIdx < ReadN) {
251 if (Diags)
252 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
253 << false << ReadFeatures[ReadIdx];
254 return true;
255 }
256
257 return false;
258}
259
260bool
261PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
262 bool Complain) {
263 const LangOptions &ExistingLangOpts = PP.getLangOpts();
264 return checkLanguageOptions(LangOpts, ExistingLangOpts,
265 Complain? &Reader.Diags : 0);
266}
267
268bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
269 bool Complain) {
270 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
271 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
272 Complain? &Reader.Diags : 0);
273}
274
275namespace {
276 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
277 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000278 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
279 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000280}
281
282/// \brief Collect the macro definitions provided by the given preprocessor
283/// options.
284static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
285 MacroDefinitionsMap &Macros,
286 SmallVectorImpl<StringRef> *MacroNames = 0){
287 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
288 StringRef Macro = PPOpts.Macros[I].first;
289 bool IsUndef = PPOpts.Macros[I].second;
290
291 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
292 StringRef MacroName = MacroPair.first;
293 StringRef MacroBody = MacroPair.second;
294
295 // For an #undef'd macro, we only care about the name.
296 if (IsUndef) {
297 if (MacroNames && !Macros.count(MacroName))
298 MacroNames->push_back(MacroName);
299
300 Macros[MacroName] = std::make_pair("", true);
301 continue;
302 }
303
304 // For a #define'd macro, figure out the actual definition.
305 if (MacroName.size() == Macro.size())
306 MacroBody = "1";
307 else {
308 // Note: GCC drops anything following an end-of-line character.
309 StringRef::size_type End = MacroBody.find_first_of("\n\r");
310 MacroBody = MacroBody.substr(0, End);
311 }
312
313 if (MacroNames && !Macros.count(MacroName))
314 MacroNames->push_back(MacroName);
315 Macros[MacroName] = std::make_pair(MacroBody, false);
316 }
317}
318
319/// \brief Check the preprocessor options deserialized from the control block
320/// against the preprocessor options in an existing preprocessor.
321///
322/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
323static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
324 const PreprocessorOptions &ExistingPPOpts,
325 DiagnosticsEngine *Diags,
326 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000327 std::string &SuggestedPredefines,
328 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000329 // Check macro definitions.
330 MacroDefinitionsMap ASTFileMacros;
331 collectMacroDefinitions(PPOpts, ASTFileMacros);
332 MacroDefinitionsMap ExistingMacros;
333 SmallVector<StringRef, 4> ExistingMacroNames;
334 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
335
336 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
337 // Dig out the macro definition in the existing preprocessor options.
338 StringRef MacroName = ExistingMacroNames[I];
339 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
340
341 // Check whether we know anything about this macro name or not.
342 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
343 = ASTFileMacros.find(MacroName);
344 if (Known == ASTFileMacros.end()) {
345 // FIXME: Check whether this identifier was referenced anywhere in the
346 // AST file. If so, we should reject the AST file. Unfortunately, this
347 // information isn't in the control block. What shall we do about it?
348
349 if (Existing.second) {
350 SuggestedPredefines += "#undef ";
351 SuggestedPredefines += MacroName.str();
352 SuggestedPredefines += '\n';
353 } else {
354 SuggestedPredefines += "#define ";
355 SuggestedPredefines += MacroName.str();
356 SuggestedPredefines += ' ';
357 SuggestedPredefines += Existing.first.str();
358 SuggestedPredefines += '\n';
359 }
360 continue;
361 }
362
363 // If the macro was defined in one but undef'd in the other, we have a
364 // conflict.
365 if (Existing.second != Known->second.second) {
366 if (Diags) {
367 Diags->Report(diag::err_pch_macro_def_undef)
368 << MacroName << Known->second.second;
369 }
370 return true;
371 }
372
373 // If the macro was #undef'd in both, or if the macro bodies are identical,
374 // it's fine.
375 if (Existing.second || Existing.first == Known->second.first)
376 continue;
377
378 // The macro bodies differ; complain.
379 if (Diags) {
380 Diags->Report(diag::err_pch_macro_def_conflict)
381 << MacroName << Known->second.first << Existing.first;
382 }
383 return true;
384 }
385
386 // Check whether we're using predefines.
387 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
388 if (Diags) {
389 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
390 }
391 return true;
392 }
393
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000394 // Detailed record is important since it is used for the module cache hash.
395 if (LangOpts.Modules &&
396 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
397 if (Diags) {
398 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
399 }
400 return true;
401 }
402
Guy Benyei11169dd2012-12-18 14:30:41 +0000403 // Compute the #include and #include_macros lines we need.
404 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
405 StringRef File = ExistingPPOpts.Includes[I];
406 if (File == ExistingPPOpts.ImplicitPCHInclude)
407 continue;
408
409 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
410 != PPOpts.Includes.end())
411 continue;
412
413 SuggestedPredefines += "#include \"";
414 SuggestedPredefines +=
415 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
416 SuggestedPredefines += "\"\n";
417 }
418
419 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
420 StringRef File = ExistingPPOpts.MacroIncludes[I];
421 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
422 File)
423 != PPOpts.MacroIncludes.end())
424 continue;
425
426 SuggestedPredefines += "#__include_macros \"";
427 SuggestedPredefines +=
428 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
429 SuggestedPredefines += "\"\n##\n";
430 }
431
432 return false;
433}
434
435bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
436 bool Complain,
437 std::string &SuggestedPredefines) {
438 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
439
440 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
441 Complain? &Reader.Diags : 0,
442 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000443 SuggestedPredefines,
444 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000445}
446
Guy Benyei11169dd2012-12-18 14:30:41 +0000447void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
448 PP.setCounterValue(Value);
449}
450
451//===----------------------------------------------------------------------===//
452// AST reader implementation
453//===----------------------------------------------------------------------===//
454
455void
456ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
457 DeserializationListener = Listener;
458}
459
460
461
462unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
463 return serialization::ComputeHash(Sel);
464}
465
466
467std::pair<unsigned, unsigned>
468ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
469 using namespace clang::io;
470 unsigned KeyLen = ReadUnalignedLE16(d);
471 unsigned DataLen = ReadUnalignedLE16(d);
472 return std::make_pair(KeyLen, DataLen);
473}
474
475ASTSelectorLookupTrait::internal_key_type
476ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
477 using namespace clang::io;
478 SelectorTable &SelTable = Reader.getContext().Selectors;
479 unsigned N = ReadUnalignedLE16(d);
480 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000481 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000482 if (N == 0)
483 return SelTable.getNullarySelector(FirstII);
484 else if (N == 1)
485 return SelTable.getUnarySelector(FirstII);
486
487 SmallVector<IdentifierInfo *, 16> Args;
488 Args.push_back(FirstII);
489 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000490 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000491
492 return SelTable.getSelector(N, Args.data());
493}
494
495ASTSelectorLookupTrait::data_type
496ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
497 unsigned DataLen) {
498 using namespace clang::io;
499
500 data_type Result;
501
502 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000503 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
504 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
505 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
506 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
507 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
508 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000509
510 // Load instance methods
511 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
512 if (ObjCMethodDecl *Method
513 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
514 Result.Instance.push_back(Method);
515 }
516
517 // Load factory methods
518 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
519 if (ObjCMethodDecl *Method
520 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
521 Result.Factory.push_back(Method);
522 }
523
524 return Result;
525}
526
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000527unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
528 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000529}
530
531std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000532ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000533 using namespace clang::io;
534 unsigned DataLen = ReadUnalignedLE16(d);
535 unsigned KeyLen = ReadUnalignedLE16(d);
536 return std::make_pair(KeyLen, DataLen);
537}
538
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000539ASTIdentifierLookupTraitBase::internal_key_type
540ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000542 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000543}
544
Douglas Gregordcf25082013-02-11 18:16:18 +0000545/// \brief Whether the given identifier is "interesting".
546static bool isInterestingIdentifier(IdentifierInfo &II) {
547 return II.isPoisoned() ||
548 II.isExtensionToken() ||
549 II.getObjCOrBuiltinID() ||
550 II.hasRevertedTokenIDToIdentifier() ||
551 II.hadMacroDefinition() ||
552 II.getFETokenInfo<void>();
553}
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
556 const unsigned char* d,
557 unsigned DataLen) {
558 using namespace clang::io;
559 unsigned RawID = ReadUnalignedLE32(d);
560 bool IsInteresting = RawID & 0x01;
561
562 // Wipe out the "is interesting" bit.
563 RawID = RawID >> 1;
564
565 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
566 if (!IsInteresting) {
567 // For uninteresting identifiers, just build the IdentifierInfo
568 // and associate it with the persistent ID.
569 IdentifierInfo *II = KnownII;
570 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000571 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 KnownII = II;
573 }
574 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000575 if (!II->isFromAST()) {
576 bool WasInteresting = isInterestingIdentifier(*II);
577 II->setIsFromAST();
578 if (WasInteresting)
579 II->setChangedSinceDeserialization();
580 }
581 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 return II;
583 }
584
585 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
586 unsigned Bits = ReadUnalignedLE16(d);
587 bool CPlusPlusOperatorKeyword = Bits & 0x01;
588 Bits >>= 1;
589 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
590 Bits >>= 1;
591 bool Poisoned = Bits & 0x01;
592 Bits >>= 1;
593 bool ExtensionToken = Bits & 0x01;
594 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000595 bool hasSubmoduleMacros = Bits & 0x01;
596 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 bool hadMacroDefinition = Bits & 0x01;
598 Bits >>= 1;
599
600 assert(Bits == 0 && "Extra bits in the identifier?");
601 DataLen -= 8;
602
603 // Build the IdentifierInfo itself and link the identifier ID with
604 // the new IdentifierInfo.
605 IdentifierInfo *II = KnownII;
606 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000607 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 KnownII = II;
609 }
610 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000611 if (!II->isFromAST()) {
612 bool WasInteresting = isInterestingIdentifier(*II);
613 II->setIsFromAST();
614 if (WasInteresting)
615 II->setChangedSinceDeserialization();
616 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000617
618 // Set or check the various bits in the IdentifierInfo structure.
619 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000620 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 II->RevertTokenIDToIdentifier();
622 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
623 assert(II->isExtensionToken() == ExtensionToken &&
624 "Incorrect extension token flag");
625 (void)ExtensionToken;
626 if (Poisoned)
627 II->setIsPoisoned(true);
628 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
629 "Incorrect C++ operator keyword flag");
630 (void)CPlusPlusOperatorKeyword;
631
632 // If this identifier is a macro, deserialize the macro
633 // definition.
634 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000635 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
636 DataLen -= 4;
637 SmallVector<uint32_t, 8> LocalMacroIDs;
638 if (hasSubmoduleMacros) {
639 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
640 DataLen -= 4;
641 LocalMacroIDs.push_back(LocalMacroID);
642 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000643 DataLen -= 4;
644 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000645
646 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000647 // Macro definitions are stored from newest to oldest, so reverse them
648 // before registering them.
649 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000650 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000651 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
652 unsigned Size = 1;
653
654 static const uint32_t HasOverridesFlag = 0x80000000U;
655 if (I + 1 != E && (I[1] & HasOverridesFlag))
656 Size += 1 + (I[1] & ~HasOverridesFlag);
657
658 MacroSizes.push_back(Size);
659 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000660 }
Richard Smith49f906a2014-03-01 00:08:04 +0000661
662 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
663 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
664 SE = MacroSizes.rend();
665 SI != SE; ++SI) {
666 I -= *SI;
667
668 uint32_t LocalMacroID = *I;
669 llvm::ArrayRef<uint32_t> Overrides;
670 if (*SI != 1)
671 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
672 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
673 }
674 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000675 } else {
676 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
677 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 }
679
680 Reader.SetIdentifierInfo(ID, II);
681
682 // Read all of the declarations visible at global scope with this
683 // name.
684 if (DataLen > 0) {
685 SmallVector<uint32_t, 4> DeclIDs;
686 for (; DataLen > 0; DataLen -= 4)
687 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
688 Reader.SetGloballyVisibleDecls(II, DeclIDs);
689 }
690
691 return II;
692}
693
694unsigned
695ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
696 llvm::FoldingSetNodeID ID;
697 ID.AddInteger(Key.Kind);
698
699 switch (Key.Kind) {
700 case DeclarationName::Identifier:
701 case DeclarationName::CXXLiteralOperatorName:
702 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
703 break;
704 case DeclarationName::ObjCZeroArgSelector:
705 case DeclarationName::ObjCOneArgSelector:
706 case DeclarationName::ObjCMultiArgSelector:
707 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
708 break;
709 case DeclarationName::CXXOperatorName:
710 ID.AddInteger((OverloadedOperatorKind)Key.Data);
711 break;
712 case DeclarationName::CXXConstructorName:
713 case DeclarationName::CXXDestructorName:
714 case DeclarationName::CXXConversionFunctionName:
715 case DeclarationName::CXXUsingDirective:
716 break;
717 }
718
719 return ID.ComputeHash();
720}
721
722ASTDeclContextNameLookupTrait::internal_key_type
723ASTDeclContextNameLookupTrait::GetInternalKey(
724 const external_key_type& Name) const {
725 DeclNameKey Key;
726 Key.Kind = Name.getNameKind();
727 switch (Name.getNameKind()) {
728 case DeclarationName::Identifier:
729 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
730 break;
731 case DeclarationName::ObjCZeroArgSelector:
732 case DeclarationName::ObjCOneArgSelector:
733 case DeclarationName::ObjCMultiArgSelector:
734 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
735 break;
736 case DeclarationName::CXXOperatorName:
737 Key.Data = Name.getCXXOverloadedOperator();
738 break;
739 case DeclarationName::CXXLiteralOperatorName:
740 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
741 break;
742 case DeclarationName::CXXConstructorName:
743 case DeclarationName::CXXDestructorName:
744 case DeclarationName::CXXConversionFunctionName:
745 case DeclarationName::CXXUsingDirective:
746 Key.Data = 0;
747 break;
748 }
749
750 return Key;
751}
752
753std::pair<unsigned, unsigned>
754ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
755 using namespace clang::io;
756 unsigned KeyLen = ReadUnalignedLE16(d);
757 unsigned DataLen = ReadUnalignedLE16(d);
758 return std::make_pair(KeyLen, DataLen);
759}
760
761ASTDeclContextNameLookupTrait::internal_key_type
762ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
763 using namespace clang::io;
764
765 DeclNameKey Key;
766 Key.Kind = (DeclarationName::NameKind)*d++;
767 switch (Key.Kind) {
768 case DeclarationName::Identifier:
769 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
770 break;
771 case DeclarationName::ObjCZeroArgSelector:
772 case DeclarationName::ObjCOneArgSelector:
773 case DeclarationName::ObjCMultiArgSelector:
774 Key.Data =
775 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
776 .getAsOpaquePtr();
777 break;
778 case DeclarationName::CXXOperatorName:
779 Key.Data = *d++; // OverloadedOperatorKind
780 break;
781 case DeclarationName::CXXLiteralOperatorName:
782 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
783 break;
784 case DeclarationName::CXXConstructorName:
785 case DeclarationName::CXXDestructorName:
786 case DeclarationName::CXXConversionFunctionName:
787 case DeclarationName::CXXUsingDirective:
788 Key.Data = 0;
789 break;
790 }
791
792 return Key;
793}
794
795ASTDeclContextNameLookupTrait::data_type
796ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
797 const unsigned char* d,
798 unsigned DataLen) {
799 using namespace clang::io;
800 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000801 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
802 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000803 return std::make_pair(Start, Start + NumDecls);
804}
805
806bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000807 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000808 const std::pair<uint64_t, uint64_t> &Offsets,
809 DeclContextInfo &Info) {
810 SavedStreamPosition SavedPosition(Cursor);
811 // First the lexical decls.
812 if (Offsets.first != 0) {
813 Cursor.JumpToBit(Offsets.first);
814
815 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000816 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000817 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000818 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 if (RecCode != DECL_CONTEXT_LEXICAL) {
820 Error("Expected lexical block");
821 return true;
822 }
823
Chris Lattner0e6c9402013-01-20 02:38:54 +0000824 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
825 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 // Now the lookup table.
829 if (Offsets.second != 0) {
830 Cursor.JumpToBit(Offsets.second);
831
832 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000833 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000835 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 if (RecCode != DECL_CONTEXT_VISIBLE) {
837 Error("Expected visible lookup table block");
838 return true;
839 }
Richard Smith52e3fba2014-03-11 07:17:35 +0000840 Info.NameLookupTableData
841 = ASTDeclContextNameLookupTable::Create(
842 (const unsigned char *)Blob.data() + Record[0],
843 (const unsigned char *)Blob.data(),
844 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 }
846
847 return false;
848}
849
850void ASTReader::Error(StringRef Msg) {
851 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000852 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
853 Diag(diag::note_module_cache_path)
854 << PP.getHeaderSearchInfo().getModuleCachePath();
855 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000856}
857
858void ASTReader::Error(unsigned DiagID,
859 StringRef Arg1, StringRef Arg2) {
860 if (Diags.isDiagnosticInFlight())
861 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
862 else
863 Diag(DiagID) << Arg1 << Arg2;
864}
865
866//===----------------------------------------------------------------------===//
867// Source Manager Deserialization
868//===----------------------------------------------------------------------===//
869
870/// \brief Read the line table in the source manager block.
871/// \returns true if there was an error.
872bool ASTReader::ParseLineTable(ModuleFile &F,
873 SmallVectorImpl<uint64_t> &Record) {
874 unsigned Idx = 0;
875 LineTableInfo &LineTable = SourceMgr.getLineTable();
876
877 // Parse the file names
878 std::map<int, int> FileIDs;
879 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
880 // Extract the file name
881 unsigned FilenameLen = Record[Idx++];
882 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
883 Idx += FilenameLen;
884 MaybeAddSystemRootToFilename(F, Filename);
885 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
886 }
887
888 // Parse the line entries
889 std::vector<LineEntry> Entries;
890 while (Idx < Record.size()) {
891 int FID = Record[Idx++];
892 assert(FID >= 0 && "Serialized line entries for non-local file.");
893 // Remap FileID from 1-based old view.
894 FID += F.SLocEntryBaseID - 1;
895
896 // Extract the line entries
897 unsigned NumEntries = Record[Idx++];
898 assert(NumEntries && "Numentries is 00000");
899 Entries.clear();
900 Entries.reserve(NumEntries);
901 for (unsigned I = 0; I != NumEntries; ++I) {
902 unsigned FileOffset = Record[Idx++];
903 unsigned LineNo = Record[Idx++];
904 int FilenameID = FileIDs[Record[Idx++]];
905 SrcMgr::CharacteristicKind FileKind
906 = (SrcMgr::CharacteristicKind)Record[Idx++];
907 unsigned IncludeOffset = Record[Idx++];
908 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
909 FileKind, IncludeOffset));
910 }
911 LineTable.AddEntry(FileID::get(FID), Entries);
912 }
913
914 return false;
915}
916
917/// \brief Read a source manager block
918bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
919 using namespace SrcMgr;
920
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000921 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000922
923 // Set the source-location entry cursor to the current position in
924 // the stream. This cursor will be used to read the contents of the
925 // source manager block initially, and then lazily read
926 // source-location entries as needed.
927 SLocEntryCursor = F.Stream;
928
929 // The stream itself is going to skip over the source manager block.
930 if (F.Stream.SkipBlock()) {
931 Error("malformed block record in AST file");
932 return true;
933 }
934
935 // Enter the source manager block.
936 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
937 Error("malformed source manager block record in AST file");
938 return true;
939 }
940
941 RecordData Record;
942 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000943 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
944
945 switch (E.Kind) {
946 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
947 case llvm::BitstreamEntry::Error:
948 Error("malformed block record in AST file");
949 return true;
950 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000952 case llvm::BitstreamEntry::Record:
953 // The interesting case.
954 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000956
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000959 StringRef Blob;
960 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 default: // Default behavior: ignore.
962 break;
963
964 case SM_SLOC_FILE_ENTRY:
965 case SM_SLOC_BUFFER_ENTRY:
966 case SM_SLOC_EXPANSION_ENTRY:
967 // Once we hit one of the source location entries, we're done.
968 return false;
969 }
970 }
971}
972
973/// \brief If a header file is not found at the path that we expect it to be
974/// and the PCH file was moved from its original location, try to resolve the
975/// file by assuming that header+PCH were moved together and the header is in
976/// the same place relative to the PCH.
977static std::string
978resolveFileRelativeToOriginalDir(const std::string &Filename,
979 const std::string &OriginalDir,
980 const std::string &CurrDir) {
981 assert(OriginalDir != CurrDir &&
982 "No point trying to resolve the file if the PCH dir didn't change");
983 using namespace llvm::sys;
984 SmallString<128> filePath(Filename);
985 fs::make_absolute(filePath);
986 assert(path::is_absolute(OriginalDir));
987 SmallString<128> currPCHPath(CurrDir);
988
989 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
990 fileDirE = path::end(path::parent_path(filePath));
991 path::const_iterator origDirI = path::begin(OriginalDir),
992 origDirE = path::end(OriginalDir);
993 // Skip the common path components from filePath and OriginalDir.
994 while (fileDirI != fileDirE && origDirI != origDirE &&
995 *fileDirI == *origDirI) {
996 ++fileDirI;
997 ++origDirI;
998 }
999 for (; origDirI != origDirE; ++origDirI)
1000 path::append(currPCHPath, "..");
1001 path::append(currPCHPath, fileDirI, fileDirE);
1002 path::append(currPCHPath, path::filename(Filename));
1003 return currPCHPath.str();
1004}
1005
1006bool ASTReader::ReadSLocEntry(int ID) {
1007 if (ID == 0)
1008 return false;
1009
1010 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1011 Error("source location entry ID out-of-range for AST file");
1012 return true;
1013 }
1014
1015 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1016 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001017 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 unsigned BaseOffset = F->SLocEntryBaseOffset;
1019
1020 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001021 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1022 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 Error("incorrectly-formatted source location entry in AST file");
1024 return true;
1025 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001026
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001028 StringRef Blob;
1029 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 default:
1031 Error("incorrectly-formatted source location entry in AST file");
1032 return true;
1033
1034 case SM_SLOC_FILE_ENTRY: {
1035 // We will detect whether a file changed and return 'Failure' for it, but
1036 // we will also try to fail gracefully by setting up the SLocEntry.
1037 unsigned InputID = Record[4];
1038 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001039 const FileEntry *File = IF.getFile();
1040 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001041
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001042 // Note that we only check if a File was returned. If it was out-of-date
1043 // we have complained but we will continue creating a FileID to recover
1044 // gracefully.
1045 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001046 return true;
1047
1048 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1049 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1050 // This is the module's main file.
1051 IncludeLoc = getImportLocation(F);
1052 }
1053 SrcMgr::CharacteristicKind
1054 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1055 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1056 ID, BaseOffset + Record[0]);
1057 SrcMgr::FileInfo &FileInfo =
1058 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1059 FileInfo.NumCreatedFIDs = Record[5];
1060 if (Record[3])
1061 FileInfo.setHasLineDirectives();
1062
1063 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1064 unsigned NumFileDecls = Record[7];
1065 if (NumFileDecls) {
1066 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1067 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1068 NumFileDecls));
1069 }
1070
1071 const SrcMgr::ContentCache *ContentCache
1072 = SourceMgr.getOrCreateContentCache(File,
1073 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1074 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1075 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1076 unsigned Code = SLocEntryCursor.ReadCode();
1077 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001078 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001079
1080 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1081 Error("AST record has invalid code");
1082 return true;
1083 }
1084
1085 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001086 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 SourceMgr.overrideFileContents(File, Buffer);
1088 }
1089
1090 break;
1091 }
1092
1093 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001094 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 unsigned Offset = Record[0];
1096 SrcMgr::CharacteristicKind
1097 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1098 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1099 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1100 IncludeLoc = getImportLocation(F);
1101 }
1102 unsigned Code = SLocEntryCursor.ReadCode();
1103 Record.clear();
1104 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001105 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001106
1107 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1108 Error("AST record has invalid code");
1109 return true;
1110 }
1111
1112 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001113 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1115 BaseOffset + Offset, IncludeLoc);
1116 break;
1117 }
1118
1119 case SM_SLOC_EXPANSION_ENTRY: {
1120 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1121 SourceMgr.createExpansionLoc(SpellingLoc,
1122 ReadSourceLocation(*F, Record[2]),
1123 ReadSourceLocation(*F, Record[3]),
1124 Record[4],
1125 ID,
1126 BaseOffset + Record[0]);
1127 break;
1128 }
1129 }
1130
1131 return false;
1132}
1133
1134std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1135 if (ID == 0)
1136 return std::make_pair(SourceLocation(), "");
1137
1138 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1139 Error("source location entry ID out-of-range for AST file");
1140 return std::make_pair(SourceLocation(), "");
1141 }
1142
1143 // Find which module file this entry lands in.
1144 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1145 if (M->Kind != MK_Module)
1146 return std::make_pair(SourceLocation(), "");
1147
1148 // FIXME: Can we map this down to a particular submodule? That would be
1149 // ideal.
1150 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1151}
1152
1153/// \brief Find the location where the module F is imported.
1154SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1155 if (F->ImportLoc.isValid())
1156 return F->ImportLoc;
1157
1158 // Otherwise we have a PCH. It's considered to be "imported" at the first
1159 // location of its includer.
1160 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1161 // Main file is the importer. We assume that it is the first entry in the
1162 // entry table. We can't ask the manager, because at the time of PCH loading
1163 // the main file entry doesn't exist yet.
1164 // The very first entry is the invalid instantiation loc, which takes up
1165 // offsets 0 and 1.
1166 return SourceLocation::getFromRawEncoding(2U);
1167 }
1168 //return F->Loaders[0]->FirstLoc;
1169 return F->ImportedBy[0]->FirstLoc;
1170}
1171
1172/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1173/// specified cursor. Read the abbreviations that are at the top of the block
1174/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001175bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 if (Cursor.EnterSubBlock(BlockID)) {
1177 Error("malformed block record in AST file");
1178 return Failure;
1179 }
1180
1181 while (true) {
1182 uint64_t Offset = Cursor.GetCurrentBitNo();
1183 unsigned Code = Cursor.ReadCode();
1184
1185 // We expect all abbrevs to be at the start of the block.
1186 if (Code != llvm::bitc::DEFINE_ABBREV) {
1187 Cursor.JumpToBit(Offset);
1188 return false;
1189 }
1190 Cursor.ReadAbbrevRecord();
1191 }
1192}
1193
Richard Smithe40f2ba2013-08-07 21:41:30 +00001194Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001195 unsigned &Idx) {
1196 Token Tok;
1197 Tok.startToken();
1198 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1199 Tok.setLength(Record[Idx++]);
1200 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1201 Tok.setIdentifierInfo(II);
1202 Tok.setKind((tok::TokenKind)Record[Idx++]);
1203 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1204 return Tok;
1205}
1206
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001207MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001208 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001209
1210 // Keep track of where we are in the stream, then jump back there
1211 // after reading this macro.
1212 SavedStreamPosition SavedPosition(Stream);
1213
1214 Stream.JumpToBit(Offset);
1215 RecordData Record;
1216 SmallVector<IdentifierInfo*, 16> MacroArgs;
1217 MacroInfo *Macro = 0;
1218
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001220 // Advance to the next record, but if we get to the end of the block, don't
1221 // pop it (removing all the abbreviations from the cursor) since we want to
1222 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001223 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001224 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1225
1226 switch (Entry.Kind) {
1227 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1228 case llvm::BitstreamEntry::Error:
1229 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001230 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001231 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001232 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001233 case llvm::BitstreamEntry::Record:
1234 // The interesting case.
1235 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001236 }
1237
1238 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 Record.clear();
1240 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001241 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001243 case PP_MACRO_DIRECTIVE_HISTORY:
1244 return Macro;
1245
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 case PP_MACRO_OBJECT_LIKE:
1247 case PP_MACRO_FUNCTION_LIKE: {
1248 // If we already have a macro, that means that we've hit the end
1249 // of the definition of the macro we were looking for. We're
1250 // done.
1251 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001252 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001254 unsigned NextIndex = 1; // Skip identifier ID.
1255 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001256 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001257 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001258 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001259 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260
Guy Benyei11169dd2012-12-18 14:30:41 +00001261 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1262 // Decode function-like macro info.
1263 bool isC99VarArgs = Record[NextIndex++];
1264 bool isGNUVarArgs = Record[NextIndex++];
1265 bool hasCommaPasting = Record[NextIndex++];
1266 MacroArgs.clear();
1267 unsigned NumArgs = Record[NextIndex++];
1268 for (unsigned i = 0; i != NumArgs; ++i)
1269 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1270
1271 // Install function-like macro info.
1272 MI->setIsFunctionLike();
1273 if (isC99VarArgs) MI->setIsC99Varargs();
1274 if (isGNUVarArgs) MI->setIsGNUVarargs();
1275 if (hasCommaPasting) MI->setHasCommaPasting();
1276 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1277 PP.getPreprocessorAllocator());
1278 }
1279
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 // Remember that we saw this macro last so that we add the tokens that
1281 // form its body to it.
1282 Macro = MI;
1283
1284 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1285 Record[NextIndex]) {
1286 // We have a macro definition. Register the association
1287 PreprocessedEntityID
1288 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1289 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001290 PreprocessingRecord::PPEntityID
1291 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1292 MacroDefinition *PPDef =
1293 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1294 if (PPDef)
1295 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001296 }
1297
1298 ++NumMacrosRead;
1299 break;
1300 }
1301
1302 case PP_TOKEN: {
1303 // If we see a TOKEN before a PP_MACRO_*, then the file is
1304 // erroneous, just pretend we didn't see this.
1305 if (Macro == 0) break;
1306
John McCallf413f5e2013-05-03 00:10:13 +00001307 unsigned Idx = 0;
1308 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 Macro->AddTokenToBody(Tok);
1310 break;
1311 }
1312 }
1313 }
1314}
1315
1316PreprocessedEntityID
1317ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1318 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1319 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1320 assert(I != M.PreprocessedEntityRemap.end()
1321 && "Invalid index into preprocessed entity index remap");
1322
1323 return LocalID + I->second;
1324}
1325
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001326unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1327 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001328}
1329
1330HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001331HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1332 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1333 FE->getName() };
1334 return ikey;
1335}
Guy Benyei11169dd2012-12-18 14:30:41 +00001336
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001337bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1338 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001339 return false;
1340
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001341 if (strcmp(a.Filename, b.Filename) == 0)
1342 return true;
1343
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001345 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001346 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1347 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001348 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001349}
1350
1351std::pair<unsigned, unsigned>
1352HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1353 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1354 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001355 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001356}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001357
1358HeaderFileInfoTrait::internal_key_type
1359HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1360 internal_key_type ikey;
1361 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1362 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1363 ikey.Filename = (const char *)d;
1364 return ikey;
1365}
1366
Guy Benyei11169dd2012-12-18 14:30:41 +00001367HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001368HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 unsigned DataLen) {
1370 const unsigned char *End = d + DataLen;
1371 using namespace clang::io;
1372 HeaderFileInfo HFI;
1373 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001374 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1375 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 HFI.isImport = (Flags >> 5) & 0x01;
1377 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1378 HFI.DirInfo = (Flags >> 2) & 0x03;
1379 HFI.Resolved = (Flags >> 1) & 0x01;
1380 HFI.IndexHeaderMapHeader = Flags & 0x01;
1381 HFI.NumIncludes = ReadUnalignedLE16(d);
1382 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1383 ReadUnalignedLE32(d));
1384 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1385 // The framework offset is 1 greater than the actual offset,
1386 // since 0 is used as an indicator for "no framework name".
1387 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1388 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1389 }
1390
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001391 if (d != End) {
1392 uint32_t LocalSMID = ReadUnalignedLE32(d);
1393 if (LocalSMID) {
1394 // This header is part of a module. Associate it with the module to enable
1395 // implicit module import.
1396 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1397 Module *Mod = Reader.getSubmodule(GlobalSMID);
1398 HFI.isModuleHeader = true;
1399 FileManager &FileMgr = Reader.getFileManager();
1400 ModuleMap &ModMap =
1401 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001402 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001403 }
1404 }
1405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1407 (void)End;
1408
1409 // This HeaderFileInfo was externally loaded.
1410 HFI.External = true;
1411 return HFI;
1412}
1413
Richard Smith49f906a2014-03-01 00:08:04 +00001414void
1415ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1416 GlobalMacroID GMacID,
1417 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001419 SubmoduleID *OverrideData = 0;
1420 if (!Overrides.empty()) {
1421 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1422 OverrideData[0] = Overrides.size();
1423 for (unsigned I = 0; I != Overrides.size(); ++I)
1424 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1425 }
1426 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001427}
1428
1429void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1430 ModuleFile *M,
1431 uint64_t MacroDirectivesOffset) {
1432 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1433 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001434}
1435
1436void ASTReader::ReadDefinedMacros() {
1437 // Note that we are loading defined macros.
1438 Deserializing Macros(this);
1439
1440 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1441 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001442 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001443
1444 // If there was no preprocessor block, skip this file.
1445 if (!MacroCursor.getBitStreamReader())
1446 continue;
1447
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001448 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 Cursor.JumpToBit((*I)->MacroStartOffset);
1450
1451 RecordData Record;
1452 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001453 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1454
1455 switch (E.Kind) {
1456 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1457 case llvm::BitstreamEntry::Error:
1458 Error("malformed block record in AST file");
1459 return;
1460 case llvm::BitstreamEntry::EndBlock:
1461 goto NextCursor;
1462
1463 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001464 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001465 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001466 default: // Default behavior: ignore.
1467 break;
1468
1469 case PP_MACRO_OBJECT_LIKE:
1470 case PP_MACRO_FUNCTION_LIKE:
1471 getLocalIdentifier(**I, Record[0]);
1472 break;
1473
1474 case PP_TOKEN:
1475 // Ignore tokens.
1476 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 break;
1479 }
1480 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001481 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001482 }
1483}
1484
1485namespace {
1486 /// \brief Visitor class used to look up identifirs in an AST file.
1487 class IdentifierLookupVisitor {
1488 StringRef Name;
1489 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001490 unsigned &NumIdentifierLookups;
1491 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001493
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001495 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1496 unsigned &NumIdentifierLookups,
1497 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001498 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001499 NumIdentifierLookups(NumIdentifierLookups),
1500 NumIdentifierLookupHits(NumIdentifierLookupHits),
1501 Found()
1502 {
1503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001504
1505 static bool visit(ModuleFile &M, void *UserData) {
1506 IdentifierLookupVisitor *This
1507 = static_cast<IdentifierLookupVisitor *>(UserData);
1508
1509 // If we've already searched this module file, skip it now.
1510 if (M.Generation <= This->PriorGeneration)
1511 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 ASTIdentifierLookupTable *IdTable
1514 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1515 if (!IdTable)
1516 return false;
1517
1518 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1519 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001520 ++This->NumIdentifierLookups;
1521 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 if (Pos == IdTable->end())
1523 return false;
1524
1525 // Dereferencing the iterator has the effect of building the
1526 // IdentifierInfo node and populating it with the various
1527 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001528 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 This->Found = *Pos;
1530 return true;
1531 }
1532
1533 // \brief Retrieve the identifier info found within the module
1534 // files.
1535 IdentifierInfo *getIdentifierInfo() const { return Found; }
1536 };
1537}
1538
1539void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1540 // Note that we are loading an identifier.
1541 Deserializing AnIdentifier(this);
1542
1543 unsigned PriorGeneration = 0;
1544 if (getContext().getLangOpts().Modules)
1545 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001546
1547 // If there is a global index, look there first to determine which modules
1548 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001549 GlobalModuleIndex::HitSet Hits;
1550 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001551 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001552 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1553 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001554 }
1555 }
1556
Douglas Gregor7211ac12013-01-25 23:32:03 +00001557 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001558 NumIdentifierLookups,
1559 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001560 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 markIdentifierUpToDate(&II);
1562}
1563
1564void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1565 if (!II)
1566 return;
1567
1568 II->setOutOfDate(false);
1569
1570 // Update the generation for this identifier.
1571 if (getContext().getLangOpts().Modules)
1572 IdentifierGeneration[II] = CurrentGeneration;
1573}
1574
Richard Smith49f906a2014-03-01 00:08:04 +00001575struct ASTReader::ModuleMacroInfo {
1576 SubmoduleID SubModID;
1577 MacroInfo *MI;
1578 SubmoduleID *Overrides;
1579 // FIXME: Remove this.
1580 ModuleFile *F;
1581
1582 bool isDefine() const { return MI; }
1583
1584 SubmoduleID getSubmoduleID() const { return SubModID; }
1585
1586 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1587 if (!Overrides)
1588 return llvm::ArrayRef<SubmoduleID>();
1589 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1590 }
1591
1592 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1593 if (!MI)
1594 return 0;
1595 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1596 }
1597};
1598
1599ASTReader::ModuleMacroInfo *
1600ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1601 ModuleMacroInfo Info;
1602
1603 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1604 if (ID & 1) {
1605 // Macro undefinition.
1606 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1607 Info.MI = 0;
1608 } else {
1609 // Macro definition.
1610 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1611 assert(GMacID);
1612
1613 // If this macro has already been loaded, don't do so again.
1614 // FIXME: This is highly dubious. Multiple macro definitions can have the
1615 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1616 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1617 return 0;
1618
1619 Info.MI = getMacro(GMacID);
1620 Info.SubModID = Info.MI->getOwningModuleID();
1621 }
1622 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1623 Info.F = PMInfo.M;
1624
1625 return new (Context) ModuleMacroInfo(Info);
1626}
1627
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001628void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1629 const PendingMacroInfo &PMInfo) {
1630 assert(II);
1631
1632 if (PMInfo.M->Kind != MK_Module) {
1633 installPCHMacroDirectives(II, *PMInfo.M,
1634 PMInfo.PCHMacroData.MacroDirectivesOffset);
1635 return;
1636 }
Richard Smith49f906a2014-03-01 00:08:04 +00001637
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001638 // Module Macro.
1639
Richard Smith49f906a2014-03-01 00:08:04 +00001640 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1641 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001642 return;
1643
Richard Smith49f906a2014-03-01 00:08:04 +00001644 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1645 if (Owner && Owner->NameVisibility == Module::Hidden) {
1646 // Macros in the owning module are hidden. Just remember this macro to
1647 // install if we make this module visible.
1648 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1649 } else {
1650 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001651 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001652}
1653
1654void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1655 ModuleFile &M, uint64_t Offset) {
1656 assert(M.Kind != MK_Module);
1657
1658 BitstreamCursor &Cursor = M.MacroCursor;
1659 SavedStreamPosition SavedPosition(Cursor);
1660 Cursor.JumpToBit(Offset);
1661
1662 llvm::BitstreamEntry Entry =
1663 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1664 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1665 Error("malformed block record in AST file");
1666 return;
1667 }
1668
1669 RecordData Record;
1670 PreprocessorRecordTypes RecType =
1671 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1672 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1673 Error("malformed block record in AST file");
1674 return;
1675 }
1676
1677 // Deserialize the macro directives history in reverse source-order.
1678 MacroDirective *Latest = 0, *Earliest = 0;
1679 unsigned Idx = 0, N = Record.size();
1680 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001681 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001682 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001683 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1684 switch (K) {
1685 case MacroDirective::MD_Define: {
1686 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1687 MacroInfo *MI = getMacro(GMacID);
1688 bool isImported = Record[Idx++];
1689 bool isAmbiguous = Record[Idx++];
1690 DefMacroDirective *DefMD =
1691 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1692 DefMD->setAmbiguous(isAmbiguous);
1693 MD = DefMD;
1694 break;
1695 }
1696 case MacroDirective::MD_Undefine:
1697 MD = PP.AllocateUndefMacroDirective(Loc);
1698 break;
1699 case MacroDirective::MD_Visibility: {
1700 bool isPublic = Record[Idx++];
1701 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1702 break;
1703 }
1704 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001705
1706 if (!Latest)
1707 Latest = MD;
1708 if (Earliest)
1709 Earliest->setPrevious(MD);
1710 Earliest = MD;
1711 }
1712
1713 PP.setLoadedMacroDirective(II, Latest);
1714}
1715
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001716/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001717/// modules.
1718static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001719 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001720 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001721 Module *PrevOwner = 0;
1722 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1723 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001724 SourceManager &SrcMgr = Reader.getSourceManager();
1725 bool PrevInSystem
1726 = PrevOwner? PrevOwner->IsSystem
1727 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1728 bool NewInSystem
1729 = NewOwner? NewOwner->IsSystem
1730 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1731 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001732 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001733 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001734}
1735
Richard Smith49f906a2014-03-01 00:08:04 +00001736void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1737 AmbiguousMacros &Ambig,
1738 llvm::ArrayRef<SubmoduleID> Overrides) {
1739 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1740 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001741
Richard Smith49f906a2014-03-01 00:08:04 +00001742 // If this macro is not yet visible, remove it from the hidden names list.
1743 Module *Owner = getSubmodule(OwnerID);
1744 HiddenNames &Hidden = HiddenNamesMap[Owner];
1745 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1746 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001747 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001748 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001749 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001750 }
1751
1752 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001753 Ambig.erase(
1754 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1755 return MD->getInfo()->getOwningModuleID() == OwnerID;
1756 }),
1757 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001758 }
1759}
1760
1761ASTReader::AmbiguousMacros *
1762ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1763 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001765 if (!Prev && Overrides.empty())
1766 return 0;
1767
1768 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1769 if (PrevDef && PrevDef->isAmbiguous()) {
1770 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1771 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1772 Ambig.push_back(PrevDef);
1773
1774 removeOverriddenMacros(II, Ambig, Overrides);
1775
1776 if (!Ambig.empty())
1777 return &Ambig;
1778
1779 AmbiguousMacroDefs.erase(II);
1780 } else {
1781 // There's no ambiguity yet. Maybe we're introducing one.
1782 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1783 if (PrevDef)
1784 Ambig.push_back(PrevDef);
1785
1786 removeOverriddenMacros(II, Ambig, Overrides);
1787
1788 if (!Ambig.empty()) {
1789 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1790 Result.swap(Ambig);
1791 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001792 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001793 }
Richard Smith49f906a2014-03-01 00:08:04 +00001794
1795 // We ended up with no ambiguity.
1796 return 0;
1797}
1798
1799void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1800 Module *Owner) {
1801 assert(II && Owner);
1802
1803 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1804 if (ImportLoc.isInvalid()) {
1805 // FIXME: If we made macros from this module visible but didn't provide a
1806 // source location for the import, we don't have a location for the macro.
1807 // Use the location at which the containing module file was first imported
1808 // for now.
1809 ImportLoc = MMI->F->DirectImportLoc;
1810 }
1811
1812 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1813 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1814
1815
1816 // Create a synthetic macro definition corresponding to the import (or null
1817 // if this was an undefinition of the macro).
1818 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1819
1820 // If there's no ambiguity, just install the macro.
1821 if (!Prev) {
1822 if (MD)
1823 PP.appendMacroDirective(II, MD);
1824 else
1825 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1826 return;
1827 }
1828 assert(!Prev->empty());
1829
1830 if (!MD) {
1831 // We imported a #undef that didn't remove all prior definitions. The most
1832 // recent prior definition remains, and we install it in the place of the
1833 // imported directive.
1834 MacroInfo *NewMI = Prev->back()->getInfo();
1835 Prev->pop_back();
1836 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1837 }
1838
1839 // We're introducing a macro definition that creates or adds to an ambiguity.
1840 // We can resolve that ambiguity if this macro is token-for-token identical to
1841 // all of the existing definitions.
1842 MacroInfo *NewMI = MD->getInfo();
1843 assert(NewMI && "macro definition with no MacroInfo?");
1844 while (!Prev->empty()) {
1845 MacroInfo *PrevMI = Prev->back()->getInfo();
1846 assert(PrevMI && "macro definition with no MacroInfo?");
1847
1848 // Before marking the macros as ambiguous, check if this is a case where
1849 // both macros are in system headers. If so, we trust that the system
1850 // did not get it wrong. This also handles cases where Clang's own
1851 // headers have a different spelling of certain system macros:
1852 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1853 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1854 //
1855 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1856 // overrides the system limits.h's macros, so there's no conflict here.
1857 if (NewMI != PrevMI &&
1858 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1859 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1860 break;
1861
1862 // The previous definition is the same as this one (or both are defined in
1863 // system modules so we can assume they're equivalent); we don't need to
1864 // track it any more.
1865 Prev->pop_back();
1866 }
1867
1868 if (!Prev->empty())
1869 MD->setAmbiguous(true);
1870
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001871 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001872}
1873
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001874ASTReader::InputFileInfo
1875ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001876 // Go find this input file.
1877 BitstreamCursor &Cursor = F.InputFilesCursor;
1878 SavedStreamPosition SavedPosition(Cursor);
1879 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1880
1881 unsigned Code = Cursor.ReadCode();
1882 RecordData Record;
1883 StringRef Blob;
1884
1885 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1886 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1887 "invalid record type for input file");
1888 (void)Result;
1889
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001890 std::string Filename;
1891 off_t StoredSize;
1892 time_t StoredTime;
1893 bool Overridden;
1894
Ben Langmuir198c1682014-03-07 07:27:49 +00001895 assert(Record[0] == ID && "Bogus stored ID or offset");
1896 StoredSize = static_cast<off_t>(Record[1]);
1897 StoredTime = static_cast<time_t>(Record[2]);
1898 Overridden = static_cast<bool>(Record[3]);
1899 Filename = Blob;
1900 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001901
1902 return { std::move(Filename), StoredSize, StoredTime, Overridden };
Ben Langmuir198c1682014-03-07 07:27:49 +00001903}
1904
1905std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001906 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001907}
1908
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001909InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 // If this ID is bogus, just return an empty input file.
1911 if (ID == 0 || ID > F.InputFilesLoaded.size())
1912 return InputFile();
1913
1914 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001915 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 return F.InputFilesLoaded[ID-1];
1917
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001918 if (F.InputFilesLoaded[ID-1].isNotFound())
1919 return InputFile();
1920
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001922 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 SavedStreamPosition SavedPosition(Cursor);
1924 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1925
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001926 InputFileInfo FI = readInputFileInfo(F, ID);
1927 off_t StoredSize = FI.StoredSize;
1928 time_t StoredTime = FI.StoredTime;
1929 bool Overridden = FI.Overridden;
1930 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001931
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 const FileEntry *File
1933 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1934 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1935
1936 // If we didn't find the file, resolve it relative to the
1937 // original directory from which this AST file was created.
1938 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1939 F.OriginalDir != CurrentDir) {
1940 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1941 F.OriginalDir,
1942 CurrentDir);
1943 if (!Resolved.empty())
1944 File = FileMgr.getFile(Resolved);
1945 }
1946
1947 // For an overridden file, create a virtual file with the stored
1948 // size/timestamp.
1949 if (Overridden && File == 0) {
1950 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1951 }
1952
1953 if (File == 0) {
1954 if (Complain) {
1955 std::string ErrorStr = "could not find file '";
1956 ErrorStr += Filename;
1957 ErrorStr += "' referenced by AST file";
1958 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001959 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001960 // Record that we didn't find the file.
1961 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1962 return InputFile();
1963 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001964
Ben Langmuir198c1682014-03-07 07:27:49 +00001965 // Check if there was a request to override the contents of the file
1966 // that was part of the precompiled header. Overridding such a file
1967 // can lead to problems when lexing using the source locations from the
1968 // PCH.
1969 SourceManager &SM = getSourceManager();
1970 if (!Overridden && SM.isFileOverridden(File)) {
1971 if (Complain)
1972 Error(diag::err_fe_pch_file_overridden, Filename);
1973 // After emitting the diagnostic, recover by disabling the override so
1974 // that the original file will be used.
1975 SM.disableFileContentsOverride(File);
1976 // The FileEntry is a virtual file entry with the size of the contents
1977 // that would override the original contents. Set it to the original's
1978 // size/time.
1979 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1980 StoredSize, StoredTime);
1981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001982
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 bool IsOutOfDate = false;
1984
1985 // For an overridden file, there is nothing to validate.
1986 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001987#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 // In our regression testing, the Windows file system seems to
1989 // have inconsistent modification times that sometimes
1990 // erroneously trigger this error-handling path.
1991 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00001992#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 )) {
1994 if (Complain) {
1995 // Build a list of the PCH imports that got us here (in reverse).
1996 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1997 while (ImportStack.back()->ImportedBy.size() > 0)
1998 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 // The top-level PCH is stale.
2001 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2002 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002003
Ben Langmuir198c1682014-03-07 07:27:49 +00002004 // Print the import stack.
2005 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2006 Diag(diag::note_pch_required_by)
2007 << Filename << ImportStack[0]->FileName;
2008 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002009 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002010 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002011 }
2012
Ben Langmuir198c1682014-03-07 07:27:49 +00002013 if (!Diags.isDiagnosticInFlight())
2014 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 }
2016
Ben Langmuir198c1682014-03-07 07:27:49 +00002017 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 }
2019
Ben Langmuir198c1682014-03-07 07:27:49 +00002020 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2021
2022 // Note that we've loaded this input file.
2023 F.InputFilesLoaded[ID-1] = IF;
2024 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025}
2026
2027const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2028 ModuleFile &M = ModuleMgr.getPrimaryModule();
2029 std::string Filename = filenameStrRef;
2030 MaybeAddSystemRootToFilename(M, Filename);
2031 const FileEntry *File = FileMgr.getFile(Filename);
2032 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2033 M.OriginalDir != CurrentDir) {
2034 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2035 M.OriginalDir,
2036 CurrentDir);
2037 if (!resolved.empty())
2038 File = FileMgr.getFile(resolved);
2039 }
2040
2041 return File;
2042}
2043
2044/// \brief If we are loading a relocatable PCH file, and the filename is
2045/// not an absolute path, add the system root to the beginning of the file
2046/// name.
2047void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2048 std::string &Filename) {
2049 // If this is not a relocatable PCH file, there's nothing to do.
2050 if (!M.RelocatablePCH)
2051 return;
2052
2053 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2054 return;
2055
2056 if (isysroot.empty()) {
2057 // If no system root was given, default to '/'
2058 Filename.insert(Filename.begin(), '/');
2059 return;
2060 }
2061
2062 unsigned Length = isysroot.size();
2063 if (isysroot[Length - 1] != '/')
2064 Filename.insert(Filename.begin(), '/');
2065
2066 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2067}
2068
2069ASTReader::ASTReadResult
2070ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002071 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00002072 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002073 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002074
2075 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2076 Error("malformed block record in AST file");
2077 return Failure;
2078 }
2079
2080 // Read all of the records and blocks in the control block.
2081 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002082 while (1) {
2083 llvm::BitstreamEntry Entry = Stream.advance();
2084
2085 switch (Entry.Kind) {
2086 case llvm::BitstreamEntry::Error:
2087 Error("malformed block record in AST file");
2088 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002089 case llvm::BitstreamEntry::EndBlock: {
2090 // Validate input files.
2091 const HeaderSearchOptions &HSOpts =
2092 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002093
2094 // All user input files reside at the index range [0, Record[1]), and
2095 // system input files reside at [Record[1], Record[0]).
2096 // Record is the one from INPUT_FILE_OFFSETS.
2097 unsigned NumInputs = Record[0];
2098 unsigned NumUserInputs = Record[1];
2099
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002100 if (!DisableValidation &&
2101 (!HSOpts.ModulesValidateOncePerBuildSession ||
2102 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002104
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002105 // If we are reading a module, we will create a verification timestamp,
2106 // so we verify all input files. Otherwise, verify only user input
2107 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002108
2109 unsigned N = NumUserInputs;
2110 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002111 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2112 N = NumInputs;
2113
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002114 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002115 InputFile IF = getInputFile(F, I+1, Complain);
2116 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002120
2121 if (Listener && Listener->needsInputFileVisitation()) {
2122 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2123 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002124 for (unsigned I = 0; I < N; ++I) {
2125 bool IsSystem = I >= NumUserInputs;
2126 InputFileInfo FI = readInputFileInfo(F, I+1);
2127 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2128 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002129 }
2130
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002132 }
2133
Chris Lattnere7b154b2013-01-19 21:39:22 +00002134 case llvm::BitstreamEntry::SubBlock:
2135 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002136 case INPUT_FILES_BLOCK_ID:
2137 F.InputFilesCursor = Stream;
2138 if (Stream.SkipBlock() || // Skip with the main cursor
2139 // Read the abbreviations
2140 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2141 Error("malformed block record in AST file");
2142 return Failure;
2143 }
2144 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002145
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002147 if (Stream.SkipBlock()) {
2148 Error("malformed block record in AST file");
2149 return Failure;
2150 }
2151 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002153
2154 case llvm::BitstreamEntry::Record:
2155 // The interesting case.
2156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 }
2158
2159 // Read and process a record.
2160 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002161 StringRef Blob;
2162 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 case METADATA: {
2164 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2165 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002166 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2167 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002168 return VersionMismatch;
2169 }
2170
2171 bool hasErrors = Record[5];
2172 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2173 Diag(diag::err_pch_with_compiler_errors);
2174 return HadErrors;
2175 }
2176
2177 F.RelocatablePCH = Record[4];
2178
2179 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002180 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2182 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002183 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002184 return VersionMismatch;
2185 }
2186 break;
2187 }
2188
2189 case IMPORTS: {
2190 // Load each of the imported PCH files.
2191 unsigned Idx = 0, N = Record.size();
2192 while (Idx < N) {
2193 // Read information about the AST file.
2194 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2195 // The import location will be the local one for now; we will adjust
2196 // all import locations of module imports after the global source
2197 // location info are setup.
2198 SourceLocation ImportLoc =
2199 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002200 off_t StoredSize = (off_t)Record[Idx++];
2201 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002202 unsigned Length = Record[Idx++];
2203 SmallString<128> ImportedFile(Record.begin() + Idx,
2204 Record.begin() + Idx + Length);
2205 Idx += Length;
2206
2207 // Load the AST file.
2208 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002209 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 ClientLoadCapabilities)) {
2211 case Failure: return Failure;
2212 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002213 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 case OutOfDate: return OutOfDate;
2215 case VersionMismatch: return VersionMismatch;
2216 case ConfigurationMismatch: return ConfigurationMismatch;
2217 case HadErrors: return HadErrors;
2218 case Success: break;
2219 }
2220 }
2221 break;
2222 }
2223
2224 case LANGUAGE_OPTIONS: {
2225 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2226 if (Listener && &F == *ModuleMgr.begin() &&
2227 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002228 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 return ConfigurationMismatch;
2230 break;
2231 }
2232
2233 case TARGET_OPTIONS: {
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2235 if (Listener && &F == *ModuleMgr.begin() &&
2236 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002237 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 return ConfigurationMismatch;
2239 break;
2240 }
2241
2242 case DIAGNOSTIC_OPTIONS: {
2243 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2244 if (Listener && &F == *ModuleMgr.begin() &&
2245 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002246 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 return ConfigurationMismatch;
2248 break;
2249 }
2250
2251 case FILE_SYSTEM_OPTIONS: {
2252 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2253 if (Listener && &F == *ModuleMgr.begin() &&
2254 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002255 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 return ConfigurationMismatch;
2257 break;
2258 }
2259
2260 case HEADER_SEARCH_OPTIONS: {
2261 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2262 if (Listener && &F == *ModuleMgr.begin() &&
2263 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002264 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 return ConfigurationMismatch;
2266 break;
2267 }
2268
2269 case PREPROCESSOR_OPTIONS: {
2270 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2271 if (Listener && &F == *ModuleMgr.begin() &&
2272 ParsePreprocessorOptions(Record, Complain, *Listener,
2273 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002274 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 return ConfigurationMismatch;
2276 break;
2277 }
2278
2279 case ORIGINAL_FILE:
2280 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002281 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2283 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2284 break;
2285
2286 case ORIGINAL_FILE_ID:
2287 F.OriginalSourceFileID = FileID::get(Record[0]);
2288 break;
2289
2290 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002291 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 break;
2293
2294 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002295 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 F.InputFilesLoaded.resize(Record[0]);
2297 break;
2298 }
2299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002300}
2301
2302bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002303 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002304
2305 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2306 Error("malformed block record in AST file");
2307 return true;
2308 }
2309
2310 // Read all of the records and blocks for the AST file.
2311 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002312 while (1) {
2313 llvm::BitstreamEntry Entry = Stream.advance();
2314
2315 switch (Entry.Kind) {
2316 case llvm::BitstreamEntry::Error:
2317 Error("error at end of module block in AST file");
2318 return true;
2319 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002320 // Outside of C++, we do not store a lookup map for the translation unit.
2321 // Instead, mark it as needing a lookup map to be built if this module
2322 // contains any declarations lexically within it (which it always does!).
2323 // This usually has no cost, since we very rarely need the lookup map for
2324 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002326 if (DC->hasExternalLexicalStorage() &&
2327 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002329
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 return false;
2331 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002332 case llvm::BitstreamEntry::SubBlock:
2333 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 case DECLTYPES_BLOCK_ID:
2335 // We lazily load the decls block, but we want to set up the
2336 // DeclsCursor cursor to point into it. Clone our current bitcode
2337 // cursor to it, enter the block and read the abbrevs in that block.
2338 // With the main cursor, we just skip over it.
2339 F.DeclsCursor = Stream;
2340 if (Stream.SkipBlock() || // Skip with the main cursor.
2341 // Read the abbrevs.
2342 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2343 Error("malformed block record in AST file");
2344 return true;
2345 }
2346 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002347
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 case DECL_UPDATES_BLOCK_ID:
2349 if (Stream.SkipBlock()) {
2350 Error("malformed block record in AST file");
2351 return true;
2352 }
2353 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 case PREPROCESSOR_BLOCK_ID:
2356 F.MacroCursor = Stream;
2357 if (!PP.getExternalSource())
2358 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002359
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 if (Stream.SkipBlock() ||
2361 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2362 Error("malformed block record in AST file");
2363 return true;
2364 }
2365 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2366 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 case PREPROCESSOR_DETAIL_BLOCK_ID:
2369 F.PreprocessorDetailCursor = Stream;
2370 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002371 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002373 Error("malformed preprocessor detail record in AST file");
2374 return true;
2375 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002377 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2378
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 if (!PP.getPreprocessingRecord())
2380 PP.createPreprocessingRecord();
2381 if (!PP.getPreprocessingRecord()->getExternalSource())
2382 PP.getPreprocessingRecord()->SetExternalSource(*this);
2383 break;
2384
2385 case SOURCE_MANAGER_BLOCK_ID:
2386 if (ReadSourceManagerBlock(F))
2387 return true;
2388 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 case SUBMODULE_BLOCK_ID:
2391 if (ReadSubmoduleBlock(F))
2392 return true;
2393 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002394
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002396 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 if (Stream.SkipBlock() ||
2398 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2399 Error("malformed comments block in AST file");
2400 return true;
2401 }
2402 CommentsCursors.push_back(std::make_pair(C, &F));
2403 break;
2404 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002405
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002407 if (Stream.SkipBlock()) {
2408 Error("malformed block record in AST file");
2409 return true;
2410 }
2411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 }
2413 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002414
2415 case llvm::BitstreamEntry::Record:
2416 // The interesting case.
2417 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 }
2419
2420 // Read and process a record.
2421 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002422 StringRef Blob;
2423 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 default: // Default behavior: ignore.
2425 break;
2426
2427 case TYPE_OFFSET: {
2428 if (F.LocalNumTypes != 0) {
2429 Error("duplicate TYPE_OFFSET record in AST file");
2430 return true;
2431 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 F.LocalNumTypes = Record[0];
2434 unsigned LocalBaseTypeIndex = Record[1];
2435 F.BaseTypeIndex = getTotalNumTypes();
2436
2437 if (F.LocalNumTypes > 0) {
2438 // Introduce the global -> local mapping for types within this module.
2439 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2440
2441 // Introduce the local -> global mapping for types within this module.
2442 F.TypeRemap.insertOrReplace(
2443 std::make_pair(LocalBaseTypeIndex,
2444 F.BaseTypeIndex - LocalBaseTypeIndex));
2445
2446 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2447 }
2448 break;
2449 }
2450
2451 case DECL_OFFSET: {
2452 if (F.LocalNumDecls != 0) {
2453 Error("duplicate DECL_OFFSET record in AST file");
2454 return true;
2455 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002456 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 F.LocalNumDecls = Record[0];
2458 unsigned LocalBaseDeclID = Record[1];
2459 F.BaseDeclID = getTotalNumDecls();
2460
2461 if (F.LocalNumDecls > 0) {
2462 // Introduce the global -> local mapping for declarations within this
2463 // module.
2464 GlobalDeclMap.insert(
2465 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2466
2467 // Introduce the local -> global mapping for declarations within this
2468 // module.
2469 F.DeclRemap.insertOrReplace(
2470 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2471
2472 // Introduce the global -> local mapping for declarations within this
2473 // module.
2474 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2475
2476 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2477 }
2478 break;
2479 }
2480
2481 case TU_UPDATE_LEXICAL: {
2482 DeclContext *TU = Context.getTranslationUnitDecl();
2483 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002484 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002486 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 TU->setHasExternalLexicalStorage(true);
2488 break;
2489 }
2490
2491 case UPDATE_VISIBLE: {
2492 unsigned Idx = 0;
2493 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2494 ASTDeclContextNameLookupTable *Table =
2495 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002496 (const unsigned char *)Blob.data() + Record[Idx++],
2497 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 ASTDeclContextNameLookupTrait(*this, F));
2499 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2500 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith52e3fba2014-03-11 07:17:35 +00002501 F.DeclContextInfos[TU].NameLookupTableData = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 TU->setHasExternalVisibleStorage(true);
Richard Smithd9174792014-03-11 03:10:46 +00002503 } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2504 auto *DC = cast<DeclContext>(D);
2505 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002506 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2507 delete LookupTable;
2508 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 } else
2510 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2511 break;
2512 }
2513
2514 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002515 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 if (Record[0]) {
2517 F.IdentifierLookupTable
2518 = ASTIdentifierLookupTable::Create(
2519 (const unsigned char *)F.IdentifierTableData + Record[0],
2520 (const unsigned char *)F.IdentifierTableData,
2521 ASTIdentifierLookupTrait(*this, F));
2522
2523 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2524 }
2525 break;
2526
2527 case IDENTIFIER_OFFSET: {
2528 if (F.LocalNumIdentifiers != 0) {
2529 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2530 return true;
2531 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002532 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 F.LocalNumIdentifiers = Record[0];
2534 unsigned LocalBaseIdentifierID = Record[1];
2535 F.BaseIdentifierID = getTotalNumIdentifiers();
2536
2537 if (F.LocalNumIdentifiers > 0) {
2538 // Introduce the global -> local mapping for identifiers within this
2539 // module.
2540 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2541 &F));
2542
2543 // Introduce the local -> global mapping for identifiers within this
2544 // module.
2545 F.IdentifierRemap.insertOrReplace(
2546 std::make_pair(LocalBaseIdentifierID,
2547 F.BaseIdentifierID - LocalBaseIdentifierID));
2548
2549 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2550 + F.LocalNumIdentifiers);
2551 }
2552 break;
2553 }
2554
Ben Langmuir332aafe2014-01-31 01:06:56 +00002555 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002557 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 break;
2559
2560 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002561 if (SpecialTypes.empty()) {
2562 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2563 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2564 break;
2565 }
2566
2567 if (SpecialTypes.size() != Record.size()) {
2568 Error("invalid special-types record");
2569 return true;
2570 }
2571
2572 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2573 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2574 if (!SpecialTypes[I])
2575 SpecialTypes[I] = ID;
2576 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2577 // merge step?
2578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 break;
2580
2581 case STATISTICS:
2582 TotalNumStatements += Record[0];
2583 TotalNumMacros += Record[1];
2584 TotalLexicalDeclContexts += Record[2];
2585 TotalVisibleDeclContexts += Record[3];
2586 break;
2587
2588 case UNUSED_FILESCOPED_DECLS:
2589 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2590 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2591 break;
2592
2593 case DELEGATING_CTORS:
2594 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2595 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2596 break;
2597
2598 case WEAK_UNDECLARED_IDENTIFIERS:
2599 if (Record.size() % 4 != 0) {
2600 Error("invalid weak identifiers record");
2601 return true;
2602 }
2603
2604 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2605 // files. This isn't the way to do it :)
2606 WeakUndeclaredIdentifiers.clear();
2607
2608 // Translate the weak, undeclared identifiers into global IDs.
2609 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2610 WeakUndeclaredIdentifiers.push_back(
2611 getGlobalIdentifierID(F, Record[I++]));
2612 WeakUndeclaredIdentifiers.push_back(
2613 getGlobalIdentifierID(F, Record[I++]));
2614 WeakUndeclaredIdentifiers.push_back(
2615 ReadSourceLocation(F, Record, I).getRawEncoding());
2616 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2617 }
2618 break;
2619
Richard Smith78165b52013-01-10 23:43:47 +00002620 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002622 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 break;
2624
2625 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002626 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 F.LocalNumSelectors = Record[0];
2628 unsigned LocalBaseSelectorID = Record[1];
2629 F.BaseSelectorID = getTotalNumSelectors();
2630
2631 if (F.LocalNumSelectors > 0) {
2632 // Introduce the global -> local mapping for selectors within this
2633 // module.
2634 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2635
2636 // Introduce the local -> global mapping for selectors within this
2637 // module.
2638 F.SelectorRemap.insertOrReplace(
2639 std::make_pair(LocalBaseSelectorID,
2640 F.BaseSelectorID - LocalBaseSelectorID));
2641
2642 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2643 }
2644 break;
2645 }
2646
2647 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002648 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 if (Record[0])
2650 F.SelectorLookupTable
2651 = ASTSelectorLookupTable::Create(
2652 F.SelectorLookupTableData + Record[0],
2653 F.SelectorLookupTableData,
2654 ASTSelectorLookupTrait(*this, F));
2655 TotalNumMethodPoolEntries += Record[1];
2656 break;
2657
2658 case REFERENCED_SELECTOR_POOL:
2659 if (!Record.empty()) {
2660 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2661 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2662 Record[Idx++]));
2663 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2664 getRawEncoding());
2665 }
2666 }
2667 break;
2668
2669 case PP_COUNTER_VALUE:
2670 if (!Record.empty() && Listener)
2671 Listener->ReadCounter(F, Record[0]);
2672 break;
2673
2674 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002675 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 F.NumFileSortedDecls = Record[0];
2677 break;
2678
2679 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002680 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 F.LocalNumSLocEntries = Record[0];
2682 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002683 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2685 SLocSpaceSize);
2686 // Make our entry in the range map. BaseID is negative and growing, so
2687 // we invert it. Because we invert it, though, we need the other end of
2688 // the range.
2689 unsigned RangeStart =
2690 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2691 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2692 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2693
2694 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2695 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2696 GlobalSLocOffsetMap.insert(
2697 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2698 - SLocSpaceSize,&F));
2699
2700 // Initialize the remapping table.
2701 // Invalid stays invalid.
2702 F.SLocRemap.insert(std::make_pair(0U, 0));
2703 // This module. Base was 2 when being compiled.
2704 F.SLocRemap.insert(std::make_pair(2U,
2705 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2706
2707 TotalNumSLocEntries += F.LocalNumSLocEntries;
2708 break;
2709 }
2710
2711 case MODULE_OFFSET_MAP: {
2712 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002713 const unsigned char *Data = (const unsigned char*)Blob.data();
2714 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002715
2716 // Continuous range maps we may be updating in our module.
2717 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2718 ContinuousRangeMap<uint32_t, int, 2>::Builder
2719 IdentifierRemap(F.IdentifierRemap);
2720 ContinuousRangeMap<uint32_t, int, 2>::Builder
2721 MacroRemap(F.MacroRemap);
2722 ContinuousRangeMap<uint32_t, int, 2>::Builder
2723 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2724 ContinuousRangeMap<uint32_t, int, 2>::Builder
2725 SubmoduleRemap(F.SubmoduleRemap);
2726 ContinuousRangeMap<uint32_t, int, 2>::Builder
2727 SelectorRemap(F.SelectorRemap);
2728 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2729 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2730
2731 while(Data < DataEnd) {
2732 uint16_t Len = io::ReadUnalignedLE16(Data);
2733 StringRef Name = StringRef((const char*)Data, Len);
2734 Data += Len;
2735 ModuleFile *OM = ModuleMgr.lookup(Name);
2736 if (!OM) {
2737 Error("SourceLocation remap refers to unknown module");
2738 return true;
2739 }
2740
2741 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2742 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2743 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2744 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2745 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2746 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2747 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2748 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2749
2750 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2751 SLocRemap.insert(std::make_pair(SLocOffset,
2752 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2753 IdentifierRemap.insert(
2754 std::make_pair(IdentifierIDOffset,
2755 OM->BaseIdentifierID - IdentifierIDOffset));
2756 MacroRemap.insert(std::make_pair(MacroIDOffset,
2757 OM->BaseMacroID - MacroIDOffset));
2758 PreprocessedEntityRemap.insert(
2759 std::make_pair(PreprocessedEntityIDOffset,
2760 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2761 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2762 OM->BaseSubmoduleID - SubmoduleIDOffset));
2763 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2764 OM->BaseSelectorID - SelectorIDOffset));
2765 DeclRemap.insert(std::make_pair(DeclIDOffset,
2766 OM->BaseDeclID - DeclIDOffset));
2767
2768 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2769 OM->BaseTypeIndex - TypeIndexOffset));
2770
2771 // Global -> local mappings.
2772 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2773 }
2774 break;
2775 }
2776
2777 case SOURCE_MANAGER_LINE_TABLE:
2778 if (ParseLineTable(F, Record))
2779 return true;
2780 break;
2781
2782 case SOURCE_LOCATION_PRELOADS: {
2783 // Need to transform from the local view (1-based IDs) to the global view,
2784 // which is based off F.SLocEntryBaseID.
2785 if (!F.PreloadSLocEntries.empty()) {
2786 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2787 return true;
2788 }
2789
2790 F.PreloadSLocEntries.swap(Record);
2791 break;
2792 }
2793
2794 case EXT_VECTOR_DECLS:
2795 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2796 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2797 break;
2798
2799 case VTABLE_USES:
2800 if (Record.size() % 3 != 0) {
2801 Error("Invalid VTABLE_USES record");
2802 return true;
2803 }
2804
2805 // Later tables overwrite earlier ones.
2806 // FIXME: Modules will have some trouble with this. This is clearly not
2807 // the right way to do this.
2808 VTableUses.clear();
2809
2810 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2811 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2812 VTableUses.push_back(
2813 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2814 VTableUses.push_back(Record[Idx++]);
2815 }
2816 break;
2817
2818 case DYNAMIC_CLASSES:
2819 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2820 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2821 break;
2822
2823 case PENDING_IMPLICIT_INSTANTIATIONS:
2824 if (PendingInstantiations.size() % 2 != 0) {
2825 Error("Invalid existing PendingInstantiations");
2826 return true;
2827 }
2828
2829 if (Record.size() % 2 != 0) {
2830 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2831 return true;
2832 }
2833
2834 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2835 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2836 PendingInstantiations.push_back(
2837 ReadSourceLocation(F, Record, I).getRawEncoding());
2838 }
2839 break;
2840
2841 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002842 if (Record.size() != 2) {
2843 Error("Invalid SEMA_DECL_REFS block");
2844 return true;
2845 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2847 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2848 break;
2849
2850 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002851 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2852 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2853 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002854
2855 unsigned LocalBasePreprocessedEntityID = Record[0];
2856
2857 unsigned StartingID;
2858 if (!PP.getPreprocessingRecord())
2859 PP.createPreprocessingRecord();
2860 if (!PP.getPreprocessingRecord()->getExternalSource())
2861 PP.getPreprocessingRecord()->SetExternalSource(*this);
2862 StartingID
2863 = PP.getPreprocessingRecord()
2864 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2865 F.BasePreprocessedEntityID = StartingID;
2866
2867 if (F.NumPreprocessedEntities > 0) {
2868 // Introduce the global -> local mapping for preprocessed entities in
2869 // this module.
2870 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2871
2872 // Introduce the local -> global mapping for preprocessed entities in
2873 // this module.
2874 F.PreprocessedEntityRemap.insertOrReplace(
2875 std::make_pair(LocalBasePreprocessedEntityID,
2876 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2877 }
2878
2879 break;
2880 }
2881
2882 case DECL_UPDATE_OFFSETS: {
2883 if (Record.size() % 2 != 0) {
2884 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2885 return true;
2886 }
2887 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2888 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2889 .push_back(std::make_pair(&F, Record[I+1]));
2890 break;
2891 }
2892
2893 case DECL_REPLACEMENTS: {
2894 if (Record.size() % 3 != 0) {
2895 Error("invalid DECL_REPLACEMENTS block in AST file");
2896 return true;
2897 }
2898 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2899 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2900 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2901 break;
2902 }
2903
2904 case OBJC_CATEGORIES_MAP: {
2905 if (F.LocalNumObjCCategoriesInMap != 0) {
2906 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2907 return true;
2908 }
2909
2910 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002911 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 break;
2913 }
2914
2915 case OBJC_CATEGORIES:
2916 F.ObjCCategories.swap(Record);
2917 break;
2918
2919 case CXX_BASE_SPECIFIER_OFFSETS: {
2920 if (F.LocalNumCXXBaseSpecifiers != 0) {
2921 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2922 return true;
2923 }
2924
2925 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002926 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2928 break;
2929 }
2930
2931 case DIAG_PRAGMA_MAPPINGS:
2932 if (F.PragmaDiagMappings.empty())
2933 F.PragmaDiagMappings.swap(Record);
2934 else
2935 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2936 Record.begin(), Record.end());
2937 break;
2938
2939 case CUDA_SPECIAL_DECL_REFS:
2940 // Later tables overwrite earlier ones.
2941 // FIXME: Modules will have trouble with this.
2942 CUDASpecialDeclRefs.clear();
2943 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2944 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2945 break;
2946
2947 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002948 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 if (Record[0]) {
2951 F.HeaderFileInfoTable
2952 = HeaderFileInfoLookupTable::Create(
2953 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2954 (const unsigned char *)F.HeaderFileInfoTableData,
2955 HeaderFileInfoTrait(*this, F,
2956 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002957 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002958
2959 PP.getHeaderSearchInfo().SetExternalSource(this);
2960 if (!PP.getHeaderSearchInfo().getExternalLookup())
2961 PP.getHeaderSearchInfo().SetExternalLookup(this);
2962 }
2963 break;
2964 }
2965
2966 case FP_PRAGMA_OPTIONS:
2967 // Later tables overwrite earlier ones.
2968 FPPragmaOptions.swap(Record);
2969 break;
2970
2971 case OPENCL_EXTENSIONS:
2972 // Later tables overwrite earlier ones.
2973 OpenCLExtensions.swap(Record);
2974 break;
2975
2976 case TENTATIVE_DEFINITIONS:
2977 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2978 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2979 break;
2980
2981 case KNOWN_NAMESPACES:
2982 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2983 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2984 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002985
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002986 case UNDEFINED_BUT_USED:
2987 if (UndefinedButUsed.size() % 2 != 0) {
2988 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002989 return true;
2990 }
2991
2992 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002993 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00002994 return true;
2995 }
2996 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002997 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2998 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00002999 ReadSourceLocation(F, Record, I).getRawEncoding());
3000 }
3001 break;
3002
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 case IMPORTED_MODULES: {
3004 if (F.Kind != MK_Module) {
3005 // If we aren't loading a module (which has its own exports), make
3006 // all of the imported modules visible.
3007 // FIXME: Deal with macros-only imports.
3008 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3009 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
3010 ImportedModules.push_back(GlobalID);
3011 }
3012 }
3013 break;
3014 }
3015
3016 case LOCAL_REDECLARATIONS: {
3017 F.RedeclarationChains.swap(Record);
3018 break;
3019 }
3020
3021 case LOCAL_REDECLARATIONS_MAP: {
3022 if (F.LocalNumRedeclarationsInMap != 0) {
3023 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3024 return true;
3025 }
3026
3027 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003028 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 break;
3030 }
3031
3032 case MERGED_DECLARATIONS: {
3033 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3034 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3035 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3036 for (unsigned N = Record[Idx++]; N > 0; --N)
3037 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3038 }
3039 break;
3040 }
3041
3042 case MACRO_OFFSET: {
3043 if (F.LocalNumMacros != 0) {
3044 Error("duplicate MACRO_OFFSET record in AST file");
3045 return true;
3046 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003047 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 F.LocalNumMacros = Record[0];
3049 unsigned LocalBaseMacroID = Record[1];
3050 F.BaseMacroID = getTotalNumMacros();
3051
3052 if (F.LocalNumMacros > 0) {
3053 // Introduce the global -> local mapping for macros within this module.
3054 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3055
3056 // Introduce the local -> global mapping for macros within this module.
3057 F.MacroRemap.insertOrReplace(
3058 std::make_pair(LocalBaseMacroID,
3059 F.BaseMacroID - LocalBaseMacroID));
3060
3061 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3062 }
3063 break;
3064 }
3065
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003066 case MACRO_TABLE: {
3067 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 break;
3069 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003070
3071 case LATE_PARSED_TEMPLATE: {
3072 LateParsedTemplates.append(Record.begin(), Record.end());
3073 break;
3074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 }
3076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003077}
3078
Douglas Gregorc1489562013-02-12 23:36:21 +00003079/// \brief Move the given method to the back of the global list of methods.
3080static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3081 // Find the entry for this selector in the method pool.
3082 Sema::GlobalMethodPool::iterator Known
3083 = S.MethodPool.find(Method->getSelector());
3084 if (Known == S.MethodPool.end())
3085 return;
3086
3087 // Retrieve the appropriate method list.
3088 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3089 : Known->second.second;
3090 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003091 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003092 if (!Found) {
3093 if (List->Method == Method) {
3094 Found = true;
3095 } else {
3096 // Keep searching.
3097 continue;
3098 }
3099 }
3100
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003101 if (List->getNext())
3102 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003103 else
3104 List->Method = Method;
3105 }
3106}
3107
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003108void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003109 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3110 Decl *D = Names.HiddenDecls[I];
3111 bool wasHidden = D->Hidden;
3112 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003113
Richard Smith49f906a2014-03-01 00:08:04 +00003114 if (wasHidden && SemaObj) {
3115 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3116 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 }
3119 }
Richard Smith49f906a2014-03-01 00:08:04 +00003120
3121 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3122 E = Names.HiddenMacros.end();
3123 I != E; ++I)
3124 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003125}
3126
Richard Smith49f906a2014-03-01 00:08:04 +00003127void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003128 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003129 SourceLocation ImportLoc,
3130 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003132 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003133 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003135 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003136
3137 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003138 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 // there is nothing more to do.
3140 continue;
3141 }
Richard Smith49f906a2014-03-01 00:08:04 +00003142
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 if (!Mod->isAvailable()) {
3144 // Modules that aren't available cannot be made visible.
3145 continue;
3146 }
3147
3148 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003149 if (NameVisibility >= Module::MacrosVisible &&
3150 Mod->NameVisibility < Module::MacrosVisible)
3151 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003153
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 // If we've already deserialized any names from this module,
3155 // mark them as visible.
3156 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3157 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003158 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 HiddenNamesMap.erase(Hidden);
3160 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003161
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003163 SmallVector<Module *, 16> Exports;
3164 Mod->getExportedModules(Exports);
3165 for (SmallVectorImpl<Module *>::iterator
3166 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3167 Module *Exported = *I;
3168 if (Visited.insert(Exported))
3169 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003171
3172 // Detect any conflicts.
3173 if (Complain) {
3174 assert(ImportLoc.isValid() && "Missing import location");
3175 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3176 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3177 Diag(ImportLoc, diag::warn_module_conflict)
3178 << Mod->getFullModuleName()
3179 << Mod->Conflicts[I].Other->getFullModuleName()
3180 << Mod->Conflicts[I].Message;
3181 // FIXME: Need note where the other module was imported.
3182 }
3183 }
3184 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 }
3186}
3187
Douglas Gregore060e572013-01-25 01:03:03 +00003188bool ASTReader::loadGlobalIndex() {
3189 if (GlobalIndex)
3190 return false;
3191
3192 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3193 !Context.getLangOpts().Modules)
3194 return true;
3195
3196 // Try to load the global index.
3197 TriedLoadingGlobalIndex = true;
3198 StringRef ModuleCachePath
3199 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3200 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003201 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003202 if (!Result.first)
3203 return true;
3204
3205 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003206 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003207 return false;
3208}
3209
3210bool ASTReader::isGlobalIndexUnavailable() const {
3211 return Context.getLangOpts().Modules && UseGlobalIndex &&
3212 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3213}
3214
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003215static void updateModuleTimestamp(ModuleFile &MF) {
3216 // Overwrite the timestamp file contents so that file's mtime changes.
3217 std::string TimestampFilename = MF.getTimestampFilename();
3218 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003219 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003220 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003221 if (!ErrorInfo.empty())
3222 return;
3223 OS << "Timestamp file\n";
3224}
3225
Guy Benyei11169dd2012-12-18 14:30:41 +00003226ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3227 ModuleKind Type,
3228 SourceLocation ImportLoc,
3229 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003230 llvm::SaveAndRestore<SourceLocation>
3231 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3232
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 // Bump the generation number.
3234 unsigned PreviousGeneration = CurrentGeneration++;
3235
3236 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003237 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3239 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003240 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 ClientLoadCapabilities)) {
3242 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003243 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003244 case OutOfDate:
3245 case VersionMismatch:
3246 case ConfigurationMismatch:
3247 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003248 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3249 Context.getLangOpts().Modules
3250 ? &PP.getHeaderSearchInfo().getModuleMap()
3251 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003252
3253 // If we find that any modules are unusable, the global index is going
3254 // to be out-of-date. Just remove it.
3255 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003256 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 return ReadResult;
3258
3259 case Success:
3260 break;
3261 }
3262
3263 // Here comes stuff that we only do once the entire chain is loaded.
3264
3265 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003266 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3267 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 M != MEnd; ++M) {
3269 ModuleFile &F = *M->Mod;
3270
3271 // Read the AST block.
3272 if (ReadASTBlock(F))
3273 return Failure;
3274
3275 // Once read, set the ModuleFile bit base offset and update the size in
3276 // bits of all files we've seen.
3277 F.GlobalBitOffset = TotalModulesSizeInBits;
3278 TotalModulesSizeInBits += F.SizeInBits;
3279 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3280
3281 // Preload SLocEntries.
3282 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3283 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3284 // Load it through the SourceManager and don't call ReadSLocEntry()
3285 // directly because the entry may have already been loaded in which case
3286 // calling ReadSLocEntry() directly would trigger an assertion in
3287 // SourceManager.
3288 SourceMgr.getLoadedSLocEntryByID(Index);
3289 }
3290 }
3291
Douglas Gregor603cd862013-03-22 18:50:14 +00003292 // Setup the import locations and notify the module manager that we've
3293 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003294 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3295 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 M != MEnd; ++M) {
3297 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003298
3299 ModuleMgr.moduleFileAccepted(&F);
3300
3301 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003302 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 if (!M->ImportedBy)
3304 F.ImportLoc = M->ImportLoc;
3305 else
3306 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3307 M->ImportLoc.getRawEncoding());
3308 }
3309
3310 // Mark all of the identifiers in the identifier table as being out of date,
3311 // so that various accessors know to check the loaded modules when the
3312 // identifier is used.
3313 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3314 IdEnd = PP.getIdentifierTable().end();
3315 Id != IdEnd; ++Id)
3316 Id->second->setOutOfDate(true);
3317
3318 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003319 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3320 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3322 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003323
3324 switch (Unresolved.Kind) {
3325 case UnresolvedModuleRef::Conflict:
3326 if (ResolvedMod) {
3327 Module::Conflict Conflict;
3328 Conflict.Other = ResolvedMod;
3329 Conflict.Message = Unresolved.String.str();
3330 Unresolved.Mod->Conflicts.push_back(Conflict);
3331 }
3332 continue;
3333
3334 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 if (ResolvedMod)
3336 Unresolved.Mod->Imports.push_back(ResolvedMod);
3337 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003338
Douglas Gregorfb912652013-03-20 21:10:35 +00003339 case UnresolvedModuleRef::Export:
3340 if (ResolvedMod || Unresolved.IsWildcard)
3341 Unresolved.Mod->Exports.push_back(
3342 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3343 continue;
3344 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003345 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003346 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003347
3348 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3349 // Might be unnecessary as use declarations are only used to build the
3350 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003351
3352 InitializeContext();
3353
Richard Smith3d8e97e2013-10-18 06:54:39 +00003354 if (SemaObj)
3355 UpdateSema();
3356
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 if (DeserializationListener)
3358 DeserializationListener->ReaderInitialized(this);
3359
3360 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3361 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3362 PrimaryModule.OriginalSourceFileID
3363 = FileID::get(PrimaryModule.SLocEntryBaseID
3364 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3365
3366 // If this AST file is a precompiled preamble, then set the
3367 // preamble file ID of the source manager to the file source file
3368 // from which the preamble was built.
3369 if (Type == MK_Preamble) {
3370 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3371 } else if (Type == MK_MainFile) {
3372 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3373 }
3374 }
3375
3376 // For any Objective-C class definitions we have already loaded, make sure
3377 // that we load any additional categories.
3378 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3379 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3380 ObjCClassesLoaded[I],
3381 PreviousGeneration);
3382 }
Douglas Gregore060e572013-01-25 01:03:03 +00003383
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003384 if (PP.getHeaderSearchInfo()
3385 .getHeaderSearchOpts()
3386 .ModulesValidateOncePerBuildSession) {
3387 // Now we are certain that the module and all modules it depends on are
3388 // up to date. Create or update timestamp files for modules that are
3389 // located in the module cache (not for PCH files that could be anywhere
3390 // in the filesystem).
3391 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3392 ImportedModule &M = Loaded[I];
3393 if (M.Mod->Kind == MK_Module) {
3394 updateModuleTimestamp(*M.Mod);
3395 }
3396 }
3397 }
3398
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 return Success;
3400}
3401
3402ASTReader::ASTReadResult
3403ASTReader::ReadASTCore(StringRef FileName,
3404 ModuleKind Type,
3405 SourceLocation ImportLoc,
3406 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003407 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003408 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 unsigned ClientLoadCapabilities) {
3410 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003412 ModuleManager::AddModuleResult AddResult
3413 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3414 CurrentGeneration, ExpectedSize, ExpectedModTime,
3415 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003416
Douglas Gregor7029ce12013-03-19 00:28:20 +00003417 switch (AddResult) {
3418 case ModuleManager::AlreadyLoaded:
3419 return Success;
3420
3421 case ModuleManager::NewlyLoaded:
3422 // Load module file below.
3423 break;
3424
3425 case ModuleManager::Missing:
3426 // The module file was missing; if the client handle handle, that, return
3427 // it.
3428 if (ClientLoadCapabilities & ARR_Missing)
3429 return Missing;
3430
3431 // Otherwise, return an error.
3432 {
3433 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3434 + ErrorStr;
3435 Error(Msg);
3436 }
3437 return Failure;
3438
3439 case ModuleManager::OutOfDate:
3440 // We couldn't load the module file because it is out-of-date. If the
3441 // client can handle out-of-date, return it.
3442 if (ClientLoadCapabilities & ARR_OutOfDate)
3443 return OutOfDate;
3444
3445 // Otherwise, return an error.
3446 {
3447 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3448 + ErrorStr;
3449 Error(Msg);
3450 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 return Failure;
3452 }
3453
Douglas Gregor7029ce12013-03-19 00:28:20 +00003454 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003455
3456 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3457 // module?
3458 if (FileName != "-") {
3459 CurrentDir = llvm::sys::path::parent_path(FileName);
3460 if (CurrentDir.empty()) CurrentDir = ".";
3461 }
3462
3463 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003464 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 Stream.init(F.StreamFile);
3466 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3467
3468 // Sniff for the signature.
3469 if (Stream.Read(8) != 'C' ||
3470 Stream.Read(8) != 'P' ||
3471 Stream.Read(8) != 'C' ||
3472 Stream.Read(8) != 'H') {
3473 Diag(diag::err_not_a_pch_file) << FileName;
3474 return Failure;
3475 }
3476
3477 // This is used for compatibility with older PCH formats.
3478 bool HaveReadControlBlock = false;
3479
Chris Lattnerefa77172013-01-20 00:00:22 +00003480 while (1) {
3481 llvm::BitstreamEntry Entry = Stream.advance();
3482
3483 switch (Entry.Kind) {
3484 case llvm::BitstreamEntry::Error:
3485 case llvm::BitstreamEntry::EndBlock:
3486 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 Error("invalid record at top-level of AST file");
3488 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003489
3490 case llvm::BitstreamEntry::SubBlock:
3491 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 }
3493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003495 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3497 if (Stream.ReadBlockInfoBlock()) {
3498 Error("malformed BlockInfoBlock in AST file");
3499 return Failure;
3500 }
3501 break;
3502 case CONTROL_BLOCK_ID:
3503 HaveReadControlBlock = true;
3504 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3505 case Success:
3506 break;
3507
3508 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003509 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 case OutOfDate: return OutOfDate;
3511 case VersionMismatch: return VersionMismatch;
3512 case ConfigurationMismatch: return ConfigurationMismatch;
3513 case HadErrors: return HadErrors;
3514 }
3515 break;
3516 case AST_BLOCK_ID:
3517 if (!HaveReadControlBlock) {
3518 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003519 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 return VersionMismatch;
3521 }
3522
3523 // Record that we've loaded this module.
3524 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3525 return Success;
3526
3527 default:
3528 if (Stream.SkipBlock()) {
3529 Error("malformed block record in AST file");
3530 return Failure;
3531 }
3532 break;
3533 }
3534 }
3535
3536 return Success;
3537}
3538
3539void ASTReader::InitializeContext() {
3540 // If there's a listener, notify them that we "read" the translation unit.
3541 if (DeserializationListener)
3542 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3543 Context.getTranslationUnitDecl());
3544
3545 // Make sure we load the declaration update records for the translation unit,
3546 // if there are any.
3547 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3548 Context.getTranslationUnitDecl());
3549
3550 // FIXME: Find a better way to deal with collisions between these
3551 // built-in types. Right now, we just ignore the problem.
3552
3553 // Load the special types.
3554 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3555 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3556 if (!Context.CFConstantStringTypeDecl)
3557 Context.setCFConstantStringType(GetType(String));
3558 }
3559
3560 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3561 QualType FileType = GetType(File);
3562 if (FileType.isNull()) {
3563 Error("FILE type is NULL");
3564 return;
3565 }
3566
3567 if (!Context.FILEDecl) {
3568 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3569 Context.setFILEDecl(Typedef->getDecl());
3570 else {
3571 const TagType *Tag = FileType->getAs<TagType>();
3572 if (!Tag) {
3573 Error("Invalid FILE type in AST file");
3574 return;
3575 }
3576 Context.setFILEDecl(Tag->getDecl());
3577 }
3578 }
3579 }
3580
3581 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3582 QualType Jmp_bufType = GetType(Jmp_buf);
3583 if (Jmp_bufType.isNull()) {
3584 Error("jmp_buf type is NULL");
3585 return;
3586 }
3587
3588 if (!Context.jmp_bufDecl) {
3589 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3590 Context.setjmp_bufDecl(Typedef->getDecl());
3591 else {
3592 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3593 if (!Tag) {
3594 Error("Invalid jmp_buf type in AST file");
3595 return;
3596 }
3597 Context.setjmp_bufDecl(Tag->getDecl());
3598 }
3599 }
3600 }
3601
3602 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3603 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3604 if (Sigjmp_bufType.isNull()) {
3605 Error("sigjmp_buf type is NULL");
3606 return;
3607 }
3608
3609 if (!Context.sigjmp_bufDecl) {
3610 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3611 Context.setsigjmp_bufDecl(Typedef->getDecl());
3612 else {
3613 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3614 assert(Tag && "Invalid sigjmp_buf type in AST file");
3615 Context.setsigjmp_bufDecl(Tag->getDecl());
3616 }
3617 }
3618 }
3619
3620 if (unsigned ObjCIdRedef
3621 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3622 if (Context.ObjCIdRedefinitionType.isNull())
3623 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3624 }
3625
3626 if (unsigned ObjCClassRedef
3627 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3628 if (Context.ObjCClassRedefinitionType.isNull())
3629 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3630 }
3631
3632 if (unsigned ObjCSelRedef
3633 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3634 if (Context.ObjCSelRedefinitionType.isNull())
3635 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3636 }
3637
3638 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3639 QualType Ucontext_tType = GetType(Ucontext_t);
3640 if (Ucontext_tType.isNull()) {
3641 Error("ucontext_t type is NULL");
3642 return;
3643 }
3644
3645 if (!Context.ucontext_tDecl) {
3646 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3647 Context.setucontext_tDecl(Typedef->getDecl());
3648 else {
3649 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3650 assert(Tag && "Invalid ucontext_t type in AST file");
3651 Context.setucontext_tDecl(Tag->getDecl());
3652 }
3653 }
3654 }
3655 }
3656
3657 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3658
3659 // If there were any CUDA special declarations, deserialize them.
3660 if (!CUDASpecialDeclRefs.empty()) {
3661 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3662 Context.setcudaConfigureCallDecl(
3663 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3664 }
3665
3666 // Re-export any modules that were imported by a non-module AST file.
3667 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3668 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003669 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003670 /*ImportLoc=*/SourceLocation(),
3671 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003672 }
3673 ImportedModules.clear();
3674}
3675
3676void ASTReader::finalizeForWriting() {
3677 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3678 HiddenEnd = HiddenNamesMap.end();
3679 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003680 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 }
3682 HiddenNamesMap.clear();
3683}
3684
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003685/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3686/// cursor into the start of the given block ID, returning false on success and
3687/// true on failure.
3688static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003689 while (1) {
3690 llvm::BitstreamEntry Entry = Cursor.advance();
3691 switch (Entry.Kind) {
3692 case llvm::BitstreamEntry::Error:
3693 case llvm::BitstreamEntry::EndBlock:
3694 return true;
3695
3696 case llvm::BitstreamEntry::Record:
3697 // Ignore top-level records.
3698 Cursor.skipRecord(Entry.ID);
3699 break;
3700
3701 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003702 if (Entry.ID == BlockID) {
3703 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003704 return true;
3705 // Found it!
3706 return false;
3707 }
3708
3709 if (Cursor.SkipBlock())
3710 return true;
3711 }
3712 }
3713}
3714
Guy Benyei11169dd2012-12-18 14:30:41 +00003715/// \brief Retrieve the name of the original source file name
3716/// directly from the AST file, without actually loading the AST
3717/// file.
3718std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3719 FileManager &FileMgr,
3720 DiagnosticsEngine &Diags) {
3721 // Open the AST file.
3722 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003723 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3725 if (!Buffer) {
3726 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3727 return std::string();
3728 }
3729
3730 // Initialize the stream
3731 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003732 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3734 (const unsigned char *)Buffer->getBufferEnd());
3735 Stream.init(StreamFile);
3736
3737 // Sniff for the signature.
3738 if (Stream.Read(8) != 'C' ||
3739 Stream.Read(8) != 'P' ||
3740 Stream.Read(8) != 'C' ||
3741 Stream.Read(8) != 'H') {
3742 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3743 return std::string();
3744 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003745
Chris Lattnere7b154b2013-01-19 21:39:22 +00003746 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003747 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003748 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3749 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003750 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003751
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003752 // Scan for ORIGINAL_FILE inside the control block.
3753 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003754 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003755 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003756 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3757 return std::string();
3758
3759 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3760 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3761 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003763
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003765 StringRef Blob;
3766 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3767 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003769}
3770
3771namespace {
3772 class SimplePCHValidator : public ASTReaderListener {
3773 const LangOptions &ExistingLangOpts;
3774 const TargetOptions &ExistingTargetOpts;
3775 const PreprocessorOptions &ExistingPPOpts;
3776 FileManager &FileMgr;
3777
3778 public:
3779 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3780 const TargetOptions &ExistingTargetOpts,
3781 const PreprocessorOptions &ExistingPPOpts,
3782 FileManager &FileMgr)
3783 : ExistingLangOpts(ExistingLangOpts),
3784 ExistingTargetOpts(ExistingTargetOpts),
3785 ExistingPPOpts(ExistingPPOpts),
3786 FileMgr(FileMgr)
3787 {
3788 }
3789
Craig Topper3e89dfe2014-03-13 02:13:41 +00003790 bool ReadLanguageOptions(const LangOptions &LangOpts,
3791 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3793 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003794 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3795 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003796 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3797 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003798 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3799 bool Complain,
3800 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003802 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 }
3804 };
3805}
3806
3807bool ASTReader::readASTFileControlBlock(StringRef Filename,
3808 FileManager &FileMgr,
3809 ASTReaderListener &Listener) {
3810 // Open the AST file.
3811 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003812 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003813 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3814 if (!Buffer) {
3815 return true;
3816 }
3817
3818 // Initialize the stream
3819 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003820 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003821 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3822 (const unsigned char *)Buffer->getBufferEnd());
3823 Stream.init(StreamFile);
3824
3825 // Sniff for the signature.
3826 if (Stream.Read(8) != 'C' ||
3827 Stream.Read(8) != 'P' ||
3828 Stream.Read(8) != 'C' ||
3829 Stream.Read(8) != 'H') {
3830 return true;
3831 }
3832
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003833 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003834 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003835 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003836
3837 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003838 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003839 BitstreamCursor InputFilesCursor;
3840 if (NeedsInputFiles) {
3841 InputFilesCursor = Stream;
3842 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3843 return true;
3844
3845 // Read the abbreviations
3846 while (true) {
3847 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3848 unsigned Code = InputFilesCursor.ReadCode();
3849
3850 // We expect all abbrevs to be at the start of the block.
3851 if (Code != llvm::bitc::DEFINE_ABBREV) {
3852 InputFilesCursor.JumpToBit(Offset);
3853 break;
3854 }
3855 InputFilesCursor.ReadAbbrevRecord();
3856 }
3857 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003858
3859 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003860 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003861 while (1) {
3862 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3863 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3864 return false;
3865
3866 if (Entry.Kind != llvm::BitstreamEntry::Record)
3867 return true;
3868
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003870 StringRef Blob;
3871 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003872 switch ((ControlRecordTypes)RecCode) {
3873 case METADATA: {
3874 if (Record[0] != VERSION_MAJOR)
3875 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003876
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003877 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003878 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003879
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003880 break;
3881 }
3882 case LANGUAGE_OPTIONS:
3883 if (ParseLanguageOptions(Record, false, Listener))
3884 return true;
3885 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003886
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003887 case TARGET_OPTIONS:
3888 if (ParseTargetOptions(Record, false, Listener))
3889 return true;
3890 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003891
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003892 case DIAGNOSTIC_OPTIONS:
3893 if (ParseDiagnosticOptions(Record, false, Listener))
3894 return true;
3895 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003896
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003897 case FILE_SYSTEM_OPTIONS:
3898 if (ParseFileSystemOptions(Record, false, Listener))
3899 return true;
3900 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003901
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003902 case HEADER_SEARCH_OPTIONS:
3903 if (ParseHeaderSearchOptions(Record, false, Listener))
3904 return true;
3905 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003906
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003907 case PREPROCESSOR_OPTIONS: {
3908 std::string IgnoredSuggestedPredefines;
3909 if (ParsePreprocessorOptions(Record, false, Listener,
3910 IgnoredSuggestedPredefines))
3911 return true;
3912 break;
3913 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003914
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003915 case INPUT_FILE_OFFSETS: {
3916 if (!NeedsInputFiles)
3917 break;
3918
3919 unsigned NumInputFiles = Record[0];
3920 unsigned NumUserFiles = Record[1];
3921 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3922 for (unsigned I = 0; I != NumInputFiles; ++I) {
3923 // Go find this input file.
3924 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00003925
3926 if (isSystemFile && !NeedsSystemInputFiles)
3927 break; // the rest are system input files
3928
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003929 BitstreamCursor &Cursor = InputFilesCursor;
3930 SavedStreamPosition SavedPosition(Cursor);
3931 Cursor.JumpToBit(InputFileOffs[I]);
3932
3933 unsigned Code = Cursor.ReadCode();
3934 RecordData Record;
3935 StringRef Blob;
3936 bool shouldContinue = false;
3937 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3938 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00003939 bool Overridden = static_cast<bool>(Record[3]);
3940 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003941 break;
3942 }
3943 if (!shouldContinue)
3944 break;
3945 }
3946 break;
3947 }
3948
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003949 default:
3950 // No other validation to perform.
3951 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003952 }
3953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003954}
3955
3956
3957bool ASTReader::isAcceptableASTFile(StringRef Filename,
3958 FileManager &FileMgr,
3959 const LangOptions &LangOpts,
3960 const TargetOptions &TargetOpts,
3961 const PreprocessorOptions &PPOpts) {
3962 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3963 return !readASTFileControlBlock(Filename, FileMgr, validator);
3964}
3965
3966bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3967 // Enter the submodule block.
3968 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3969 Error("malformed submodule block record in AST file");
3970 return true;
3971 }
3972
3973 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3974 bool First = true;
3975 Module *CurrentModule = 0;
3976 RecordData Record;
3977 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003978 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3979
3980 switch (Entry.Kind) {
3981 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3982 case llvm::BitstreamEntry::Error:
3983 Error("malformed block record in AST file");
3984 return true;
3985 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003987 case llvm::BitstreamEntry::Record:
3988 // The interesting case.
3989 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003991
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003993 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003995 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 default: // Default behavior: ignore.
3997 break;
3998
3999 case SUBMODULE_DEFINITION: {
4000 if (First) {
4001 Error("missing submodule metadata record at beginning of block");
4002 return true;
4003 }
4004
Douglas Gregor8d932422013-03-20 03:59:18 +00004005 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 Error("malformed module definition");
4007 return true;
4008 }
4009
Chris Lattner0e6c9402013-01-20 02:38:54 +00004010 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004011 unsigned Idx = 0;
4012 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4013 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4014 bool IsFramework = Record[Idx++];
4015 bool IsExplicit = Record[Idx++];
4016 bool IsSystem = Record[Idx++];
4017 bool IsExternC = Record[Idx++];
4018 bool InferSubmodules = Record[Idx++];
4019 bool InferExplicitSubmodules = Record[Idx++];
4020 bool InferExportWildcard = Record[Idx++];
4021 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004022
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 Module *ParentModule = 0;
4024 if (Parent)
4025 ParentModule = getSubmodule(Parent);
4026
4027 // Retrieve this (sub)module from the module map, creating it if
4028 // necessary.
4029 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4030 IsFramework,
4031 IsExplicit).first;
4032 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4033 if (GlobalIndex >= SubmodulesLoaded.size() ||
4034 SubmodulesLoaded[GlobalIndex]) {
4035 Error("too many submodules");
4036 return true;
4037 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004038
Douglas Gregor7029ce12013-03-19 00:28:20 +00004039 if (!ParentModule) {
4040 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4041 if (CurFile != F.File) {
4042 if (!Diags.isDiagnosticInFlight()) {
4043 Diag(diag::err_module_file_conflict)
4044 << CurrentModule->getTopLevelModuleName()
4045 << CurFile->getName()
4046 << F.File->getName();
4047 }
4048 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004049 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004050 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004051
4052 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004053 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004054
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 CurrentModule->IsFromModuleFile = true;
4056 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004057 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 CurrentModule->InferSubmodules = InferSubmodules;
4059 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4060 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004061 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 if (DeserializationListener)
4063 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4064
4065 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004066
Douglas Gregorfb912652013-03-20 21:10:35 +00004067 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004068 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004069 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004070 CurrentModule->UnresolvedConflicts.clear();
4071 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 break;
4073 }
4074
4075 case SUBMODULE_UMBRELLA_HEADER: {
4076 if (First) {
4077 Error("missing submodule metadata record at beginning of block");
4078 return true;
4079 }
4080
4081 if (!CurrentModule)
4082 break;
4083
Chris Lattner0e6c9402013-01-20 02:38:54 +00004084 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 if (!CurrentModule->getUmbrellaHeader())
4086 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4087 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4088 Error("mismatched umbrella headers in submodule");
4089 return true;
4090 }
4091 }
4092 break;
4093 }
4094
4095 case SUBMODULE_HEADER: {
4096 if (First) {
4097 Error("missing submodule metadata record at beginning of block");
4098 return true;
4099 }
4100
4101 if (!CurrentModule)
4102 break;
4103
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004104 // We lazily associate headers with their modules via the HeaderInfoTable.
4105 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4106 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004107 break;
4108 }
4109
4110 case SUBMODULE_EXCLUDED_HEADER: {
4111 if (First) {
4112 Error("missing submodule metadata record at beginning of block");
4113 return true;
4114 }
4115
4116 if (!CurrentModule)
4117 break;
4118
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004119 // We lazily associate headers with their modules via the HeaderInfoTable.
4120 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4121 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 break;
4123 }
4124
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004125 case SUBMODULE_PRIVATE_HEADER: {
4126 if (First) {
4127 Error("missing submodule metadata record at beginning of block");
4128 return true;
4129 }
4130
4131 if (!CurrentModule)
4132 break;
4133
4134 // We lazily associate headers with their modules via the HeaderInfoTable.
4135 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4136 // of complete filenames or remove it entirely.
4137 break;
4138 }
4139
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 case SUBMODULE_TOPHEADER: {
4141 if (First) {
4142 Error("missing submodule metadata record at beginning of block");
4143 return true;
4144 }
4145
4146 if (!CurrentModule)
4147 break;
4148
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004149 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 break;
4151 }
4152
4153 case SUBMODULE_UMBRELLA_DIR: {
4154 if (First) {
4155 Error("missing submodule metadata record at beginning of block");
4156 return true;
4157 }
4158
4159 if (!CurrentModule)
4160 break;
4161
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004163 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 if (!CurrentModule->getUmbrellaDir())
4165 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4166 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4167 Error("mismatched umbrella directories in submodule");
4168 return true;
4169 }
4170 }
4171 break;
4172 }
4173
4174 case SUBMODULE_METADATA: {
4175 if (!First) {
4176 Error("submodule metadata record not at beginning of block");
4177 return true;
4178 }
4179 First = false;
4180
4181 F.BaseSubmoduleID = getTotalNumSubmodules();
4182 F.LocalNumSubmodules = Record[0];
4183 unsigned LocalBaseSubmoduleID = Record[1];
4184 if (F.LocalNumSubmodules > 0) {
4185 // Introduce the global -> local mapping for submodules within this
4186 // module.
4187 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4188
4189 // Introduce the local -> global mapping for submodules within this
4190 // module.
4191 F.SubmoduleRemap.insertOrReplace(
4192 std::make_pair(LocalBaseSubmoduleID,
4193 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4194
4195 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4196 }
4197 break;
4198 }
4199
4200 case SUBMODULE_IMPORTS: {
4201 if (First) {
4202 Error("missing submodule metadata record at beginning of block");
4203 return true;
4204 }
4205
4206 if (!CurrentModule)
4207 break;
4208
4209 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004210 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 Unresolved.File = &F;
4212 Unresolved.Mod = CurrentModule;
4213 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004214 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004216 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 }
4218 break;
4219 }
4220
4221 case SUBMODULE_EXPORTS: {
4222 if (First) {
4223 Error("missing submodule metadata record at beginning of block");
4224 return true;
4225 }
4226
4227 if (!CurrentModule)
4228 break;
4229
4230 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004231 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 Unresolved.File = &F;
4233 Unresolved.Mod = CurrentModule;
4234 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004235 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004237 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 }
4239
4240 // Once we've loaded the set of exports, there's no reason to keep
4241 // the parsed, unresolved exports around.
4242 CurrentModule->UnresolvedExports.clear();
4243 break;
4244 }
4245 case SUBMODULE_REQUIRES: {
4246 if (First) {
4247 Error("missing submodule metadata record at beginning of block");
4248 return true;
4249 }
4250
4251 if (!CurrentModule)
4252 break;
4253
Richard Smitha3feee22013-10-28 22:18:19 +00004254 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 Context.getTargetInfo());
4256 break;
4257 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004258
4259 case SUBMODULE_LINK_LIBRARY:
4260 if (First) {
4261 Error("missing submodule metadata record at beginning of block");
4262 return true;
4263 }
4264
4265 if (!CurrentModule)
4266 break;
4267
4268 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004269 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004270 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004271
4272 case SUBMODULE_CONFIG_MACRO:
4273 if (First) {
4274 Error("missing submodule metadata record at beginning of block");
4275 return true;
4276 }
4277
4278 if (!CurrentModule)
4279 break;
4280
4281 CurrentModule->ConfigMacros.push_back(Blob.str());
4282 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004283
4284 case SUBMODULE_CONFLICT: {
4285 if (First) {
4286 Error("missing submodule metadata record at beginning of block");
4287 return true;
4288 }
4289
4290 if (!CurrentModule)
4291 break;
4292
4293 UnresolvedModuleRef Unresolved;
4294 Unresolved.File = &F;
4295 Unresolved.Mod = CurrentModule;
4296 Unresolved.ID = Record[0];
4297 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4298 Unresolved.IsWildcard = false;
4299 Unresolved.String = Blob;
4300 UnresolvedModuleRefs.push_back(Unresolved);
4301 break;
4302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 }
4304 }
4305}
4306
4307/// \brief Parse the record that corresponds to a LangOptions data
4308/// structure.
4309///
4310/// This routine parses the language options from the AST file and then gives
4311/// them to the AST listener if one is set.
4312///
4313/// \returns true if the listener deems the file unacceptable, false otherwise.
4314bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4315 bool Complain,
4316 ASTReaderListener &Listener) {
4317 LangOptions LangOpts;
4318 unsigned Idx = 0;
4319#define LANGOPT(Name, Bits, Default, Description) \
4320 LangOpts.Name = Record[Idx++];
4321#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4322 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4323#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004324#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4325#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004326
4327 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4328 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4329 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4330
4331 unsigned Length = Record[Idx++];
4332 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4333 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004334
4335 Idx += Length;
4336
4337 // Comment options.
4338 for (unsigned N = Record[Idx++]; N; --N) {
4339 LangOpts.CommentOpts.BlockCommandNames.push_back(
4340 ReadString(Record, Idx));
4341 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004342 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004343
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 return Listener.ReadLanguageOptions(LangOpts, Complain);
4345}
4346
4347bool ASTReader::ParseTargetOptions(const RecordData &Record,
4348 bool Complain,
4349 ASTReaderListener &Listener) {
4350 unsigned Idx = 0;
4351 TargetOptions TargetOpts;
4352 TargetOpts.Triple = ReadString(Record, Idx);
4353 TargetOpts.CPU = ReadString(Record, Idx);
4354 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4356 for (unsigned N = Record[Idx++]; N; --N) {
4357 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4358 }
4359 for (unsigned N = Record[Idx++]; N; --N) {
4360 TargetOpts.Features.push_back(ReadString(Record, Idx));
4361 }
4362
4363 return Listener.ReadTargetOptions(TargetOpts, Complain);
4364}
4365
4366bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4367 ASTReaderListener &Listener) {
4368 DiagnosticOptions DiagOpts;
4369 unsigned Idx = 0;
4370#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4371#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4372 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4373#include "clang/Basic/DiagnosticOptions.def"
4374
4375 for (unsigned N = Record[Idx++]; N; --N) {
4376 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4377 }
4378
4379 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4380}
4381
4382bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4383 ASTReaderListener &Listener) {
4384 FileSystemOptions FSOpts;
4385 unsigned Idx = 0;
4386 FSOpts.WorkingDir = ReadString(Record, Idx);
4387 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4388}
4389
4390bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4391 bool Complain,
4392 ASTReaderListener &Listener) {
4393 HeaderSearchOptions HSOpts;
4394 unsigned Idx = 0;
4395 HSOpts.Sysroot = ReadString(Record, Idx);
4396
4397 // Include entries.
4398 for (unsigned N = Record[Idx++]; N; --N) {
4399 std::string Path = ReadString(Record, Idx);
4400 frontend::IncludeDirGroup Group
4401 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 bool IsFramework = Record[Idx++];
4403 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004405 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 }
4407
4408 // System header prefixes.
4409 for (unsigned N = Record[Idx++]; N; --N) {
4410 std::string Prefix = ReadString(Record, Idx);
4411 bool IsSystemHeader = Record[Idx++];
4412 HSOpts.SystemHeaderPrefixes.push_back(
4413 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4414 }
4415
4416 HSOpts.ResourceDir = ReadString(Record, Idx);
4417 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004418 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 HSOpts.DisableModuleHash = Record[Idx++];
4420 HSOpts.UseBuiltinIncludes = Record[Idx++];
4421 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4422 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4423 HSOpts.UseLibcxx = Record[Idx++];
4424
4425 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4426}
4427
4428bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4429 bool Complain,
4430 ASTReaderListener &Listener,
4431 std::string &SuggestedPredefines) {
4432 PreprocessorOptions PPOpts;
4433 unsigned Idx = 0;
4434
4435 // Macro definitions/undefs
4436 for (unsigned N = Record[Idx++]; N; --N) {
4437 std::string Macro = ReadString(Record, Idx);
4438 bool IsUndef = Record[Idx++];
4439 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4440 }
4441
4442 // Includes
4443 for (unsigned N = Record[Idx++]; N; --N) {
4444 PPOpts.Includes.push_back(ReadString(Record, Idx));
4445 }
4446
4447 // Macro Includes
4448 for (unsigned N = Record[Idx++]; N; --N) {
4449 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4450 }
4451
4452 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004453 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4455 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4456 PPOpts.ObjCXXARCStandardLibrary =
4457 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4458 SuggestedPredefines.clear();
4459 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4460 SuggestedPredefines);
4461}
4462
4463std::pair<ModuleFile *, unsigned>
4464ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4465 GlobalPreprocessedEntityMapType::iterator
4466 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4467 assert(I != GlobalPreprocessedEntityMap.end() &&
4468 "Corrupted global preprocessed entity map");
4469 ModuleFile *M = I->second;
4470 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4471 return std::make_pair(M, LocalIndex);
4472}
4473
4474std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4475ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4476 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4477 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4478 Mod.NumPreprocessedEntities);
4479
4480 return std::make_pair(PreprocessingRecord::iterator(),
4481 PreprocessingRecord::iterator());
4482}
4483
4484std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4485ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4486 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4487 ModuleDeclIterator(this, &Mod,
4488 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4489}
4490
4491PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4492 PreprocessedEntityID PPID = Index+1;
4493 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4494 ModuleFile &M = *PPInfo.first;
4495 unsigned LocalIndex = PPInfo.second;
4496 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4497
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 if (!PP.getPreprocessingRecord()) {
4499 Error("no preprocessing record");
4500 return 0;
4501 }
4502
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004503 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4504 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4505
4506 llvm::BitstreamEntry Entry =
4507 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4508 if (Entry.Kind != llvm::BitstreamEntry::Record)
4509 return 0;
4510
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 // Read the record.
4512 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4513 ReadSourceLocation(M, PPOffs.End));
4514 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004515 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 RecordData Record;
4517 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004518 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4519 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 switch (RecType) {
4521 case PPD_MACRO_EXPANSION: {
4522 bool isBuiltin = Record[0];
4523 IdentifierInfo *Name = 0;
4524 MacroDefinition *Def = 0;
4525 if (isBuiltin)
4526 Name = getLocalIdentifier(M, Record[1]);
4527 else {
4528 PreprocessedEntityID
4529 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4530 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4531 }
4532
4533 MacroExpansion *ME;
4534 if (isBuiltin)
4535 ME = new (PPRec) MacroExpansion(Name, Range);
4536 else
4537 ME = new (PPRec) MacroExpansion(Def, Range);
4538
4539 return ME;
4540 }
4541
4542 case PPD_MACRO_DEFINITION: {
4543 // Decode the identifier info and then check again; if the macro is
4544 // still defined and associated with the identifier,
4545 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4546 MacroDefinition *MD
4547 = new (PPRec) MacroDefinition(II, Range);
4548
4549 if (DeserializationListener)
4550 DeserializationListener->MacroDefinitionRead(PPID, MD);
4551
4552 return MD;
4553 }
4554
4555 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004556 const char *FullFileNameStart = Blob.data() + Record[0];
4557 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 const FileEntry *File = 0;
4559 if (!FullFileName.empty())
4560 File = PP.getFileManager().getFile(FullFileName);
4561
4562 // FIXME: Stable encoding
4563 InclusionDirective::InclusionKind Kind
4564 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4565 InclusionDirective *ID
4566 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004567 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 Record[1], Record[3],
4569 File,
4570 Range);
4571 return ID;
4572 }
4573 }
4574
4575 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4576}
4577
4578/// \brief \arg SLocMapI points at a chunk of a module that contains no
4579/// preprocessed entities or the entities it contains are not the ones we are
4580/// looking for. Find the next module that contains entities and return the ID
4581/// of the first entry.
4582PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4583 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4584 ++SLocMapI;
4585 for (GlobalSLocOffsetMapType::const_iterator
4586 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4587 ModuleFile &M = *SLocMapI->second;
4588 if (M.NumPreprocessedEntities)
4589 return M.BasePreprocessedEntityID;
4590 }
4591
4592 return getTotalNumPreprocessedEntities();
4593}
4594
4595namespace {
4596
4597template <unsigned PPEntityOffset::*PPLoc>
4598struct PPEntityComp {
4599 const ASTReader &Reader;
4600 ModuleFile &M;
4601
4602 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4603
4604 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4605 SourceLocation LHS = getLoc(L);
4606 SourceLocation RHS = getLoc(R);
4607 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4608 }
4609
4610 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4611 SourceLocation LHS = getLoc(L);
4612 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4613 }
4614
4615 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4616 SourceLocation RHS = getLoc(R);
4617 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4618 }
4619
4620 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4621 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4622 }
4623};
4624
4625}
4626
4627/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4628PreprocessedEntityID
4629ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4630 if (SourceMgr.isLocalSourceLocation(BLoc))
4631 return getTotalNumPreprocessedEntities();
4632
4633 GlobalSLocOffsetMapType::const_iterator
4634 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004635 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4637 "Corrupted global sloc offset map");
4638
4639 if (SLocMapI->second->NumPreprocessedEntities == 0)
4640 return findNextPreprocessedEntity(SLocMapI);
4641
4642 ModuleFile &M = *SLocMapI->second;
4643 typedef const PPEntityOffset *pp_iterator;
4644 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4645 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4646
4647 size_t Count = M.NumPreprocessedEntities;
4648 size_t Half;
4649 pp_iterator First = pp_begin;
4650 pp_iterator PPI;
4651
4652 // Do a binary search manually instead of using std::lower_bound because
4653 // The end locations of entities may be unordered (when a macro expansion
4654 // is inside another macro argument), but for this case it is not important
4655 // whether we get the first macro expansion or its containing macro.
4656 while (Count > 0) {
4657 Half = Count/2;
4658 PPI = First;
4659 std::advance(PPI, Half);
4660 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4661 BLoc)){
4662 First = PPI;
4663 ++First;
4664 Count = Count - Half - 1;
4665 } else
4666 Count = Half;
4667 }
4668
4669 if (PPI == pp_end)
4670 return findNextPreprocessedEntity(SLocMapI);
4671
4672 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4673}
4674
4675/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4676PreprocessedEntityID
4677ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4678 if (SourceMgr.isLocalSourceLocation(ELoc))
4679 return getTotalNumPreprocessedEntities();
4680
4681 GlobalSLocOffsetMapType::const_iterator
4682 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004683 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4685 "Corrupted global sloc offset map");
4686
4687 if (SLocMapI->second->NumPreprocessedEntities == 0)
4688 return findNextPreprocessedEntity(SLocMapI);
4689
4690 ModuleFile &M = *SLocMapI->second;
4691 typedef const PPEntityOffset *pp_iterator;
4692 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4693 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4694 pp_iterator PPI =
4695 std::upper_bound(pp_begin, pp_end, ELoc,
4696 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4697
4698 if (PPI == pp_end)
4699 return findNextPreprocessedEntity(SLocMapI);
4700
4701 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4702}
4703
4704/// \brief Returns a pair of [Begin, End) indices of preallocated
4705/// preprocessed entities that \arg Range encompasses.
4706std::pair<unsigned, unsigned>
4707 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4708 if (Range.isInvalid())
4709 return std::make_pair(0,0);
4710 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4711
4712 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4713 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4714 return std::make_pair(BeginID, EndID);
4715}
4716
4717/// \brief Optionally returns true or false if the preallocated preprocessed
4718/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004719Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 FileID FID) {
4721 if (FID.isInvalid())
4722 return false;
4723
4724 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4725 ModuleFile &M = *PPInfo.first;
4726 unsigned LocalIndex = PPInfo.second;
4727 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4728
4729 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4730 if (Loc.isInvalid())
4731 return false;
4732
4733 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4734 return true;
4735 else
4736 return false;
4737}
4738
4739namespace {
4740 /// \brief Visitor used to search for information about a header file.
4741 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 const FileEntry *FE;
4743
David Blaikie05785d12013-02-20 22:23:23 +00004744 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004745
4746 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004747 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4748 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004749
4750 static bool visit(ModuleFile &M, void *UserData) {
4751 HeaderFileInfoVisitor *This
4752 = static_cast<HeaderFileInfoVisitor *>(UserData);
4753
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 HeaderFileInfoLookupTable *Table
4755 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4756 if (!Table)
4757 return false;
4758
4759 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004760 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 if (Pos == Table->end())
4762 return false;
4763
4764 This->HFI = *Pos;
4765 return true;
4766 }
4767
David Blaikie05785d12013-02-20 22:23:23 +00004768 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 };
4770}
4771
4772HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004773 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004775 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004777
4778 return HeaderFileInfo();
4779}
4780
4781void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4782 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004783 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4785 ModuleFile &F = *(*I);
4786 unsigned Idx = 0;
4787 DiagStates.clear();
4788 assert(!Diag.DiagStates.empty());
4789 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4790 while (Idx < F.PragmaDiagMappings.size()) {
4791 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4792 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4793 if (DiagStateID != 0) {
4794 Diag.DiagStatePoints.push_back(
4795 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4796 FullSourceLoc(Loc, SourceMgr)));
4797 continue;
4798 }
4799
4800 assert(DiagStateID == 0);
4801 // A new DiagState was created here.
4802 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4803 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4804 DiagStates.push_back(NewState);
4805 Diag.DiagStatePoints.push_back(
4806 DiagnosticsEngine::DiagStatePoint(NewState,
4807 FullSourceLoc(Loc, SourceMgr)));
4808 while (1) {
4809 assert(Idx < F.PragmaDiagMappings.size() &&
4810 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4811 if (Idx >= F.PragmaDiagMappings.size()) {
4812 break; // Something is messed up but at least avoid infinite loop in
4813 // release build.
4814 }
4815 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4816 if (DiagID == (unsigned)-1) {
4817 break; // no more diag/map pairs for this location.
4818 }
4819 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4820 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4821 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4822 }
4823 }
4824 }
4825}
4826
4827/// \brief Get the correct cursor and offset for loading a type.
4828ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4829 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4830 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4831 ModuleFile *M = I->second;
4832 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4833}
4834
4835/// \brief Read and return the type with the given index..
4836///
4837/// The index is the type ID, shifted and minus the number of predefs. This
4838/// routine actually reads the record corresponding to the type at the given
4839/// location. It is a helper routine for GetType, which deals with reading type
4840/// IDs.
4841QualType ASTReader::readTypeRecord(unsigned Index) {
4842 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004843 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004844
4845 // Keep track of where we are in the stream, then jump back there
4846 // after reading this type.
4847 SavedStreamPosition SavedPosition(DeclsCursor);
4848
4849 ReadingKindTracker ReadingKind(Read_Type, *this);
4850
4851 // Note that we are loading a type record.
4852 Deserializing AType(this);
4853
4854 unsigned Idx = 0;
4855 DeclsCursor.JumpToBit(Loc.Offset);
4856 RecordData Record;
4857 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004858 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 case TYPE_EXT_QUAL: {
4860 if (Record.size() != 2) {
4861 Error("Incorrect encoding of extended qualifier type");
4862 return QualType();
4863 }
4864 QualType Base = readType(*Loc.F, Record, Idx);
4865 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4866 return Context.getQualifiedType(Base, Quals);
4867 }
4868
4869 case TYPE_COMPLEX: {
4870 if (Record.size() != 1) {
4871 Error("Incorrect encoding of complex type");
4872 return QualType();
4873 }
4874 QualType ElemType = readType(*Loc.F, Record, Idx);
4875 return Context.getComplexType(ElemType);
4876 }
4877
4878 case TYPE_POINTER: {
4879 if (Record.size() != 1) {
4880 Error("Incorrect encoding of pointer type");
4881 return QualType();
4882 }
4883 QualType PointeeType = readType(*Loc.F, Record, Idx);
4884 return Context.getPointerType(PointeeType);
4885 }
4886
Reid Kleckner8a365022013-06-24 17:51:48 +00004887 case TYPE_DECAYED: {
4888 if (Record.size() != 1) {
4889 Error("Incorrect encoding of decayed type");
4890 return QualType();
4891 }
4892 QualType OriginalType = readType(*Loc.F, Record, Idx);
4893 QualType DT = Context.getAdjustedParameterType(OriginalType);
4894 if (!isa<DecayedType>(DT))
4895 Error("Decayed type does not decay");
4896 return DT;
4897 }
4898
Reid Kleckner0503a872013-12-05 01:23:43 +00004899 case TYPE_ADJUSTED: {
4900 if (Record.size() != 2) {
4901 Error("Incorrect encoding of adjusted type");
4902 return QualType();
4903 }
4904 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4905 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4906 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4907 }
4908
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 case TYPE_BLOCK_POINTER: {
4910 if (Record.size() != 1) {
4911 Error("Incorrect encoding of block pointer type");
4912 return QualType();
4913 }
4914 QualType PointeeType = readType(*Loc.F, Record, Idx);
4915 return Context.getBlockPointerType(PointeeType);
4916 }
4917
4918 case TYPE_LVALUE_REFERENCE: {
4919 if (Record.size() != 2) {
4920 Error("Incorrect encoding of lvalue reference type");
4921 return QualType();
4922 }
4923 QualType PointeeType = readType(*Loc.F, Record, Idx);
4924 return Context.getLValueReferenceType(PointeeType, Record[1]);
4925 }
4926
4927 case TYPE_RVALUE_REFERENCE: {
4928 if (Record.size() != 1) {
4929 Error("Incorrect encoding of rvalue reference type");
4930 return QualType();
4931 }
4932 QualType PointeeType = readType(*Loc.F, Record, Idx);
4933 return Context.getRValueReferenceType(PointeeType);
4934 }
4935
4936 case TYPE_MEMBER_POINTER: {
4937 if (Record.size() != 2) {
4938 Error("Incorrect encoding of member pointer type");
4939 return QualType();
4940 }
4941 QualType PointeeType = readType(*Loc.F, Record, Idx);
4942 QualType ClassType = readType(*Loc.F, Record, Idx);
4943 if (PointeeType.isNull() || ClassType.isNull())
4944 return QualType();
4945
4946 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4947 }
4948
4949 case TYPE_CONSTANT_ARRAY: {
4950 QualType ElementType = readType(*Loc.F, Record, Idx);
4951 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4952 unsigned IndexTypeQuals = Record[2];
4953 unsigned Idx = 3;
4954 llvm::APInt Size = ReadAPInt(Record, Idx);
4955 return Context.getConstantArrayType(ElementType, Size,
4956 ASM, IndexTypeQuals);
4957 }
4958
4959 case TYPE_INCOMPLETE_ARRAY: {
4960 QualType ElementType = readType(*Loc.F, Record, Idx);
4961 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4962 unsigned IndexTypeQuals = Record[2];
4963 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4964 }
4965
4966 case TYPE_VARIABLE_ARRAY: {
4967 QualType ElementType = readType(*Loc.F, Record, Idx);
4968 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4969 unsigned IndexTypeQuals = Record[2];
4970 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4971 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4972 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4973 ASM, IndexTypeQuals,
4974 SourceRange(LBLoc, RBLoc));
4975 }
4976
4977 case TYPE_VECTOR: {
4978 if (Record.size() != 3) {
4979 Error("incorrect encoding of vector type in AST file");
4980 return QualType();
4981 }
4982
4983 QualType ElementType = readType(*Loc.F, Record, Idx);
4984 unsigned NumElements = Record[1];
4985 unsigned VecKind = Record[2];
4986 return Context.getVectorType(ElementType, NumElements,
4987 (VectorType::VectorKind)VecKind);
4988 }
4989
4990 case TYPE_EXT_VECTOR: {
4991 if (Record.size() != 3) {
4992 Error("incorrect encoding of extended vector type in AST file");
4993 return QualType();
4994 }
4995
4996 QualType ElementType = readType(*Loc.F, Record, Idx);
4997 unsigned NumElements = Record[1];
4998 return Context.getExtVectorType(ElementType, NumElements);
4999 }
5000
5001 case TYPE_FUNCTION_NO_PROTO: {
5002 if (Record.size() != 6) {
5003 Error("incorrect encoding of no-proto function type");
5004 return QualType();
5005 }
5006 QualType ResultType = readType(*Loc.F, Record, Idx);
5007 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5008 (CallingConv)Record[4], Record[5]);
5009 return Context.getFunctionNoProtoType(ResultType, Info);
5010 }
5011
5012 case TYPE_FUNCTION_PROTO: {
5013 QualType ResultType = readType(*Loc.F, Record, Idx);
5014
5015 FunctionProtoType::ExtProtoInfo EPI;
5016 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5017 /*hasregparm*/ Record[2],
5018 /*regparm*/ Record[3],
5019 static_cast<CallingConv>(Record[4]),
5020 /*produces*/ Record[5]);
5021
5022 unsigned Idx = 6;
5023 unsigned NumParams = Record[Idx++];
5024 SmallVector<QualType, 16> ParamTypes;
5025 for (unsigned I = 0; I != NumParams; ++I)
5026 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5027
5028 EPI.Variadic = Record[Idx++];
5029 EPI.HasTrailingReturn = Record[Idx++];
5030 EPI.TypeQuals = Record[Idx++];
5031 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5032 ExceptionSpecificationType EST =
5033 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5034 EPI.ExceptionSpecType = EST;
5035 SmallVector<QualType, 2> Exceptions;
5036 if (EST == EST_Dynamic) {
5037 EPI.NumExceptions = Record[Idx++];
5038 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5039 Exceptions.push_back(readType(*Loc.F, Record, Idx));
5040 EPI.Exceptions = Exceptions.data();
5041 } else if (EST == EST_ComputedNoexcept) {
5042 EPI.NoexceptExpr = ReadExpr(*Loc.F);
5043 } else if (EST == EST_Uninstantiated) {
5044 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5045 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5046 } else if (EST == EST_Unevaluated) {
5047 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5048 }
Jordan Rose5c382722013-03-08 21:51:21 +00005049 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 }
5051
5052 case TYPE_UNRESOLVED_USING: {
5053 unsigned Idx = 0;
5054 return Context.getTypeDeclType(
5055 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5056 }
5057
5058 case TYPE_TYPEDEF: {
5059 if (Record.size() != 2) {
5060 Error("incorrect encoding of typedef type");
5061 return QualType();
5062 }
5063 unsigned Idx = 0;
5064 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5065 QualType Canonical = readType(*Loc.F, Record, Idx);
5066 if (!Canonical.isNull())
5067 Canonical = Context.getCanonicalType(Canonical);
5068 return Context.getTypedefType(Decl, Canonical);
5069 }
5070
5071 case TYPE_TYPEOF_EXPR:
5072 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5073
5074 case TYPE_TYPEOF: {
5075 if (Record.size() != 1) {
5076 Error("incorrect encoding of typeof(type) in AST file");
5077 return QualType();
5078 }
5079 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5080 return Context.getTypeOfType(UnderlyingType);
5081 }
5082
5083 case TYPE_DECLTYPE: {
5084 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5085 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5086 }
5087
5088 case TYPE_UNARY_TRANSFORM: {
5089 QualType BaseType = readType(*Loc.F, Record, Idx);
5090 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5091 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5092 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5093 }
5094
Richard Smith74aeef52013-04-26 16:15:35 +00005095 case TYPE_AUTO: {
5096 QualType Deduced = readType(*Loc.F, Record, Idx);
5097 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005098 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005099 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005100 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005101
5102 case TYPE_RECORD: {
5103 if (Record.size() != 2) {
5104 Error("incorrect encoding of record type");
5105 return QualType();
5106 }
5107 unsigned Idx = 0;
5108 bool IsDependent = Record[Idx++];
5109 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5110 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5111 QualType T = Context.getRecordType(RD);
5112 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5113 return T;
5114 }
5115
5116 case TYPE_ENUM: {
5117 if (Record.size() != 2) {
5118 Error("incorrect encoding of enum type");
5119 return QualType();
5120 }
5121 unsigned Idx = 0;
5122 bool IsDependent = Record[Idx++];
5123 QualType T
5124 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5125 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5126 return T;
5127 }
5128
5129 case TYPE_ATTRIBUTED: {
5130 if (Record.size() != 3) {
5131 Error("incorrect encoding of attributed type");
5132 return QualType();
5133 }
5134 QualType modifiedType = readType(*Loc.F, Record, Idx);
5135 QualType equivalentType = readType(*Loc.F, Record, Idx);
5136 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5137 return Context.getAttributedType(kind, modifiedType, equivalentType);
5138 }
5139
5140 case TYPE_PAREN: {
5141 if (Record.size() != 1) {
5142 Error("incorrect encoding of paren type");
5143 return QualType();
5144 }
5145 QualType InnerType = readType(*Loc.F, Record, Idx);
5146 return Context.getParenType(InnerType);
5147 }
5148
5149 case TYPE_PACK_EXPANSION: {
5150 if (Record.size() != 2) {
5151 Error("incorrect encoding of pack expansion type");
5152 return QualType();
5153 }
5154 QualType Pattern = readType(*Loc.F, Record, Idx);
5155 if (Pattern.isNull())
5156 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005157 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 if (Record[1])
5159 NumExpansions = Record[1] - 1;
5160 return Context.getPackExpansionType(Pattern, NumExpansions);
5161 }
5162
5163 case TYPE_ELABORATED: {
5164 unsigned Idx = 0;
5165 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5166 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5167 QualType NamedType = readType(*Loc.F, Record, Idx);
5168 return Context.getElaboratedType(Keyword, NNS, NamedType);
5169 }
5170
5171 case TYPE_OBJC_INTERFACE: {
5172 unsigned Idx = 0;
5173 ObjCInterfaceDecl *ItfD
5174 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5175 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5176 }
5177
5178 case TYPE_OBJC_OBJECT: {
5179 unsigned Idx = 0;
5180 QualType Base = readType(*Loc.F, Record, Idx);
5181 unsigned NumProtos = Record[Idx++];
5182 SmallVector<ObjCProtocolDecl*, 4> Protos;
5183 for (unsigned I = 0; I != NumProtos; ++I)
5184 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5185 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5186 }
5187
5188 case TYPE_OBJC_OBJECT_POINTER: {
5189 unsigned Idx = 0;
5190 QualType Pointee = readType(*Loc.F, Record, Idx);
5191 return Context.getObjCObjectPointerType(Pointee);
5192 }
5193
5194 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5195 unsigned Idx = 0;
5196 QualType Parm = readType(*Loc.F, Record, Idx);
5197 QualType Replacement = readType(*Loc.F, Record, Idx);
5198 return
5199 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
5200 Replacement);
5201 }
5202
5203 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5204 unsigned Idx = 0;
5205 QualType Parm = readType(*Loc.F, Record, Idx);
5206 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5207 return Context.getSubstTemplateTypeParmPackType(
5208 cast<TemplateTypeParmType>(Parm),
5209 ArgPack);
5210 }
5211
5212 case TYPE_INJECTED_CLASS_NAME: {
5213 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5214 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5215 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5216 // for AST reading, too much interdependencies.
5217 return
5218 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5219 }
5220
5221 case TYPE_TEMPLATE_TYPE_PARM: {
5222 unsigned Idx = 0;
5223 unsigned Depth = Record[Idx++];
5224 unsigned Index = Record[Idx++];
5225 bool Pack = Record[Idx++];
5226 TemplateTypeParmDecl *D
5227 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5228 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5229 }
5230
5231 case TYPE_DEPENDENT_NAME: {
5232 unsigned Idx = 0;
5233 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5234 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5235 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5236 QualType Canon = readType(*Loc.F, Record, Idx);
5237 if (!Canon.isNull())
5238 Canon = Context.getCanonicalType(Canon);
5239 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5240 }
5241
5242 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5243 unsigned Idx = 0;
5244 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5245 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5246 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5247 unsigned NumArgs = Record[Idx++];
5248 SmallVector<TemplateArgument, 8> Args;
5249 Args.reserve(NumArgs);
5250 while (NumArgs--)
5251 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5252 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5253 Args.size(), Args.data());
5254 }
5255
5256 case TYPE_DEPENDENT_SIZED_ARRAY: {
5257 unsigned Idx = 0;
5258
5259 // ArrayType
5260 QualType ElementType = readType(*Loc.F, Record, Idx);
5261 ArrayType::ArraySizeModifier ASM
5262 = (ArrayType::ArraySizeModifier)Record[Idx++];
5263 unsigned IndexTypeQuals = Record[Idx++];
5264
5265 // DependentSizedArrayType
5266 Expr *NumElts = ReadExpr(*Loc.F);
5267 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5268
5269 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5270 IndexTypeQuals, Brackets);
5271 }
5272
5273 case TYPE_TEMPLATE_SPECIALIZATION: {
5274 unsigned Idx = 0;
5275 bool IsDependent = Record[Idx++];
5276 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5277 SmallVector<TemplateArgument, 8> Args;
5278 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5279 QualType Underlying = readType(*Loc.F, Record, Idx);
5280 QualType T;
5281 if (Underlying.isNull())
5282 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5283 Args.size());
5284 else
5285 T = Context.getTemplateSpecializationType(Name, Args.data(),
5286 Args.size(), Underlying);
5287 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5288 return T;
5289 }
5290
5291 case TYPE_ATOMIC: {
5292 if (Record.size() != 1) {
5293 Error("Incorrect encoding of atomic type");
5294 return QualType();
5295 }
5296 QualType ValueType = readType(*Loc.F, Record, Idx);
5297 return Context.getAtomicType(ValueType);
5298 }
5299 }
5300 llvm_unreachable("Invalid TypeCode!");
5301}
5302
5303class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5304 ASTReader &Reader;
5305 ModuleFile &F;
5306 const ASTReader::RecordData &Record;
5307 unsigned &Idx;
5308
5309 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5310 unsigned &I) {
5311 return Reader.ReadSourceLocation(F, R, I);
5312 }
5313
5314 template<typename T>
5315 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5316 return Reader.ReadDeclAs<T>(F, Record, Idx);
5317 }
5318
5319public:
5320 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5321 const ASTReader::RecordData &Record, unsigned &Idx)
5322 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5323 { }
5324
5325 // We want compile-time assurance that we've enumerated all of
5326 // these, so unfortunately we have to declare them first, then
5327 // define them out-of-line.
5328#define ABSTRACT_TYPELOC(CLASS, PARENT)
5329#define TYPELOC(CLASS, PARENT) \
5330 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5331#include "clang/AST/TypeLocNodes.def"
5332
5333 void VisitFunctionTypeLoc(FunctionTypeLoc);
5334 void VisitArrayTypeLoc(ArrayTypeLoc);
5335};
5336
5337void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5338 // nothing to do
5339}
5340void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5341 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5342 if (TL.needsExtraLocalData()) {
5343 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5344 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5345 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5346 TL.setModeAttr(Record[Idx++]);
5347 }
5348}
5349void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5350 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5351}
5352void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5353 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5354}
Reid Kleckner8a365022013-06-24 17:51:48 +00005355void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5356 // nothing to do
5357}
Reid Kleckner0503a872013-12-05 01:23:43 +00005358void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5359 // nothing to do
5360}
Guy Benyei11169dd2012-12-18 14:30:41 +00005361void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5362 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5363}
5364void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5365 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5366}
5367void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5368 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5369}
5370void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5371 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5372 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5373}
5374void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5375 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5376 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5377 if (Record[Idx++])
5378 TL.setSizeExpr(Reader.ReadExpr(F));
5379 else
5380 TL.setSizeExpr(0);
5381}
5382void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5383 VisitArrayTypeLoc(TL);
5384}
5385void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5386 VisitArrayTypeLoc(TL);
5387}
5388void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5389 VisitArrayTypeLoc(TL);
5390}
5391void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5392 DependentSizedArrayTypeLoc TL) {
5393 VisitArrayTypeLoc(TL);
5394}
5395void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5396 DependentSizedExtVectorTypeLoc TL) {
5397 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5398}
5399void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5400 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5401}
5402void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5403 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5404}
5405void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5406 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5407 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5408 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5409 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005410 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5411 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 }
5413}
5414void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5415 VisitFunctionTypeLoc(TL);
5416}
5417void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5418 VisitFunctionTypeLoc(TL);
5419}
5420void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5421 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5422}
5423void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5424 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5425}
5426void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5427 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5428 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5429 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5430}
5431void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5432 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5433 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5434 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5435 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5436}
5437void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5438 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5439}
5440void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5441 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5442 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5443 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5444 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5445}
5446void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5447 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5448}
5449void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5450 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5451}
5452void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5453 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5454}
5455void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5456 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5457 if (TL.hasAttrOperand()) {
5458 SourceRange range;
5459 range.setBegin(ReadSourceLocation(Record, Idx));
5460 range.setEnd(ReadSourceLocation(Record, Idx));
5461 TL.setAttrOperandParensRange(range);
5462 }
5463 if (TL.hasAttrExprOperand()) {
5464 if (Record[Idx++])
5465 TL.setAttrExprOperand(Reader.ReadExpr(F));
5466 else
5467 TL.setAttrExprOperand(0);
5468 } else if (TL.hasAttrEnumOperand())
5469 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5470}
5471void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5472 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5473}
5474void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5475 SubstTemplateTypeParmTypeLoc TL) {
5476 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5477}
5478void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5479 SubstTemplateTypeParmPackTypeLoc TL) {
5480 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5481}
5482void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5483 TemplateSpecializationTypeLoc TL) {
5484 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5485 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5486 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5487 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5488 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5489 TL.setArgLocInfo(i,
5490 Reader.GetTemplateArgumentLocInfo(F,
5491 TL.getTypePtr()->getArg(i).getKind(),
5492 Record, Idx));
5493}
5494void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5495 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5496 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5497}
5498void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5499 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5500 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5501}
5502void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5503 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5504}
5505void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5506 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5507 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5508 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5509}
5510void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5511 DependentTemplateSpecializationTypeLoc TL) {
5512 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5513 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5514 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5515 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5516 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5517 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5518 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5519 TL.setArgLocInfo(I,
5520 Reader.GetTemplateArgumentLocInfo(F,
5521 TL.getTypePtr()->getArg(I).getKind(),
5522 Record, Idx));
5523}
5524void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5525 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5526}
5527void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5528 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5529}
5530void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5531 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5532 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5533 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5534 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5535 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5536}
5537void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5538 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5539}
5540void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5541 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5542 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5543 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5544}
5545
5546TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5547 const RecordData &Record,
5548 unsigned &Idx) {
5549 QualType InfoTy = readType(F, Record, Idx);
5550 if (InfoTy.isNull())
5551 return 0;
5552
5553 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5554 TypeLocReader TLR(*this, F, Record, Idx);
5555 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5556 TLR.Visit(TL);
5557 return TInfo;
5558}
5559
5560QualType ASTReader::GetType(TypeID ID) {
5561 unsigned FastQuals = ID & Qualifiers::FastMask;
5562 unsigned Index = ID >> Qualifiers::FastWidth;
5563
5564 if (Index < NUM_PREDEF_TYPE_IDS) {
5565 QualType T;
5566 switch ((PredefinedTypeIDs)Index) {
5567 case PREDEF_TYPE_NULL_ID: return QualType();
5568 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5569 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5570
5571 case PREDEF_TYPE_CHAR_U_ID:
5572 case PREDEF_TYPE_CHAR_S_ID:
5573 // FIXME: Check that the signedness of CharTy is correct!
5574 T = Context.CharTy;
5575 break;
5576
5577 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5578 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5579 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5580 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5581 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5582 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5583 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5584 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5585 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5586 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5587 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5588 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5589 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5590 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5591 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5592 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5593 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5594 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5595 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5596 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5597 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5598 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5599 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5600 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5601 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5602 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5603 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5604 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005605 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5606 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5607 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5608 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5609 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5610 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005611 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005612 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005613 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5614
5615 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5616 T = Context.getAutoRRefDeductType();
5617 break;
5618
5619 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5620 T = Context.ARCUnbridgedCastTy;
5621 break;
5622
5623 case PREDEF_TYPE_VA_LIST_TAG:
5624 T = Context.getVaListTagType();
5625 break;
5626
5627 case PREDEF_TYPE_BUILTIN_FN:
5628 T = Context.BuiltinFnTy;
5629 break;
5630 }
5631
5632 assert(!T.isNull() && "Unknown predefined type");
5633 return T.withFastQualifiers(FastQuals);
5634 }
5635
5636 Index -= NUM_PREDEF_TYPE_IDS;
5637 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5638 if (TypesLoaded[Index].isNull()) {
5639 TypesLoaded[Index] = readTypeRecord(Index);
5640 if (TypesLoaded[Index].isNull())
5641 return QualType();
5642
5643 TypesLoaded[Index]->setFromAST();
5644 if (DeserializationListener)
5645 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5646 TypesLoaded[Index]);
5647 }
5648
5649 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5650}
5651
5652QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5653 return GetType(getGlobalTypeID(F, LocalID));
5654}
5655
5656serialization::TypeID
5657ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5658 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5659 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5660
5661 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5662 return LocalID;
5663
5664 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5665 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5666 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5667
5668 unsigned GlobalIndex = LocalIndex + I->second;
5669 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5670}
5671
5672TemplateArgumentLocInfo
5673ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5674 TemplateArgument::ArgKind Kind,
5675 const RecordData &Record,
5676 unsigned &Index) {
5677 switch (Kind) {
5678 case TemplateArgument::Expression:
5679 return ReadExpr(F);
5680 case TemplateArgument::Type:
5681 return GetTypeSourceInfo(F, Record, Index);
5682 case TemplateArgument::Template: {
5683 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5684 Index);
5685 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5686 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5687 SourceLocation());
5688 }
5689 case TemplateArgument::TemplateExpansion: {
5690 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5691 Index);
5692 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5693 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5694 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5695 EllipsisLoc);
5696 }
5697 case TemplateArgument::Null:
5698 case TemplateArgument::Integral:
5699 case TemplateArgument::Declaration:
5700 case TemplateArgument::NullPtr:
5701 case TemplateArgument::Pack:
5702 // FIXME: Is this right?
5703 return TemplateArgumentLocInfo();
5704 }
5705 llvm_unreachable("unexpected template argument loc");
5706}
5707
5708TemplateArgumentLoc
5709ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5710 const RecordData &Record, unsigned &Index) {
5711 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5712
5713 if (Arg.getKind() == TemplateArgument::Expression) {
5714 if (Record[Index++]) // bool InfoHasSameExpr.
5715 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5716 }
5717 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5718 Record, Index));
5719}
5720
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005721const ASTTemplateArgumentListInfo*
5722ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5723 const RecordData &Record,
5724 unsigned &Index) {
5725 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5726 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5727 unsigned NumArgsAsWritten = Record[Index++];
5728 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5729 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5730 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5731 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5732}
5733
Guy Benyei11169dd2012-12-18 14:30:41 +00005734Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5735 return GetDecl(ID);
5736}
5737
5738uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5739 unsigned &Idx){
5740 if (Idx >= Record.size())
5741 return 0;
5742
5743 unsigned LocalID = Record[Idx++];
5744 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5745}
5746
5747CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5748 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005749 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005750 SavedStreamPosition SavedPosition(Cursor);
5751 Cursor.JumpToBit(Loc.Offset);
5752 ReadingKindTracker ReadingKind(Read_Decl, *this);
5753 RecordData Record;
5754 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005755 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005756 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5757 Error("Malformed AST file: missing C++ base specifiers");
5758 return 0;
5759 }
5760
5761 unsigned Idx = 0;
5762 unsigned NumBases = Record[Idx++];
5763 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5764 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5765 for (unsigned I = 0; I != NumBases; ++I)
5766 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5767 return Bases;
5768}
5769
5770serialization::DeclID
5771ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5772 if (LocalID < NUM_PREDEF_DECL_IDS)
5773 return LocalID;
5774
5775 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5776 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5777 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5778
5779 return LocalID + I->second;
5780}
5781
5782bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5783 ModuleFile &M) const {
5784 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5785 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5786 return &M == I->second;
5787}
5788
Douglas Gregor9f782892013-01-21 15:25:38 +00005789ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005790 if (!D->isFromASTFile())
5791 return 0;
5792 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5793 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5794 return I->second;
5795}
5796
5797SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5798 if (ID < NUM_PREDEF_DECL_IDS)
5799 return SourceLocation();
5800
5801 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5802
5803 if (Index > DeclsLoaded.size()) {
5804 Error("declaration ID out-of-range for AST file");
5805 return SourceLocation();
5806 }
5807
5808 if (Decl *D = DeclsLoaded[Index])
5809 return D->getLocation();
5810
5811 unsigned RawLocation = 0;
5812 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5813 return ReadSourceLocation(*Rec.F, RawLocation);
5814}
5815
5816Decl *ASTReader::GetDecl(DeclID ID) {
5817 if (ID < NUM_PREDEF_DECL_IDS) {
5818 switch ((PredefinedDeclIDs)ID) {
5819 case PREDEF_DECL_NULL_ID:
5820 return 0;
5821
5822 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5823 return Context.getTranslationUnitDecl();
5824
5825 case PREDEF_DECL_OBJC_ID_ID:
5826 return Context.getObjCIdDecl();
5827
5828 case PREDEF_DECL_OBJC_SEL_ID:
5829 return Context.getObjCSelDecl();
5830
5831 case PREDEF_DECL_OBJC_CLASS_ID:
5832 return Context.getObjCClassDecl();
5833
5834 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5835 return Context.getObjCProtocolDecl();
5836
5837 case PREDEF_DECL_INT_128_ID:
5838 return Context.getInt128Decl();
5839
5840 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5841 return Context.getUInt128Decl();
5842
5843 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5844 return Context.getObjCInstanceTypeDecl();
5845
5846 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5847 return Context.getBuiltinVaListDecl();
5848 }
5849 }
5850
5851 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5852
5853 if (Index >= DeclsLoaded.size()) {
5854 assert(0 && "declaration ID out-of-range for AST file");
5855 Error("declaration ID out-of-range for AST file");
5856 return 0;
5857 }
5858
5859 if (!DeclsLoaded[Index]) {
5860 ReadDeclRecord(ID);
5861 if (DeserializationListener)
5862 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5863 }
5864
5865 return DeclsLoaded[Index];
5866}
5867
5868DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5869 DeclID GlobalID) {
5870 if (GlobalID < NUM_PREDEF_DECL_IDS)
5871 return GlobalID;
5872
5873 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5874 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5875 ModuleFile *Owner = I->second;
5876
5877 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5878 = M.GlobalToLocalDeclIDs.find(Owner);
5879 if (Pos == M.GlobalToLocalDeclIDs.end())
5880 return 0;
5881
5882 return GlobalID - Owner->BaseDeclID + Pos->second;
5883}
5884
5885serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5886 const RecordData &Record,
5887 unsigned &Idx) {
5888 if (Idx >= Record.size()) {
5889 Error("Corrupted AST file");
5890 return 0;
5891 }
5892
5893 return getGlobalDeclID(F, Record[Idx++]);
5894}
5895
5896/// \brief Resolve the offset of a statement into a statement.
5897///
5898/// This operation will read a new statement from the external
5899/// source each time it is called, and is meant to be used via a
5900/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5901Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5902 // Switch case IDs are per Decl.
5903 ClearSwitchCaseIDs();
5904
5905 // Offset here is a global offset across the entire chain.
5906 RecordLocation Loc = getLocalBitOffset(Offset);
5907 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5908 return ReadStmtFromStream(*Loc.F);
5909}
5910
5911namespace {
5912 class FindExternalLexicalDeclsVisitor {
5913 ASTReader &Reader;
5914 const DeclContext *DC;
5915 bool (*isKindWeWant)(Decl::Kind);
5916
5917 SmallVectorImpl<Decl*> &Decls;
5918 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5919
5920 public:
5921 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5922 bool (*isKindWeWant)(Decl::Kind),
5923 SmallVectorImpl<Decl*> &Decls)
5924 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5925 {
5926 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5927 PredefsVisited[I] = false;
5928 }
5929
5930 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5931 if (Preorder)
5932 return false;
5933
5934 FindExternalLexicalDeclsVisitor *This
5935 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5936
5937 ModuleFile::DeclContextInfosMap::iterator Info
5938 = M.DeclContextInfos.find(This->DC);
5939 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5940 return false;
5941
5942 // Load all of the declaration IDs
5943 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5944 *IDE = ID + Info->second.NumLexicalDecls;
5945 ID != IDE; ++ID) {
5946 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5947 continue;
5948
5949 // Don't add predefined declarations to the lexical context more
5950 // than once.
5951 if (ID->second < NUM_PREDEF_DECL_IDS) {
5952 if (This->PredefsVisited[ID->second])
5953 continue;
5954
5955 This->PredefsVisited[ID->second] = true;
5956 }
5957
5958 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5959 if (!This->DC->isDeclInLexicalTraversal(D))
5960 This->Decls.push_back(D);
5961 }
5962 }
5963
5964 return false;
5965 }
5966 };
5967}
5968
5969ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5970 bool (*isKindWeWant)(Decl::Kind),
5971 SmallVectorImpl<Decl*> &Decls) {
5972 // There might be lexical decls in multiple modules, for the TU at
5973 // least. Walk all of the modules in the order they were loaded.
5974 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5975 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5976 ++NumLexicalDeclContextsRead;
5977 return ELR_Success;
5978}
5979
5980namespace {
5981
5982class DeclIDComp {
5983 ASTReader &Reader;
5984 ModuleFile &Mod;
5985
5986public:
5987 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5988
5989 bool operator()(LocalDeclID L, LocalDeclID R) const {
5990 SourceLocation LHS = getLocation(L);
5991 SourceLocation RHS = getLocation(R);
5992 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5993 }
5994
5995 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5996 SourceLocation RHS = getLocation(R);
5997 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5998 }
5999
6000 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6001 SourceLocation LHS = getLocation(L);
6002 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6003 }
6004
6005 SourceLocation getLocation(LocalDeclID ID) const {
6006 return Reader.getSourceManager().getFileLoc(
6007 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6008 }
6009};
6010
6011}
6012
6013void ASTReader::FindFileRegionDecls(FileID File,
6014 unsigned Offset, unsigned Length,
6015 SmallVectorImpl<Decl *> &Decls) {
6016 SourceManager &SM = getSourceManager();
6017
6018 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6019 if (I == FileDeclIDs.end())
6020 return;
6021
6022 FileDeclsInfo &DInfo = I->second;
6023 if (DInfo.Decls.empty())
6024 return;
6025
6026 SourceLocation
6027 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6028 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6029
6030 DeclIDComp DIDComp(*this, *DInfo.Mod);
6031 ArrayRef<serialization::LocalDeclID>::iterator
6032 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6033 BeginLoc, DIDComp);
6034 if (BeginIt != DInfo.Decls.begin())
6035 --BeginIt;
6036
6037 // If we are pointing at a top-level decl inside an objc container, we need
6038 // to backtrack until we find it otherwise we will fail to report that the
6039 // region overlaps with an objc container.
6040 while (BeginIt != DInfo.Decls.begin() &&
6041 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6042 ->isTopLevelDeclInObjCContainer())
6043 --BeginIt;
6044
6045 ArrayRef<serialization::LocalDeclID>::iterator
6046 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6047 EndLoc, DIDComp);
6048 if (EndIt != DInfo.Decls.end())
6049 ++EndIt;
6050
6051 for (ArrayRef<serialization::LocalDeclID>::iterator
6052 DIt = BeginIt; DIt != EndIt; ++DIt)
6053 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6054}
6055
6056namespace {
6057 /// \brief ModuleFile visitor used to perform name lookup into a
6058 /// declaration context.
6059 class DeclContextNameLookupVisitor {
6060 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006061 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006062 DeclarationName Name;
6063 SmallVectorImpl<NamedDecl *> &Decls;
6064
6065 public:
6066 DeclContextNameLookupVisitor(ASTReader &Reader,
6067 SmallVectorImpl<const DeclContext *> &Contexts,
6068 DeclarationName Name,
6069 SmallVectorImpl<NamedDecl *> &Decls)
6070 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6071
6072 static bool visit(ModuleFile &M, void *UserData) {
6073 DeclContextNameLookupVisitor *This
6074 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6075
6076 // Check whether we have any visible declaration information for
6077 // this context in this module.
6078 ModuleFile::DeclContextInfosMap::iterator Info;
6079 bool FoundInfo = false;
6080 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6081 Info = M.DeclContextInfos.find(This->Contexts[I]);
6082 if (Info != M.DeclContextInfos.end() &&
6083 Info->second.NameLookupTableData) {
6084 FoundInfo = true;
6085 break;
6086 }
6087 }
6088
6089 if (!FoundInfo)
6090 return false;
6091
6092 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006093 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 Info->second.NameLookupTableData;
6095 ASTDeclContextNameLookupTable::iterator Pos
6096 = LookupTable->find(This->Name);
6097 if (Pos == LookupTable->end())
6098 return false;
6099
6100 bool FoundAnything = false;
6101 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6102 for (; Data.first != Data.second; ++Data.first) {
6103 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6104 if (!ND)
6105 continue;
6106
6107 if (ND->getDeclName() != This->Name) {
6108 // A name might be null because the decl's redeclarable part is
6109 // currently read before reading its name. The lookup is triggered by
6110 // building that decl (likely indirectly), and so it is later in the
6111 // sense of "already existing" and can be ignored here.
6112 continue;
6113 }
6114
6115 // Record this declaration.
6116 FoundAnything = true;
6117 This->Decls.push_back(ND);
6118 }
6119
6120 return FoundAnything;
6121 }
6122 };
6123}
6124
Douglas Gregor9f782892013-01-21 15:25:38 +00006125/// \brief Retrieve the "definitive" module file for the definition of the
6126/// given declaration context, if there is one.
6127///
6128/// The "definitive" module file is the only place where we need to look to
6129/// find information about the declarations within the given declaration
6130/// context. For example, C++ and Objective-C classes, C structs/unions, and
6131/// Objective-C protocols, categories, and extensions are all defined in a
6132/// single place in the source code, so they have definitive module files
6133/// associated with them. C++ namespaces, on the other hand, can have
6134/// definitions in multiple different module files.
6135///
6136/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6137/// NDEBUG checking.
6138static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6139 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006140 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6141 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006142
6143 return 0;
6144}
6145
Richard Smith9ce12e32013-02-07 03:30:24 +00006146bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006147ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6148 DeclarationName Name) {
6149 assert(DC->hasExternalVisibleStorage() &&
6150 "DeclContext has no visible decls in storage");
6151 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006152 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006153
6154 SmallVector<NamedDecl *, 64> Decls;
6155
6156 // Compute the declaration contexts we need to look into. Multiple such
6157 // declaration contexts occur when two declaration contexts from disjoint
6158 // modules get merged, e.g., when two namespaces with the same name are
6159 // independently defined in separate modules.
6160 SmallVector<const DeclContext *, 2> Contexts;
6161 Contexts.push_back(DC);
6162
6163 if (DC->isNamespace()) {
6164 MergedDeclsMap::iterator Merged
6165 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6166 if (Merged != MergedDecls.end()) {
6167 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6168 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6169 }
6170 }
6171
6172 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006173
6174 // If we can definitively determine which module file to look into,
6175 // only look there. Otherwise, look in all module files.
6176 ModuleFile *Definitive;
6177 if (Contexts.size() == 1 &&
6178 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6179 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6180 } else {
6181 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6182 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 ++NumVisibleDeclContextsRead;
6184 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006185 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006186}
6187
6188namespace {
6189 /// \brief ModuleFile visitor used to retrieve all visible names in a
6190 /// declaration context.
6191 class DeclContextAllNamesVisitor {
6192 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006193 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006194 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006195 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006196
6197 public:
6198 DeclContextAllNamesVisitor(ASTReader &Reader,
6199 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006200 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006201 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006202
6203 static bool visit(ModuleFile &M, void *UserData) {
6204 DeclContextAllNamesVisitor *This
6205 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6206
6207 // Check whether we have any visible declaration information for
6208 // this context in this module.
6209 ModuleFile::DeclContextInfosMap::iterator Info;
6210 bool FoundInfo = false;
6211 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6212 Info = M.DeclContextInfos.find(This->Contexts[I]);
6213 if (Info != M.DeclContextInfos.end() &&
6214 Info->second.NameLookupTableData) {
6215 FoundInfo = true;
6216 break;
6217 }
6218 }
6219
6220 if (!FoundInfo)
6221 return false;
6222
Richard Smith52e3fba2014-03-11 07:17:35 +00006223 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 Info->second.NameLookupTableData;
6225 bool FoundAnything = false;
6226 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006227 I = LookupTable->data_begin(), E = LookupTable->data_end();
6228 I != E;
6229 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006230 ASTDeclContextNameLookupTrait::data_type Data = *I;
6231 for (; Data.first != Data.second; ++Data.first) {
6232 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6233 *Data.first);
6234 if (!ND)
6235 continue;
6236
6237 // Record this declaration.
6238 FoundAnything = true;
6239 This->Decls[ND->getDeclName()].push_back(ND);
6240 }
6241 }
6242
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006243 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 }
6245 };
6246}
6247
6248void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6249 if (!DC->hasExternalVisibleStorage())
6250 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006251 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006252
6253 // Compute the declaration contexts we need to look into. Multiple such
6254 // declaration contexts occur when two declaration contexts from disjoint
6255 // modules get merged, e.g., when two namespaces with the same name are
6256 // independently defined in separate modules.
6257 SmallVector<const DeclContext *, 2> Contexts;
6258 Contexts.push_back(DC);
6259
6260 if (DC->isNamespace()) {
6261 MergedDeclsMap::iterator Merged
6262 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6263 if (Merged != MergedDecls.end()) {
6264 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6265 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6266 }
6267 }
6268
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006269 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6270 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6272 ++NumVisibleDeclContextsRead;
6273
Craig Topper79be4cd2013-07-05 04:33:53 +00006274 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006275 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6276 }
6277 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6278}
6279
6280/// \brief Under non-PCH compilation the consumer receives the objc methods
6281/// before receiving the implementation, and codegen depends on this.
6282/// We simulate this by deserializing and passing to consumer the methods of the
6283/// implementation before passing the deserialized implementation decl.
6284static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6285 ASTConsumer *Consumer) {
6286 assert(ImplD && Consumer);
6287
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006288 for (auto *I : ImplD->methods())
6289 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006290
6291 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6292}
6293
6294void ASTReader::PassInterestingDeclsToConsumer() {
6295 assert(Consumer);
6296 while (!InterestingDecls.empty()) {
6297 Decl *D = InterestingDecls.front();
6298 InterestingDecls.pop_front();
6299
6300 PassInterestingDeclToConsumer(D);
6301 }
6302}
6303
6304void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6305 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6306 PassObjCImplDeclToConsumer(ImplD, Consumer);
6307 else
6308 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6309}
6310
6311void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6312 this->Consumer = Consumer;
6313
6314 if (!Consumer)
6315 return;
6316
Ben Langmuir332aafe2014-01-31 01:06:56 +00006317 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006318 // Force deserialization of this decl, which will cause it to be queued for
6319 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006320 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006322 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006323
6324 PassInterestingDeclsToConsumer();
6325}
6326
6327void ASTReader::PrintStats() {
6328 std::fprintf(stderr, "*** AST File Statistics:\n");
6329
6330 unsigned NumTypesLoaded
6331 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6332 QualType());
6333 unsigned NumDeclsLoaded
6334 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6335 (Decl *)0);
6336 unsigned NumIdentifiersLoaded
6337 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6338 IdentifiersLoaded.end(),
6339 (IdentifierInfo *)0);
6340 unsigned NumMacrosLoaded
6341 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6342 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006343 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 unsigned NumSelectorsLoaded
6345 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6346 SelectorsLoaded.end(),
6347 Selector());
6348
6349 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6350 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6351 NumSLocEntriesRead, TotalNumSLocEntries,
6352 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6353 if (!TypesLoaded.empty())
6354 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6355 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6356 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6357 if (!DeclsLoaded.empty())
6358 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6359 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6360 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6361 if (!IdentifiersLoaded.empty())
6362 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6363 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6364 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6365 if (!MacrosLoaded.empty())
6366 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6367 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6368 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6369 if (!SelectorsLoaded.empty())
6370 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6371 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6372 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6373 if (TotalNumStatements)
6374 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6375 NumStatementsRead, TotalNumStatements,
6376 ((float)NumStatementsRead/TotalNumStatements * 100));
6377 if (TotalNumMacros)
6378 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6379 NumMacrosRead, TotalNumMacros,
6380 ((float)NumMacrosRead/TotalNumMacros * 100));
6381 if (TotalLexicalDeclContexts)
6382 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6383 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6384 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6385 * 100));
6386 if (TotalVisibleDeclContexts)
6387 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6388 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6389 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6390 * 100));
6391 if (TotalNumMethodPoolEntries) {
6392 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6393 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6394 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6395 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006397 if (NumMethodPoolLookups) {
6398 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6399 NumMethodPoolHits, NumMethodPoolLookups,
6400 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6401 }
6402 if (NumMethodPoolTableLookups) {
6403 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6404 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6405 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6406 * 100.0));
6407 }
6408
Douglas Gregor00a50f72013-01-25 00:38:33 +00006409 if (NumIdentifierLookupHits) {
6410 std::fprintf(stderr,
6411 " %u / %u identifier table lookups succeeded (%f%%)\n",
6412 NumIdentifierLookupHits, NumIdentifierLookups,
6413 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6414 }
6415
Douglas Gregore060e572013-01-25 01:03:03 +00006416 if (GlobalIndex) {
6417 std::fprintf(stderr, "\n");
6418 GlobalIndex->printStats();
6419 }
6420
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 std::fprintf(stderr, "\n");
6422 dump();
6423 std::fprintf(stderr, "\n");
6424}
6425
6426template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6427static void
6428dumpModuleIDMap(StringRef Name,
6429 const ContinuousRangeMap<Key, ModuleFile *,
6430 InitialCapacity> &Map) {
6431 if (Map.begin() == Map.end())
6432 return;
6433
6434 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6435 llvm::errs() << Name << ":\n";
6436 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6437 I != IEnd; ++I) {
6438 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6439 << "\n";
6440 }
6441}
6442
6443void ASTReader::dump() {
6444 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6445 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6446 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6447 dumpModuleIDMap("Global type map", GlobalTypeMap);
6448 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6449 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6450 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6451 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6452 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6453 dumpModuleIDMap("Global preprocessed entity map",
6454 GlobalPreprocessedEntityMap);
6455
6456 llvm::errs() << "\n*** PCH/Modules Loaded:";
6457 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6458 MEnd = ModuleMgr.end();
6459 M != MEnd; ++M)
6460 (*M)->dump();
6461}
6462
6463/// Return the amount of memory used by memory buffers, breaking down
6464/// by heap-backed versus mmap'ed memory.
6465void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6466 for (ModuleConstIterator I = ModuleMgr.begin(),
6467 E = ModuleMgr.end(); I != E; ++I) {
6468 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6469 size_t bytes = buf->getBufferSize();
6470 switch (buf->getBufferKind()) {
6471 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6472 sizes.malloc_bytes += bytes;
6473 break;
6474 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6475 sizes.mmap_bytes += bytes;
6476 break;
6477 }
6478 }
6479 }
6480}
6481
6482void ASTReader::InitializeSema(Sema &S) {
6483 SemaObj = &S;
6484 S.addExternalSource(this);
6485
6486 // Makes sure any declarations that were deserialized "too early"
6487 // still get added to the identifier's declaration chains.
6488 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006489 pushExternalDeclIntoScope(PreloadedDecls[I],
6490 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 }
6492 PreloadedDecls.clear();
6493
Richard Smith3d8e97e2013-10-18 06:54:39 +00006494 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006495 if (!FPPragmaOptions.empty()) {
6496 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6497 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6498 }
6499
Richard Smith3d8e97e2013-10-18 06:54:39 +00006500 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 if (!OpenCLExtensions.empty()) {
6502 unsigned I = 0;
6503#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6504#include "clang/Basic/OpenCLExtensions.def"
6505
6506 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6507 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006508
6509 UpdateSema();
6510}
6511
6512void ASTReader::UpdateSema() {
6513 assert(SemaObj && "no Sema to update");
6514
6515 // Load the offsets of the declarations that Sema references.
6516 // They will be lazily deserialized when needed.
6517 if (!SemaDeclRefs.empty()) {
6518 assert(SemaDeclRefs.size() % 2 == 0);
6519 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6520 if (!SemaObj->StdNamespace)
6521 SemaObj->StdNamespace = SemaDeclRefs[I];
6522 if (!SemaObj->StdBadAlloc)
6523 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6524 }
6525 SemaDeclRefs.clear();
6526 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006527}
6528
6529IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6530 // Note that we are loading an identifier.
6531 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006532 StringRef Name(NameStart, NameEnd - NameStart);
6533
6534 // If there is a global index, look there first to determine which modules
6535 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006536 GlobalModuleIndex::HitSet Hits;
6537 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006538 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006539 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6540 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006541 }
6542 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006543 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006544 NumIdentifierLookups,
6545 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006546 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 IdentifierInfo *II = Visitor.getIdentifierInfo();
6548 markIdentifierUpToDate(II);
6549 return II;
6550}
6551
6552namespace clang {
6553 /// \brief An identifier-lookup iterator that enumerates all of the
6554 /// identifiers stored within a set of AST files.
6555 class ASTIdentifierIterator : public IdentifierIterator {
6556 /// \brief The AST reader whose identifiers are being enumerated.
6557 const ASTReader &Reader;
6558
6559 /// \brief The current index into the chain of AST files stored in
6560 /// the AST reader.
6561 unsigned Index;
6562
6563 /// \brief The current position within the identifier lookup table
6564 /// of the current AST file.
6565 ASTIdentifierLookupTable::key_iterator Current;
6566
6567 /// \brief The end position within the identifier lookup table of
6568 /// the current AST file.
6569 ASTIdentifierLookupTable::key_iterator End;
6570
6571 public:
6572 explicit ASTIdentifierIterator(const ASTReader &Reader);
6573
Craig Topper3e89dfe2014-03-13 02:13:41 +00006574 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 };
6576}
6577
6578ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6579 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6580 ASTIdentifierLookupTable *IdTable
6581 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6582 Current = IdTable->key_begin();
6583 End = IdTable->key_end();
6584}
6585
6586StringRef ASTIdentifierIterator::Next() {
6587 while (Current == End) {
6588 // If we have exhausted all of our AST files, we're done.
6589 if (Index == 0)
6590 return StringRef();
6591
6592 --Index;
6593 ASTIdentifierLookupTable *IdTable
6594 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6595 IdentifierLookupTable;
6596 Current = IdTable->key_begin();
6597 End = IdTable->key_end();
6598 }
6599
6600 // We have any identifiers remaining in the current AST file; return
6601 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006602 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006604 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006605}
6606
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006607IdentifierIterator *ASTReader::getIdentifiers() {
6608 if (!loadGlobalIndex())
6609 return GlobalIndex->createIdentifierIterator();
6610
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 return new ASTIdentifierIterator(*this);
6612}
6613
6614namespace clang { namespace serialization {
6615 class ReadMethodPoolVisitor {
6616 ASTReader &Reader;
6617 Selector Sel;
6618 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006619 unsigned InstanceBits;
6620 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006621 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6622 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006623
6624 public:
6625 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6626 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006627 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6628 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006629
6630 static bool visit(ModuleFile &M, void *UserData) {
6631 ReadMethodPoolVisitor *This
6632 = static_cast<ReadMethodPoolVisitor *>(UserData);
6633
6634 if (!M.SelectorLookupTable)
6635 return false;
6636
6637 // If we've already searched this module file, skip it now.
6638 if (M.Generation <= This->PriorGeneration)
6639 return true;
6640
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006641 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 ASTSelectorLookupTable *PoolTable
6643 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6644 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6645 if (Pos == PoolTable->end())
6646 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006647
6648 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 ++This->Reader.NumSelectorsRead;
6650 // FIXME: Not quite happy with the statistics here. We probably should
6651 // disable this tracking when called via LoadSelector.
6652 // Also, should entries without methods count as misses?
6653 ++This->Reader.NumMethodPoolEntriesRead;
6654 ASTSelectorLookupTrait::data_type Data = *Pos;
6655 if (This->Reader.DeserializationListener)
6656 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6657 This->Sel);
6658
6659 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6660 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006661 This->InstanceBits = Data.InstanceBits;
6662 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 return true;
6664 }
6665
6666 /// \brief Retrieve the instance methods found by this visitor.
6667 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6668 return InstanceMethods;
6669 }
6670
6671 /// \brief Retrieve the instance methods found by this visitor.
6672 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6673 return FactoryMethods;
6674 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006675
6676 unsigned getInstanceBits() const { return InstanceBits; }
6677 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 };
6679} } // end namespace clang::serialization
6680
6681/// \brief Add the given set of methods to the method list.
6682static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6683 ObjCMethodList &List) {
6684 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6685 S.addMethodToGlobalList(&List, Methods[I]);
6686 }
6687}
6688
6689void ASTReader::ReadMethodPool(Selector Sel) {
6690 // Get the selector generation and update it to the current generation.
6691 unsigned &Generation = SelectorGeneration[Sel];
6692 unsigned PriorGeneration = Generation;
6693 Generation = CurrentGeneration;
6694
6695 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006696 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006697 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6698 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6699
6700 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006701 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006702 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006703
6704 ++NumMethodPoolHits;
6705
Guy Benyei11169dd2012-12-18 14:30:41 +00006706 if (!getSema())
6707 return;
6708
6709 Sema &S = *getSema();
6710 Sema::GlobalMethodPool::iterator Pos
6711 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6712
6713 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6714 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006715 Pos->second.first.setBits(Visitor.getInstanceBits());
6716 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006717}
6718
6719void ASTReader::ReadKnownNamespaces(
6720 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6721 Namespaces.clear();
6722
6723 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6724 if (NamespaceDecl *Namespace
6725 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6726 Namespaces.push_back(Namespace);
6727 }
6728}
6729
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006730void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006731 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006732 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6733 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006734 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006735 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006736 Undefined.insert(std::make_pair(D, Loc));
6737 }
6738}
Nick Lewycky8334af82013-01-26 00:35:08 +00006739
Guy Benyei11169dd2012-12-18 14:30:41 +00006740void ASTReader::ReadTentativeDefinitions(
6741 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6742 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6743 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6744 if (Var)
6745 TentativeDefs.push_back(Var);
6746 }
6747 TentativeDefinitions.clear();
6748}
6749
6750void ASTReader::ReadUnusedFileScopedDecls(
6751 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6752 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6753 DeclaratorDecl *D
6754 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6755 if (D)
6756 Decls.push_back(D);
6757 }
6758 UnusedFileScopedDecls.clear();
6759}
6760
6761void ASTReader::ReadDelegatingConstructors(
6762 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6763 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6764 CXXConstructorDecl *D
6765 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6766 if (D)
6767 Decls.push_back(D);
6768 }
6769 DelegatingCtorDecls.clear();
6770}
6771
6772void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6773 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6774 TypedefNameDecl *D
6775 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6776 if (D)
6777 Decls.push_back(D);
6778 }
6779 ExtVectorDecls.clear();
6780}
6781
6782void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6783 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6784 CXXRecordDecl *D
6785 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6786 if (D)
6787 Decls.push_back(D);
6788 }
6789 DynamicClasses.clear();
6790}
6791
6792void
Richard Smith78165b52013-01-10 23:43:47 +00006793ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6794 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6795 NamedDecl *D
6796 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 if (D)
6798 Decls.push_back(D);
6799 }
Richard Smith78165b52013-01-10 23:43:47 +00006800 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006801}
6802
6803void ASTReader::ReadReferencedSelectors(
6804 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6805 if (ReferencedSelectorsData.empty())
6806 return;
6807
6808 // If there are @selector references added them to its pool. This is for
6809 // implementation of -Wselector.
6810 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6811 unsigned I = 0;
6812 while (I < DataSize) {
6813 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6814 SourceLocation SelLoc
6815 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6816 Sels.push_back(std::make_pair(Sel, SelLoc));
6817 }
6818 ReferencedSelectorsData.clear();
6819}
6820
6821void ASTReader::ReadWeakUndeclaredIdentifiers(
6822 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6823 if (WeakUndeclaredIdentifiers.empty())
6824 return;
6825
6826 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6827 IdentifierInfo *WeakId
6828 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6829 IdentifierInfo *AliasId
6830 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6831 SourceLocation Loc
6832 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6833 bool Used = WeakUndeclaredIdentifiers[I++];
6834 WeakInfo WI(AliasId, Loc);
6835 WI.setUsed(Used);
6836 WeakIDs.push_back(std::make_pair(WeakId, WI));
6837 }
6838 WeakUndeclaredIdentifiers.clear();
6839}
6840
6841void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6842 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6843 ExternalVTableUse VT;
6844 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6845 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6846 VT.DefinitionRequired = VTableUses[Idx++];
6847 VTables.push_back(VT);
6848 }
6849
6850 VTableUses.clear();
6851}
6852
6853void ASTReader::ReadPendingInstantiations(
6854 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6855 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6856 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6857 SourceLocation Loc
6858 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6859
6860 Pending.push_back(std::make_pair(D, Loc));
6861 }
6862 PendingInstantiations.clear();
6863}
6864
Richard Smithe40f2ba2013-08-07 21:41:30 +00006865void ASTReader::ReadLateParsedTemplates(
6866 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6867 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6868 /* In loop */) {
6869 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6870
6871 LateParsedTemplate *LT = new LateParsedTemplate;
6872 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6873
6874 ModuleFile *F = getOwningModuleFile(LT->D);
6875 assert(F && "No module");
6876
6877 unsigned TokN = LateParsedTemplates[Idx++];
6878 LT->Toks.reserve(TokN);
6879 for (unsigned T = 0; T < TokN; ++T)
6880 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6881
6882 LPTMap[FD] = LT;
6883 }
6884
6885 LateParsedTemplates.clear();
6886}
6887
Guy Benyei11169dd2012-12-18 14:30:41 +00006888void ASTReader::LoadSelector(Selector Sel) {
6889 // It would be complicated to avoid reading the methods anyway. So don't.
6890 ReadMethodPool(Sel);
6891}
6892
6893void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6894 assert(ID && "Non-zero identifier ID required");
6895 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6896 IdentifiersLoaded[ID - 1] = II;
6897 if (DeserializationListener)
6898 DeserializationListener->IdentifierRead(ID, II);
6899}
6900
6901/// \brief Set the globally-visible declarations associated with the given
6902/// identifier.
6903///
6904/// If the AST reader is currently in a state where the given declaration IDs
6905/// cannot safely be resolved, they are queued until it is safe to resolve
6906/// them.
6907///
6908/// \param II an IdentifierInfo that refers to one or more globally-visible
6909/// declarations.
6910///
6911/// \param DeclIDs the set of declaration IDs with the name @p II that are
6912/// visible at global scope.
6913///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006914/// \param Decls if non-null, this vector will be populated with the set of
6915/// deserialized declarations. These declarations will not be pushed into
6916/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006917void
6918ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6919 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006920 SmallVectorImpl<Decl *> *Decls) {
6921 if (NumCurrentElementsDeserializing && !Decls) {
6922 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 return;
6924 }
6925
6926 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6927 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6928 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006929 // If we're simply supposed to record the declarations, do so now.
6930 if (Decls) {
6931 Decls->push_back(D);
6932 continue;
6933 }
6934
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 // Introduce this declaration into the translation-unit scope
6936 // and add it to the declaration chain for this identifier, so
6937 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006938 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 } else {
6940 // Queue this declaration so that it will be added to the
6941 // translation unit scope and identifier's declaration chain
6942 // once a Sema object is known.
6943 PreloadedDecls.push_back(D);
6944 }
6945 }
6946}
6947
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006948IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 if (ID == 0)
6950 return 0;
6951
6952 if (IdentifiersLoaded.empty()) {
6953 Error("no identifier table in AST file");
6954 return 0;
6955 }
6956
6957 ID -= 1;
6958 if (!IdentifiersLoaded[ID]) {
6959 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6960 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6961 ModuleFile *M = I->second;
6962 unsigned Index = ID - M->BaseIdentifierID;
6963 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6964
6965 // All of the strings in the AST file are preceded by a 16-bit length.
6966 // Extract that 16-bit length to avoid having to execute strlen().
6967 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6968 // unsigned integers. This is important to avoid integer overflow when
6969 // we cast them to 'unsigned'.
6970 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6971 unsigned StrLen = (((unsigned) StrLenPtr[0])
6972 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006973 IdentifiersLoaded[ID]
6974 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 if (DeserializationListener)
6976 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6977 }
6978
6979 return IdentifiersLoaded[ID];
6980}
6981
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006982IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6983 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006984}
6985
6986IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6987 if (LocalID < NUM_PREDEF_IDENT_IDS)
6988 return LocalID;
6989
6990 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6991 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6992 assert(I != M.IdentifierRemap.end()
6993 && "Invalid index into identifier index remap");
6994
6995 return LocalID + I->second;
6996}
6997
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006998MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 if (ID == 0)
7000 return 0;
7001
7002 if (MacrosLoaded.empty()) {
7003 Error("no macro table in AST file");
7004 return 0;
7005 }
7006
7007 ID -= NUM_PREDEF_MACRO_IDS;
7008 if (!MacrosLoaded[ID]) {
7009 GlobalMacroMapType::iterator I
7010 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7011 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7012 ModuleFile *M = I->second;
7013 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007014 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7015
7016 if (DeserializationListener)
7017 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7018 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007019 }
7020
7021 return MacrosLoaded[ID];
7022}
7023
7024MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7025 if (LocalID < NUM_PREDEF_MACRO_IDS)
7026 return LocalID;
7027
7028 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7029 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7030 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7031
7032 return LocalID + I->second;
7033}
7034
7035serialization::SubmoduleID
7036ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7037 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7038 return LocalID;
7039
7040 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7041 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7042 assert(I != M.SubmoduleRemap.end()
7043 && "Invalid index into submodule index remap");
7044
7045 return LocalID + I->second;
7046}
7047
7048Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7049 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7050 assert(GlobalID == 0 && "Unhandled global submodule ID");
7051 return 0;
7052 }
7053
7054 if (GlobalID > SubmodulesLoaded.size()) {
7055 Error("submodule ID out of range in AST file");
7056 return 0;
7057 }
7058
7059 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7060}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007061
7062Module *ASTReader::getModule(unsigned ID) {
7063 return getSubmodule(ID);
7064}
7065
Guy Benyei11169dd2012-12-18 14:30:41 +00007066Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7067 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7068}
7069
7070Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7071 if (ID == 0)
7072 return Selector();
7073
7074 if (ID > SelectorsLoaded.size()) {
7075 Error("selector ID out of range in AST file");
7076 return Selector();
7077 }
7078
7079 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7080 // Load this selector from the selector table.
7081 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7082 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7083 ModuleFile &M = *I->second;
7084 ASTSelectorLookupTrait Trait(*this, M);
7085 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7086 SelectorsLoaded[ID - 1] =
7087 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7088 if (DeserializationListener)
7089 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7090 }
7091
7092 return SelectorsLoaded[ID - 1];
7093}
7094
7095Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7096 return DecodeSelector(ID);
7097}
7098
7099uint32_t ASTReader::GetNumExternalSelectors() {
7100 // ID 0 (the null selector) is considered an external selector.
7101 return getTotalNumSelectors() + 1;
7102}
7103
7104serialization::SelectorID
7105ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7106 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7107 return LocalID;
7108
7109 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7110 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7111 assert(I != M.SelectorRemap.end()
7112 && "Invalid index into selector index remap");
7113
7114 return LocalID + I->second;
7115}
7116
7117DeclarationName
7118ASTReader::ReadDeclarationName(ModuleFile &F,
7119 const RecordData &Record, unsigned &Idx) {
7120 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7121 switch (Kind) {
7122 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007123 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007124
7125 case DeclarationName::ObjCZeroArgSelector:
7126 case DeclarationName::ObjCOneArgSelector:
7127 case DeclarationName::ObjCMultiArgSelector:
7128 return DeclarationName(ReadSelector(F, Record, Idx));
7129
7130 case DeclarationName::CXXConstructorName:
7131 return Context.DeclarationNames.getCXXConstructorName(
7132 Context.getCanonicalType(readType(F, Record, Idx)));
7133
7134 case DeclarationName::CXXDestructorName:
7135 return Context.DeclarationNames.getCXXDestructorName(
7136 Context.getCanonicalType(readType(F, Record, Idx)));
7137
7138 case DeclarationName::CXXConversionFunctionName:
7139 return Context.DeclarationNames.getCXXConversionFunctionName(
7140 Context.getCanonicalType(readType(F, Record, Idx)));
7141
7142 case DeclarationName::CXXOperatorName:
7143 return Context.DeclarationNames.getCXXOperatorName(
7144 (OverloadedOperatorKind)Record[Idx++]);
7145
7146 case DeclarationName::CXXLiteralOperatorName:
7147 return Context.DeclarationNames.getCXXLiteralOperatorName(
7148 GetIdentifierInfo(F, Record, Idx));
7149
7150 case DeclarationName::CXXUsingDirective:
7151 return DeclarationName::getUsingDirectiveName();
7152 }
7153
7154 llvm_unreachable("Invalid NameKind!");
7155}
7156
7157void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7158 DeclarationNameLoc &DNLoc,
7159 DeclarationName Name,
7160 const RecordData &Record, unsigned &Idx) {
7161 switch (Name.getNameKind()) {
7162 case DeclarationName::CXXConstructorName:
7163 case DeclarationName::CXXDestructorName:
7164 case DeclarationName::CXXConversionFunctionName:
7165 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7166 break;
7167
7168 case DeclarationName::CXXOperatorName:
7169 DNLoc.CXXOperatorName.BeginOpNameLoc
7170 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7171 DNLoc.CXXOperatorName.EndOpNameLoc
7172 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7173 break;
7174
7175 case DeclarationName::CXXLiteralOperatorName:
7176 DNLoc.CXXLiteralOperatorName.OpNameLoc
7177 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7178 break;
7179
7180 case DeclarationName::Identifier:
7181 case DeclarationName::ObjCZeroArgSelector:
7182 case DeclarationName::ObjCOneArgSelector:
7183 case DeclarationName::ObjCMultiArgSelector:
7184 case DeclarationName::CXXUsingDirective:
7185 break;
7186 }
7187}
7188
7189void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7190 DeclarationNameInfo &NameInfo,
7191 const RecordData &Record, unsigned &Idx) {
7192 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7193 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7194 DeclarationNameLoc DNLoc;
7195 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7196 NameInfo.setInfo(DNLoc);
7197}
7198
7199void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7200 const RecordData &Record, unsigned &Idx) {
7201 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7202 unsigned NumTPLists = Record[Idx++];
7203 Info.NumTemplParamLists = NumTPLists;
7204 if (NumTPLists) {
7205 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7206 for (unsigned i=0; i != NumTPLists; ++i)
7207 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7208 }
7209}
7210
7211TemplateName
7212ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7213 unsigned &Idx) {
7214 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7215 switch (Kind) {
7216 case TemplateName::Template:
7217 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7218
7219 case TemplateName::OverloadedTemplate: {
7220 unsigned size = Record[Idx++];
7221 UnresolvedSet<8> Decls;
7222 while (size--)
7223 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7224
7225 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7226 }
7227
7228 case TemplateName::QualifiedTemplate: {
7229 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7230 bool hasTemplKeyword = Record[Idx++];
7231 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7232 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7233 }
7234
7235 case TemplateName::DependentTemplate: {
7236 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7237 if (Record[Idx++]) // isIdentifier
7238 return Context.getDependentTemplateName(NNS,
7239 GetIdentifierInfo(F, Record,
7240 Idx));
7241 return Context.getDependentTemplateName(NNS,
7242 (OverloadedOperatorKind)Record[Idx++]);
7243 }
7244
7245 case TemplateName::SubstTemplateTemplateParm: {
7246 TemplateTemplateParmDecl *param
7247 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7248 if (!param) return TemplateName();
7249 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7250 return Context.getSubstTemplateTemplateParm(param, replacement);
7251 }
7252
7253 case TemplateName::SubstTemplateTemplateParmPack: {
7254 TemplateTemplateParmDecl *Param
7255 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7256 if (!Param)
7257 return TemplateName();
7258
7259 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7260 if (ArgPack.getKind() != TemplateArgument::Pack)
7261 return TemplateName();
7262
7263 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7264 }
7265 }
7266
7267 llvm_unreachable("Unhandled template name kind!");
7268}
7269
7270TemplateArgument
7271ASTReader::ReadTemplateArgument(ModuleFile &F,
7272 const RecordData &Record, unsigned &Idx) {
7273 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7274 switch (Kind) {
7275 case TemplateArgument::Null:
7276 return TemplateArgument();
7277 case TemplateArgument::Type:
7278 return TemplateArgument(readType(F, Record, Idx));
7279 case TemplateArgument::Declaration: {
7280 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7281 bool ForReferenceParam = Record[Idx++];
7282 return TemplateArgument(D, ForReferenceParam);
7283 }
7284 case TemplateArgument::NullPtr:
7285 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7286 case TemplateArgument::Integral: {
7287 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7288 QualType T = readType(F, Record, Idx);
7289 return TemplateArgument(Context, Value, T);
7290 }
7291 case TemplateArgument::Template:
7292 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7293 case TemplateArgument::TemplateExpansion: {
7294 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007295 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007296 if (unsigned NumExpansions = Record[Idx++])
7297 NumTemplateExpansions = NumExpansions - 1;
7298 return TemplateArgument(Name, NumTemplateExpansions);
7299 }
7300 case TemplateArgument::Expression:
7301 return TemplateArgument(ReadExpr(F));
7302 case TemplateArgument::Pack: {
7303 unsigned NumArgs = Record[Idx++];
7304 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7305 for (unsigned I = 0; I != NumArgs; ++I)
7306 Args[I] = ReadTemplateArgument(F, Record, Idx);
7307 return TemplateArgument(Args, NumArgs);
7308 }
7309 }
7310
7311 llvm_unreachable("Unhandled template argument kind!");
7312}
7313
7314TemplateParameterList *
7315ASTReader::ReadTemplateParameterList(ModuleFile &F,
7316 const RecordData &Record, unsigned &Idx) {
7317 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7318 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7319 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7320
7321 unsigned NumParams = Record[Idx++];
7322 SmallVector<NamedDecl *, 16> Params;
7323 Params.reserve(NumParams);
7324 while (NumParams--)
7325 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7326
7327 TemplateParameterList* TemplateParams =
7328 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7329 Params.data(), Params.size(), RAngleLoc);
7330 return TemplateParams;
7331}
7332
7333void
7334ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007335ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 ModuleFile &F, const RecordData &Record,
7337 unsigned &Idx) {
7338 unsigned NumTemplateArgs = Record[Idx++];
7339 TemplArgs.reserve(NumTemplateArgs);
7340 while (NumTemplateArgs--)
7341 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7342}
7343
7344/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007345void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007346 const RecordData &Record, unsigned &Idx) {
7347 unsigned NumDecls = Record[Idx++];
7348 Set.reserve(Context, NumDecls);
7349 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007350 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007351 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007352 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007353 }
7354}
7355
7356CXXBaseSpecifier
7357ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7358 const RecordData &Record, unsigned &Idx) {
7359 bool isVirtual = static_cast<bool>(Record[Idx++]);
7360 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7361 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7362 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7363 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7364 SourceRange Range = ReadSourceRange(F, Record, Idx);
7365 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7366 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7367 EllipsisLoc);
7368 Result.setInheritConstructors(inheritConstructors);
7369 return Result;
7370}
7371
7372std::pair<CXXCtorInitializer **, unsigned>
7373ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7374 unsigned &Idx) {
7375 CXXCtorInitializer **CtorInitializers = 0;
7376 unsigned NumInitializers = Record[Idx++];
7377 if (NumInitializers) {
7378 CtorInitializers
7379 = new (Context) CXXCtorInitializer*[NumInitializers];
7380 for (unsigned i=0; i != NumInitializers; ++i) {
7381 TypeSourceInfo *TInfo = 0;
7382 bool IsBaseVirtual = false;
7383 FieldDecl *Member = 0;
7384 IndirectFieldDecl *IndirectMember = 0;
7385
7386 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7387 switch (Type) {
7388 case CTOR_INITIALIZER_BASE:
7389 TInfo = GetTypeSourceInfo(F, Record, Idx);
7390 IsBaseVirtual = Record[Idx++];
7391 break;
7392
7393 case CTOR_INITIALIZER_DELEGATING:
7394 TInfo = GetTypeSourceInfo(F, Record, Idx);
7395 break;
7396
7397 case CTOR_INITIALIZER_MEMBER:
7398 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7399 break;
7400
7401 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7402 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7403 break;
7404 }
7405
7406 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7407 Expr *Init = ReadExpr(F);
7408 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7409 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7410 bool IsWritten = Record[Idx++];
7411 unsigned SourceOrderOrNumArrayIndices;
7412 SmallVector<VarDecl *, 8> Indices;
7413 if (IsWritten) {
7414 SourceOrderOrNumArrayIndices = Record[Idx++];
7415 } else {
7416 SourceOrderOrNumArrayIndices = Record[Idx++];
7417 Indices.reserve(SourceOrderOrNumArrayIndices);
7418 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7419 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7420 }
7421
7422 CXXCtorInitializer *BOMInit;
7423 if (Type == CTOR_INITIALIZER_BASE) {
7424 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7425 LParenLoc, Init, RParenLoc,
7426 MemberOrEllipsisLoc);
7427 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7428 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7429 Init, RParenLoc);
7430 } else if (IsWritten) {
7431 if (Member)
7432 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7433 LParenLoc, Init, RParenLoc);
7434 else
7435 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7436 MemberOrEllipsisLoc, LParenLoc,
7437 Init, RParenLoc);
7438 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007439 if (IndirectMember) {
7440 assert(Indices.empty() && "Indirect field improperly initialized");
7441 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7442 MemberOrEllipsisLoc, LParenLoc,
7443 Init, RParenLoc);
7444 } else {
7445 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7446 LParenLoc, Init, RParenLoc,
7447 Indices.data(), Indices.size());
7448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 }
7450
7451 if (IsWritten)
7452 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7453 CtorInitializers[i] = BOMInit;
7454 }
7455 }
7456
7457 return std::make_pair(CtorInitializers, NumInitializers);
7458}
7459
7460NestedNameSpecifier *
7461ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7462 const RecordData &Record, unsigned &Idx) {
7463 unsigned N = Record[Idx++];
7464 NestedNameSpecifier *NNS = 0, *Prev = 0;
7465 for (unsigned I = 0; I != N; ++I) {
7466 NestedNameSpecifier::SpecifierKind Kind
7467 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7468 switch (Kind) {
7469 case NestedNameSpecifier::Identifier: {
7470 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7471 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7472 break;
7473 }
7474
7475 case NestedNameSpecifier::Namespace: {
7476 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7477 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7478 break;
7479 }
7480
7481 case NestedNameSpecifier::NamespaceAlias: {
7482 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7483 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7484 break;
7485 }
7486
7487 case NestedNameSpecifier::TypeSpec:
7488 case NestedNameSpecifier::TypeSpecWithTemplate: {
7489 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7490 if (!T)
7491 return 0;
7492
7493 bool Template = Record[Idx++];
7494 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7495 break;
7496 }
7497
7498 case NestedNameSpecifier::Global: {
7499 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7500 // No associated value, and there can't be a prefix.
7501 break;
7502 }
7503 }
7504 Prev = NNS;
7505 }
7506 return NNS;
7507}
7508
7509NestedNameSpecifierLoc
7510ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7511 unsigned &Idx) {
7512 unsigned N = Record[Idx++];
7513 NestedNameSpecifierLocBuilder Builder;
7514 for (unsigned I = 0; I != N; ++I) {
7515 NestedNameSpecifier::SpecifierKind Kind
7516 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7517 switch (Kind) {
7518 case NestedNameSpecifier::Identifier: {
7519 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7520 SourceRange Range = ReadSourceRange(F, Record, Idx);
7521 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7522 break;
7523 }
7524
7525 case NestedNameSpecifier::Namespace: {
7526 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7527 SourceRange Range = ReadSourceRange(F, Record, Idx);
7528 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7529 break;
7530 }
7531
7532 case NestedNameSpecifier::NamespaceAlias: {
7533 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7534 SourceRange Range = ReadSourceRange(F, Record, Idx);
7535 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7536 break;
7537 }
7538
7539 case NestedNameSpecifier::TypeSpec:
7540 case NestedNameSpecifier::TypeSpecWithTemplate: {
7541 bool Template = Record[Idx++];
7542 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7543 if (!T)
7544 return NestedNameSpecifierLoc();
7545 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7546
7547 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7548 Builder.Extend(Context,
7549 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7550 T->getTypeLoc(), ColonColonLoc);
7551 break;
7552 }
7553
7554 case NestedNameSpecifier::Global: {
7555 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7556 Builder.MakeGlobal(Context, ColonColonLoc);
7557 break;
7558 }
7559 }
7560 }
7561
7562 return Builder.getWithLocInContext(Context);
7563}
7564
7565SourceRange
7566ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7567 unsigned &Idx) {
7568 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7569 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7570 return SourceRange(beg, end);
7571}
7572
7573/// \brief Read an integral value
7574llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7575 unsigned BitWidth = Record[Idx++];
7576 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7577 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7578 Idx += NumWords;
7579 return Result;
7580}
7581
7582/// \brief Read a signed integral value
7583llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7584 bool isUnsigned = Record[Idx++];
7585 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7586}
7587
7588/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007589llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7590 const llvm::fltSemantics &Sem,
7591 unsigned &Idx) {
7592 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007593}
7594
7595// \brief Read a string
7596std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7597 unsigned Len = Record[Idx++];
7598 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7599 Idx += Len;
7600 return Result;
7601}
7602
7603VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7604 unsigned &Idx) {
7605 unsigned Major = Record[Idx++];
7606 unsigned Minor = Record[Idx++];
7607 unsigned Subminor = Record[Idx++];
7608 if (Minor == 0)
7609 return VersionTuple(Major);
7610 if (Subminor == 0)
7611 return VersionTuple(Major, Minor - 1);
7612 return VersionTuple(Major, Minor - 1, Subminor - 1);
7613}
7614
7615CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7616 const RecordData &Record,
7617 unsigned &Idx) {
7618 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7619 return CXXTemporary::Create(Context, Decl);
7620}
7621
7622DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007623 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007624}
7625
7626DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7627 return Diags.Report(Loc, DiagID);
7628}
7629
7630/// \brief Retrieve the identifier table associated with the
7631/// preprocessor.
7632IdentifierTable &ASTReader::getIdentifierTable() {
7633 return PP.getIdentifierTable();
7634}
7635
7636/// \brief Record that the given ID maps to the given switch-case
7637/// statement.
7638void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7639 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7640 "Already have a SwitchCase with this ID");
7641 (*CurrSwitchCaseStmts)[ID] = SC;
7642}
7643
7644/// \brief Retrieve the switch-case statement with the given ID.
7645SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7646 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7647 return (*CurrSwitchCaseStmts)[ID];
7648}
7649
7650void ASTReader::ClearSwitchCaseIDs() {
7651 CurrSwitchCaseStmts->clear();
7652}
7653
7654void ASTReader::ReadComments() {
7655 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007656 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 serialization::ModuleFile *> >::iterator
7658 I = CommentsCursors.begin(),
7659 E = CommentsCursors.end();
7660 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007661 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 serialization::ModuleFile &F = *I->second;
7663 SavedStreamPosition SavedPosition(Cursor);
7664
7665 RecordData Record;
7666 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007667 llvm::BitstreamEntry Entry =
7668 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7669
7670 switch (Entry.Kind) {
7671 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7672 case llvm::BitstreamEntry::Error:
7673 Error("malformed block record in AST file");
7674 return;
7675 case llvm::BitstreamEntry::EndBlock:
7676 goto NextCursor;
7677 case llvm::BitstreamEntry::Record:
7678 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007679 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 }
7681
7682 // Read a record.
7683 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007684 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 case COMMENTS_RAW_COMMENT: {
7686 unsigned Idx = 0;
7687 SourceRange SR = ReadSourceRange(F, Record, Idx);
7688 RawComment::CommentKind Kind =
7689 (RawComment::CommentKind) Record[Idx++];
7690 bool IsTrailingComment = Record[Idx++];
7691 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007692 Comments.push_back(new (Context) RawComment(
7693 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7694 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007695 break;
7696 }
7697 }
7698 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007699 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 }
7701 Context.Comments.addCommentsToFront(Comments);
7702}
7703
7704void ASTReader::finishPendingActions() {
7705 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007706 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7707 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 // If any identifiers with corresponding top-level declarations have
7709 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007710 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7711 TopLevelDeclsMap;
7712 TopLevelDeclsMap TopLevelDecls;
7713
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007715 // FIXME: std::move
7716 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7717 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007718 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007719
7720 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 }
7722
7723 // Load pending declaration chains.
7724 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7725 loadPendingDeclChain(PendingDeclChains[I]);
7726 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7727 }
7728 PendingDeclChains.clear();
7729
Douglas Gregor6168bd22013-02-18 15:53:43 +00007730 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007731 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7732 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007733 IdentifierInfo *II = TLD->first;
7734 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007735 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007736 }
7737 }
7738
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 // Load any pending macro definitions.
7740 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007741 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7742 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7743 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7744 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007745 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007746 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007747 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7748 if (Info.M->Kind != MK_Module)
7749 resolvePendingMacro(II, Info);
7750 }
7751 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007752 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007753 ++IDIdx) {
7754 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7755 if (Info.M->Kind == MK_Module)
7756 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 }
7758 }
7759 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007760
7761 // Wire up the DeclContexts for Decls that we delayed setting until
7762 // recursive loading is completed.
7763 while (!PendingDeclContextInfos.empty()) {
7764 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7765 PendingDeclContextInfos.pop_front();
7766 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7767 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7768 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7769 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007770
7771 // For each declaration from a merged context, check that the canonical
7772 // definition of that context also contains a declaration of the same
7773 // entity.
7774 while (!PendingOdrMergeChecks.empty()) {
7775 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7776
7777 // FIXME: Skip over implicit declarations for now. This matters for things
7778 // like implicitly-declared special member functions. This isn't entirely
7779 // correct; we can end up with multiple unmerged declarations of the same
7780 // implicit entity.
7781 if (D->isImplicit())
7782 continue;
7783
7784 DeclContext *CanonDef = D->getDeclContext();
7785 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7786
7787 bool Found = false;
7788 const Decl *DCanon = D->getCanonicalDecl();
7789
7790 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7791 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7792 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007793 for (auto RI : (*I)->redecls()) {
7794 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007795 // This declaration is present in the canonical definition. If it's
7796 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007797 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007798 Found = true;
7799 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007800 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007801 break;
7802 }
7803 }
7804 }
7805
7806 if (!Found) {
7807 D->setInvalidDecl();
7808
7809 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7810 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7811 << D << D->getOwningModule()->getFullModuleName()
7812 << CanonDef << !CanonDefModule
7813 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7814
7815 if (Candidates.empty())
7816 Diag(cast<Decl>(CanonDef)->getLocation(),
7817 diag::note_module_odr_violation_no_possible_decls) << D;
7818 else {
7819 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7820 Diag(Candidates[I]->getLocation(),
7821 diag::note_module_odr_violation_possible_decl)
7822 << Candidates[I];
7823 }
7824 }
7825 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 }
7827
7828 // If we deserialized any C++ or Objective-C class definitions, any
7829 // Objective-C protocol definitions, or any redeclarable templates, make sure
7830 // that all redeclarations point to the definitions. Note that this can only
7831 // happen now, after the redeclaration chains have been fully wired.
7832 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7833 DEnd = PendingDefinitions.end();
7834 D != DEnd; ++D) {
7835 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7836 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7837 // Make sure that the TagType points at the definition.
7838 const_cast<TagType*>(TagT)->decl = TD;
7839 }
7840
Aaron Ballman86c93902014-03-06 23:45:36 +00007841 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7842 for (auto R : RD->redecls())
7843 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00007844
7845 }
7846
7847 continue;
7848 }
7849
Aaron Ballman86c93902014-03-06 23:45:36 +00007850 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 // Make sure that the ObjCInterfaceType points at the definition.
7852 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7853 ->Decl = ID;
7854
Aaron Ballman86c93902014-03-06 23:45:36 +00007855 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 R->Data = ID->Data;
7857
7858 continue;
7859 }
7860
Aaron Ballman86c93902014-03-06 23:45:36 +00007861 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7862 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007863 R->Data = PD->Data;
7864
7865 continue;
7866 }
7867
Aaron Ballman86c93902014-03-06 23:45:36 +00007868 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7869 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 R->Common = RTD->Common;
7871 }
7872 PendingDefinitions.clear();
7873
7874 // Load the bodies of any functions or methods we've encountered. We do
7875 // this now (delayed) so that we can be sure that the declaration chains
7876 // have been fully wired up.
7877 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7878 PBEnd = PendingBodies.end();
7879 PB != PBEnd; ++PB) {
7880 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7881 // FIXME: Check for =delete/=default?
7882 // FIXME: Complain about ODR violations here?
7883 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7884 FD->setLazyBody(PB->second);
7885 continue;
7886 }
7887
7888 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7889 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7890 MD->setLazyBody(PB->second);
7891 }
7892 PendingBodies.clear();
7893}
7894
7895void ASTReader::FinishedDeserializing() {
7896 assert(NumCurrentElementsDeserializing &&
7897 "FinishedDeserializing not paired with StartedDeserializing");
7898 if (NumCurrentElementsDeserializing == 1) {
7899 // We decrease NumCurrentElementsDeserializing only after pending actions
7900 // are finished, to avoid recursively re-calling finishPendingActions().
7901 finishPendingActions();
7902 }
7903 --NumCurrentElementsDeserializing;
7904
7905 if (NumCurrentElementsDeserializing == 0 &&
7906 Consumer && !PassingDeclsToConsumer) {
7907 // Guard variable to avoid recursively redoing the process of passing
7908 // decls to consumer.
7909 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7910 true);
7911
7912 while (!InterestingDecls.empty()) {
7913 // We are not in recursive loading, so it's safe to pass the "interesting"
7914 // decls to the consumer.
7915 Decl *D = InterestingDecls.front();
7916 InterestingDecls.pop_front();
7917 PassInterestingDeclToConsumer(D);
7918 }
7919 }
7920}
7921
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007922void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007923 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007924
7925 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7926 SemaObj->TUScope->AddDecl(D);
7927 } else if (SemaObj->TUScope) {
7928 // Adding the decl to IdResolver may have failed because it was already in
7929 // (even though it was not added in scope). If it is already in, make sure
7930 // it gets in the scope as well.
7931 if (std::find(SemaObj->IdResolver.begin(Name),
7932 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7933 SemaObj->TUScope->AddDecl(D);
7934 }
7935}
7936
Guy Benyei11169dd2012-12-18 14:30:41 +00007937ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7938 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007939 bool AllowASTWithCompilerErrors,
7940 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007941 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007942 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007943 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7944 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7945 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7946 Consumer(0), ModuleMgr(PP.getFileManager()),
7947 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007948 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007949 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007950 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007951 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007952 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7953 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007954 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7955 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7956 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007957 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7958 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7959 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007960 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7961 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7962 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7963 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007964 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007965{
7966 SourceMgr.setExternalSLocEntrySource(this);
7967}
7968
7969ASTReader::~ASTReader() {
7970 for (DeclContextVisibleUpdatesPending::iterator
7971 I = PendingVisibleUpdates.begin(),
7972 E = PendingVisibleUpdates.end();
7973 I != E; ++I) {
7974 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7975 F = I->second.end();
7976 J != F; ++J)
7977 delete J->first;
7978 }
7979}