blob: 7e31723b165e2540439656e5058b234744eade86 [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,
122 bool isSystem) {
123 return First->visitInputFile(Filename, isSystem) ||
124 Second->visitInputFile(Filename, isSystem);
125}
126
Guy Benyei11169dd2012-12-18 14:30:41 +0000127//===----------------------------------------------------------------------===//
128// PCH validator implementation
129//===----------------------------------------------------------------------===//
130
131ASTReaderListener::~ASTReaderListener() {}
132
133/// \brief Compare the given set of language options against an existing set of
134/// language options.
135///
136/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
137///
138/// \returns true if the languagae options mis-match, false otherwise.
139static bool checkLanguageOptions(const LangOptions &LangOpts,
140 const LangOptions &ExistingLangOpts,
141 DiagnosticsEngine *Diags) {
142#define LANGOPT(Name, Bits, Default, Description) \
143 if (ExistingLangOpts.Name != LangOpts.Name) { \
144 if (Diags) \
145 Diags->Report(diag::err_pch_langopt_mismatch) \
146 << Description << LangOpts.Name << ExistingLangOpts.Name; \
147 return true; \
148 }
149
150#define VALUE_LANGOPT(Name, Bits, Default, Description) \
151 if (ExistingLangOpts.Name != LangOpts.Name) { \
152 if (Diags) \
153 Diags->Report(diag::err_pch_langopt_value_mismatch) \
154 << Description; \
155 return true; \
156 }
157
158#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
159 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
160 if (Diags) \
161 Diags->Report(diag::err_pch_langopt_value_mismatch) \
162 << Description; \
163 return true; \
164 }
165
166#define BENIGN_LANGOPT(Name, Bits, Default, Description)
167#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
168#include "clang/Basic/LangOptions.def"
169
170 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
171 if (Diags)
172 Diags->Report(diag::err_pch_langopt_value_mismatch)
173 << "target Objective-C runtime";
174 return true;
175 }
176
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000177 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
178 LangOpts.CommentOpts.BlockCommandNames) {
179 if (Diags)
180 Diags->Report(diag::err_pch_langopt_value_mismatch)
181 << "block command names";
182 return true;
183 }
184
Guy Benyei11169dd2012-12-18 14:30:41 +0000185 return false;
186}
187
188/// \brief Compare the given set of target options against an existing set of
189/// target options.
190///
191/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
192///
193/// \returns true if the target options mis-match, false otherwise.
194static bool checkTargetOptions(const TargetOptions &TargetOpts,
195 const TargetOptions &ExistingTargetOpts,
196 DiagnosticsEngine *Diags) {
197#define CHECK_TARGET_OPT(Field, Name) \
198 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
199 if (Diags) \
200 Diags->Report(diag::err_pch_targetopt_mismatch) \
201 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
202 return true; \
203 }
204
205 CHECK_TARGET_OPT(Triple, "target");
206 CHECK_TARGET_OPT(CPU, "target CPU");
207 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000208 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
209#undef CHECK_TARGET_OPT
210
211 // Compare feature sets.
212 SmallVector<StringRef, 4> ExistingFeatures(
213 ExistingTargetOpts.FeaturesAsWritten.begin(),
214 ExistingTargetOpts.FeaturesAsWritten.end());
215 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
216 TargetOpts.FeaturesAsWritten.end());
217 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
218 std::sort(ReadFeatures.begin(), ReadFeatures.end());
219
220 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
221 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
222 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
223 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
224 ++ExistingIdx;
225 ++ReadIdx;
226 continue;
227 }
228
229 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
230 if (Diags)
231 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
232 << false << ReadFeatures[ReadIdx];
233 return true;
234 }
235
236 if (Diags)
237 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
238 << true << ExistingFeatures[ExistingIdx];
239 return true;
240 }
241
242 if (ExistingIdx < ExistingN) {
243 if (Diags)
244 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
245 << true << ExistingFeatures[ExistingIdx];
246 return true;
247 }
248
249 if (ReadIdx < ReadN) {
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << false << ReadFeatures[ReadIdx];
253 return true;
254 }
255
256 return false;
257}
258
259bool
260PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
261 bool Complain) {
262 const LangOptions &ExistingLangOpts = PP.getLangOpts();
263 return checkLanguageOptions(LangOpts, ExistingLangOpts,
264 Complain? &Reader.Diags : 0);
265}
266
267bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
268 bool Complain) {
269 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
270 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
271 Complain? &Reader.Diags : 0);
272}
273
274namespace {
275 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
276 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000277 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
278 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000279}
280
281/// \brief Collect the macro definitions provided by the given preprocessor
282/// options.
283static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
284 MacroDefinitionsMap &Macros,
285 SmallVectorImpl<StringRef> *MacroNames = 0){
286 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
287 StringRef Macro = PPOpts.Macros[I].first;
288 bool IsUndef = PPOpts.Macros[I].second;
289
290 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
291 StringRef MacroName = MacroPair.first;
292 StringRef MacroBody = MacroPair.second;
293
294 // For an #undef'd macro, we only care about the name.
295 if (IsUndef) {
296 if (MacroNames && !Macros.count(MacroName))
297 MacroNames->push_back(MacroName);
298
299 Macros[MacroName] = std::make_pair("", true);
300 continue;
301 }
302
303 // For a #define'd macro, figure out the actual definition.
304 if (MacroName.size() == Macro.size())
305 MacroBody = "1";
306 else {
307 // Note: GCC drops anything following an end-of-line character.
308 StringRef::size_type End = MacroBody.find_first_of("\n\r");
309 MacroBody = MacroBody.substr(0, End);
310 }
311
312 if (MacroNames && !Macros.count(MacroName))
313 MacroNames->push_back(MacroName);
314 Macros[MacroName] = std::make_pair(MacroBody, false);
315 }
316}
317
318/// \brief Check the preprocessor options deserialized from the control block
319/// against the preprocessor options in an existing preprocessor.
320///
321/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
322static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
323 const PreprocessorOptions &ExistingPPOpts,
324 DiagnosticsEngine *Diags,
325 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000326 std::string &SuggestedPredefines,
327 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000328 // Check macro definitions.
329 MacroDefinitionsMap ASTFileMacros;
330 collectMacroDefinitions(PPOpts, ASTFileMacros);
331 MacroDefinitionsMap ExistingMacros;
332 SmallVector<StringRef, 4> ExistingMacroNames;
333 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
334
335 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
336 // Dig out the macro definition in the existing preprocessor options.
337 StringRef MacroName = ExistingMacroNames[I];
338 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
339
340 // Check whether we know anything about this macro name or not.
341 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
342 = ASTFileMacros.find(MacroName);
343 if (Known == ASTFileMacros.end()) {
344 // FIXME: Check whether this identifier was referenced anywhere in the
345 // AST file. If so, we should reject the AST file. Unfortunately, this
346 // information isn't in the control block. What shall we do about it?
347
348 if (Existing.second) {
349 SuggestedPredefines += "#undef ";
350 SuggestedPredefines += MacroName.str();
351 SuggestedPredefines += '\n';
352 } else {
353 SuggestedPredefines += "#define ";
354 SuggestedPredefines += MacroName.str();
355 SuggestedPredefines += ' ';
356 SuggestedPredefines += Existing.first.str();
357 SuggestedPredefines += '\n';
358 }
359 continue;
360 }
361
362 // If the macro was defined in one but undef'd in the other, we have a
363 // conflict.
364 if (Existing.second != Known->second.second) {
365 if (Diags) {
366 Diags->Report(diag::err_pch_macro_def_undef)
367 << MacroName << Known->second.second;
368 }
369 return true;
370 }
371
372 // If the macro was #undef'd in both, or if the macro bodies are identical,
373 // it's fine.
374 if (Existing.second || Existing.first == Known->second.first)
375 continue;
376
377 // The macro bodies differ; complain.
378 if (Diags) {
379 Diags->Report(diag::err_pch_macro_def_conflict)
380 << MacroName << Known->second.first << Existing.first;
381 }
382 return true;
383 }
384
385 // Check whether we're using predefines.
386 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
387 if (Diags) {
388 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
389 }
390 return true;
391 }
392
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000393 // Detailed record is important since it is used for the module cache hash.
394 if (LangOpts.Modules &&
395 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
396 if (Diags) {
397 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
398 }
399 return true;
400 }
401
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 // Compute the #include and #include_macros lines we need.
403 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
404 StringRef File = ExistingPPOpts.Includes[I];
405 if (File == ExistingPPOpts.ImplicitPCHInclude)
406 continue;
407
408 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
409 != PPOpts.Includes.end())
410 continue;
411
412 SuggestedPredefines += "#include \"";
413 SuggestedPredefines +=
414 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
415 SuggestedPredefines += "\"\n";
416 }
417
418 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
419 StringRef File = ExistingPPOpts.MacroIncludes[I];
420 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
421 File)
422 != PPOpts.MacroIncludes.end())
423 continue;
424
425 SuggestedPredefines += "#__include_macros \"";
426 SuggestedPredefines +=
427 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
428 SuggestedPredefines += "\"\n##\n";
429 }
430
431 return false;
432}
433
434bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
435 bool Complain,
436 std::string &SuggestedPredefines) {
437 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
438
439 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
440 Complain? &Reader.Diags : 0,
441 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000442 SuggestedPredefines,
443 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000444}
445
Guy Benyei11169dd2012-12-18 14:30:41 +0000446void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
447 PP.setCounterValue(Value);
448}
449
450//===----------------------------------------------------------------------===//
451// AST reader implementation
452//===----------------------------------------------------------------------===//
453
454void
455ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
456 DeserializationListener = Listener;
457}
458
459
460
461unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
462 return serialization::ComputeHash(Sel);
463}
464
465
466std::pair<unsigned, unsigned>
467ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
468 using namespace clang::io;
469 unsigned KeyLen = ReadUnalignedLE16(d);
470 unsigned DataLen = ReadUnalignedLE16(d);
471 return std::make_pair(KeyLen, DataLen);
472}
473
474ASTSelectorLookupTrait::internal_key_type
475ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
476 using namespace clang::io;
477 SelectorTable &SelTable = Reader.getContext().Selectors;
478 unsigned N = ReadUnalignedLE16(d);
479 IdentifierInfo *FirstII
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000480 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 if (N == 0)
482 return SelTable.getNullarySelector(FirstII);
483 else if (N == 1)
484 return SelTable.getUnarySelector(FirstII);
485
486 SmallVector<IdentifierInfo *, 16> Args;
487 Args.push_back(FirstII);
488 for (unsigned I = 1; I != N; ++I)
Douglas Gregorc8a992f2013-01-21 16:52:34 +0000489 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000490
491 return SelTable.getSelector(N, Args.data());
492}
493
494ASTSelectorLookupTrait::data_type
495ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
496 unsigned DataLen) {
497 using namespace clang::io;
498
499 data_type Result;
500
501 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000502 unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
503 unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
504 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
505 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
506 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
507 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000508
509 // Load instance methods
510 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
511 if (ObjCMethodDecl *Method
512 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
513 Result.Instance.push_back(Method);
514 }
515
516 // Load factory methods
517 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
518 if (ObjCMethodDecl *Method
519 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
520 Result.Factory.push_back(Method);
521 }
522
523 return Result;
524}
525
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000526unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
527 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000528}
529
530std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000531ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 using namespace clang::io;
533 unsigned DataLen = ReadUnalignedLE16(d);
534 unsigned KeyLen = ReadUnalignedLE16(d);
535 return std::make_pair(KeyLen, DataLen);
536}
537
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000538ASTIdentifierLookupTraitBase::internal_key_type
539ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000540 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000541 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000542}
543
Douglas Gregordcf25082013-02-11 18:16:18 +0000544/// \brief Whether the given identifier is "interesting".
545static bool isInterestingIdentifier(IdentifierInfo &II) {
546 return II.isPoisoned() ||
547 II.isExtensionToken() ||
548 II.getObjCOrBuiltinID() ||
549 II.hasRevertedTokenIDToIdentifier() ||
550 II.hadMacroDefinition() ||
551 II.getFETokenInfo<void>();
552}
553
Guy Benyei11169dd2012-12-18 14:30:41 +0000554IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
555 const unsigned char* d,
556 unsigned DataLen) {
557 using namespace clang::io;
558 unsigned RawID = ReadUnalignedLE32(d);
559 bool IsInteresting = RawID & 0x01;
560
561 // Wipe out the "is interesting" bit.
562 RawID = RawID >> 1;
563
564 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
565 if (!IsInteresting) {
566 // For uninteresting identifiers, just build the IdentifierInfo
567 // and associate it with the persistent ID.
568 IdentifierInfo *II = KnownII;
569 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000570 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000571 KnownII = II;
572 }
573 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000574 if (!II->isFromAST()) {
575 bool WasInteresting = isInterestingIdentifier(*II);
576 II->setIsFromAST();
577 if (WasInteresting)
578 II->setChangedSinceDeserialization();
579 }
580 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 return II;
582 }
583
584 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
585 unsigned Bits = ReadUnalignedLE16(d);
586 bool CPlusPlusOperatorKeyword = Bits & 0x01;
587 Bits >>= 1;
588 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
589 Bits >>= 1;
590 bool Poisoned = Bits & 0x01;
591 Bits >>= 1;
592 bool ExtensionToken = Bits & 0x01;
593 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000594 bool hasSubmoduleMacros = Bits & 0x01;
595 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000596 bool hadMacroDefinition = Bits & 0x01;
597 Bits >>= 1;
598
599 assert(Bits == 0 && "Extra bits in the identifier?");
600 DataLen -= 8;
601
602 // Build the IdentifierInfo itself and link the identifier ID with
603 // the new IdentifierInfo.
604 IdentifierInfo *II = KnownII;
605 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000606 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 KnownII = II;
608 }
609 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000610 if (!II->isFromAST()) {
611 bool WasInteresting = isInterestingIdentifier(*II);
612 II->setIsFromAST();
613 if (WasInteresting)
614 II->setChangedSinceDeserialization();
615 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000616
617 // Set or check the various bits in the IdentifierInfo structure.
618 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000619 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 II->RevertTokenIDToIdentifier();
621 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
622 assert(II->isExtensionToken() == ExtensionToken &&
623 "Incorrect extension token flag");
624 (void)ExtensionToken;
625 if (Poisoned)
626 II->setIsPoisoned(true);
627 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
628 "Incorrect C++ operator keyword flag");
629 (void)CPlusPlusOperatorKeyword;
630
631 // If this identifier is a macro, deserialize the macro
632 // definition.
633 if (hadMacroDefinition) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000634 uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
635 DataLen -= 4;
636 SmallVector<uint32_t, 8> LocalMacroIDs;
637 if (hasSubmoduleMacros) {
638 while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
639 DataLen -= 4;
640 LocalMacroIDs.push_back(LocalMacroID);
641 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000642 DataLen -= 4;
643 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000644
645 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000646 // Macro definitions are stored from newest to oldest, so reverse them
647 // before registering them.
648 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000649 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000650 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
651 unsigned Size = 1;
652
653 static const uint32_t HasOverridesFlag = 0x80000000U;
654 if (I + 1 != E && (I[1] & HasOverridesFlag))
655 Size += 1 + (I[1] & ~HasOverridesFlag);
656
657 MacroSizes.push_back(Size);
658 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000659 }
Richard Smith49f906a2014-03-01 00:08:04 +0000660
661 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
662 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
663 SE = MacroSizes.rend();
664 SI != SE; ++SI) {
665 I -= *SI;
666
667 uint32_t LocalMacroID = *I;
668 llvm::ArrayRef<uint32_t> Overrides;
669 if (*SI != 1)
670 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
671 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
672 }
673 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000674 } else {
675 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
676 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000677 }
678
679 Reader.SetIdentifierInfo(ID, II);
680
681 // Read all of the declarations visible at global scope with this
682 // name.
683 if (DataLen > 0) {
684 SmallVector<uint32_t, 4> DeclIDs;
685 for (; DataLen > 0; DataLen -= 4)
686 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
687 Reader.SetGloballyVisibleDecls(II, DeclIDs);
688 }
689
690 return II;
691}
692
693unsigned
694ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
695 llvm::FoldingSetNodeID ID;
696 ID.AddInteger(Key.Kind);
697
698 switch (Key.Kind) {
699 case DeclarationName::Identifier:
700 case DeclarationName::CXXLiteralOperatorName:
701 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
702 break;
703 case DeclarationName::ObjCZeroArgSelector:
704 case DeclarationName::ObjCOneArgSelector:
705 case DeclarationName::ObjCMultiArgSelector:
706 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
707 break;
708 case DeclarationName::CXXOperatorName:
709 ID.AddInteger((OverloadedOperatorKind)Key.Data);
710 break;
711 case DeclarationName::CXXConstructorName:
712 case DeclarationName::CXXDestructorName:
713 case DeclarationName::CXXConversionFunctionName:
714 case DeclarationName::CXXUsingDirective:
715 break;
716 }
717
718 return ID.ComputeHash();
719}
720
721ASTDeclContextNameLookupTrait::internal_key_type
722ASTDeclContextNameLookupTrait::GetInternalKey(
723 const external_key_type& Name) const {
724 DeclNameKey Key;
725 Key.Kind = Name.getNameKind();
726 switch (Name.getNameKind()) {
727 case DeclarationName::Identifier:
728 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
729 break;
730 case DeclarationName::ObjCZeroArgSelector:
731 case DeclarationName::ObjCOneArgSelector:
732 case DeclarationName::ObjCMultiArgSelector:
733 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
734 break;
735 case DeclarationName::CXXOperatorName:
736 Key.Data = Name.getCXXOverloadedOperator();
737 break;
738 case DeclarationName::CXXLiteralOperatorName:
739 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
740 break;
741 case DeclarationName::CXXConstructorName:
742 case DeclarationName::CXXDestructorName:
743 case DeclarationName::CXXConversionFunctionName:
744 case DeclarationName::CXXUsingDirective:
745 Key.Data = 0;
746 break;
747 }
748
749 return Key;
750}
751
752std::pair<unsigned, unsigned>
753ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
754 using namespace clang::io;
755 unsigned KeyLen = ReadUnalignedLE16(d);
756 unsigned DataLen = ReadUnalignedLE16(d);
757 return std::make_pair(KeyLen, DataLen);
758}
759
760ASTDeclContextNameLookupTrait::internal_key_type
761ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
762 using namespace clang::io;
763
764 DeclNameKey Key;
765 Key.Kind = (DeclarationName::NameKind)*d++;
766 switch (Key.Kind) {
767 case DeclarationName::Identifier:
768 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
769 break;
770 case DeclarationName::ObjCZeroArgSelector:
771 case DeclarationName::ObjCOneArgSelector:
772 case DeclarationName::ObjCMultiArgSelector:
773 Key.Data =
774 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
775 .getAsOpaquePtr();
776 break;
777 case DeclarationName::CXXOperatorName:
778 Key.Data = *d++; // OverloadedOperatorKind
779 break;
780 case DeclarationName::CXXLiteralOperatorName:
781 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
782 break;
783 case DeclarationName::CXXConstructorName:
784 case DeclarationName::CXXDestructorName:
785 case DeclarationName::CXXConversionFunctionName:
786 case DeclarationName::CXXUsingDirective:
787 Key.Data = 0;
788 break;
789 }
790
791 return Key;
792}
793
794ASTDeclContextNameLookupTrait::data_type
795ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
796 const unsigned char* d,
797 unsigned DataLen) {
798 using namespace clang::io;
799 unsigned NumDecls = ReadUnalignedLE16(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000800 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
801 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000802 return std::make_pair(Start, Start + NumDecls);
803}
804
805bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000806 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 const std::pair<uint64_t, uint64_t> &Offsets,
808 DeclContextInfo &Info) {
809 SavedStreamPosition SavedPosition(Cursor);
810 // First the lexical decls.
811 if (Offsets.first != 0) {
812 Cursor.JumpToBit(Offsets.first);
813
814 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000815 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000817 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000818 if (RecCode != DECL_CONTEXT_LEXICAL) {
819 Error("Expected lexical block");
820 return true;
821 }
822
Chris Lattner0e6c9402013-01-20 02:38:54 +0000823 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
824 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 }
826
827 // Now the lookup table.
828 if (Offsets.second != 0) {
829 Cursor.JumpToBit(Offsets.second);
830
831 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000832 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000834 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 if (RecCode != DECL_CONTEXT_VISIBLE) {
836 Error("Expected visible lookup table block");
837 return true;
838 }
839 Info.NameLookupTableData
840 = ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +0000841 (const unsigned char *)Blob.data() + Record[0],
842 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 ASTDeclContextNameLookupTrait(*this, M));
844 }
845
846 return false;
847}
848
849void ASTReader::Error(StringRef Msg) {
850 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000851 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
852 Diag(diag::note_module_cache_path)
853 << PP.getHeaderSearchInfo().getModuleCachePath();
854 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000855}
856
857void ASTReader::Error(unsigned DiagID,
858 StringRef Arg1, StringRef Arg2) {
859 if (Diags.isDiagnosticInFlight())
860 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
861 else
862 Diag(DiagID) << Arg1 << Arg2;
863}
864
865//===----------------------------------------------------------------------===//
866// Source Manager Deserialization
867//===----------------------------------------------------------------------===//
868
869/// \brief Read the line table in the source manager block.
870/// \returns true if there was an error.
871bool ASTReader::ParseLineTable(ModuleFile &F,
872 SmallVectorImpl<uint64_t> &Record) {
873 unsigned Idx = 0;
874 LineTableInfo &LineTable = SourceMgr.getLineTable();
875
876 // Parse the file names
877 std::map<int, int> FileIDs;
878 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
879 // Extract the file name
880 unsigned FilenameLen = Record[Idx++];
881 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
882 Idx += FilenameLen;
883 MaybeAddSystemRootToFilename(F, Filename);
884 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
885 }
886
887 // Parse the line entries
888 std::vector<LineEntry> Entries;
889 while (Idx < Record.size()) {
890 int FID = Record[Idx++];
891 assert(FID >= 0 && "Serialized line entries for non-local file.");
892 // Remap FileID from 1-based old view.
893 FID += F.SLocEntryBaseID - 1;
894
895 // Extract the line entries
896 unsigned NumEntries = Record[Idx++];
897 assert(NumEntries && "Numentries is 00000");
898 Entries.clear();
899 Entries.reserve(NumEntries);
900 for (unsigned I = 0; I != NumEntries; ++I) {
901 unsigned FileOffset = Record[Idx++];
902 unsigned LineNo = Record[Idx++];
903 int FilenameID = FileIDs[Record[Idx++]];
904 SrcMgr::CharacteristicKind FileKind
905 = (SrcMgr::CharacteristicKind)Record[Idx++];
906 unsigned IncludeOffset = Record[Idx++];
907 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
908 FileKind, IncludeOffset));
909 }
910 LineTable.AddEntry(FileID::get(FID), Entries);
911 }
912
913 return false;
914}
915
916/// \brief Read a source manager block
917bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
918 using namespace SrcMgr;
919
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000920 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000921
922 // Set the source-location entry cursor to the current position in
923 // the stream. This cursor will be used to read the contents of the
924 // source manager block initially, and then lazily read
925 // source-location entries as needed.
926 SLocEntryCursor = F.Stream;
927
928 // The stream itself is going to skip over the source manager block.
929 if (F.Stream.SkipBlock()) {
930 Error("malformed block record in AST file");
931 return true;
932 }
933
934 // Enter the source manager block.
935 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
936 Error("malformed source manager block record in AST file");
937 return true;
938 }
939
940 RecordData Record;
941 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +0000942 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
943
944 switch (E.Kind) {
945 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
946 case llvm::BitstreamEntry::Error:
947 Error("malformed block record in AST file");
948 return true;
949 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +0000951 case llvm::BitstreamEntry::Record:
952 // The interesting case.
953 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 }
Chris Lattnere7b154b2013-01-19 21:39:22 +0000955
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +0000958 StringRef Blob;
959 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 default: // Default behavior: ignore.
961 break;
962
963 case SM_SLOC_FILE_ENTRY:
964 case SM_SLOC_BUFFER_ENTRY:
965 case SM_SLOC_EXPANSION_ENTRY:
966 // Once we hit one of the source location entries, we're done.
967 return false;
968 }
969 }
970}
971
972/// \brief If a header file is not found at the path that we expect it to be
973/// and the PCH file was moved from its original location, try to resolve the
974/// file by assuming that header+PCH were moved together and the header is in
975/// the same place relative to the PCH.
976static std::string
977resolveFileRelativeToOriginalDir(const std::string &Filename,
978 const std::string &OriginalDir,
979 const std::string &CurrDir) {
980 assert(OriginalDir != CurrDir &&
981 "No point trying to resolve the file if the PCH dir didn't change");
982 using namespace llvm::sys;
983 SmallString<128> filePath(Filename);
984 fs::make_absolute(filePath);
985 assert(path::is_absolute(OriginalDir));
986 SmallString<128> currPCHPath(CurrDir);
987
988 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
989 fileDirE = path::end(path::parent_path(filePath));
990 path::const_iterator origDirI = path::begin(OriginalDir),
991 origDirE = path::end(OriginalDir);
992 // Skip the common path components from filePath and OriginalDir.
993 while (fileDirI != fileDirE && origDirI != origDirE &&
994 *fileDirI == *origDirI) {
995 ++fileDirI;
996 ++origDirI;
997 }
998 for (; origDirI != origDirE; ++origDirI)
999 path::append(currPCHPath, "..");
1000 path::append(currPCHPath, fileDirI, fileDirE);
1001 path::append(currPCHPath, path::filename(Filename));
1002 return currPCHPath.str();
1003}
1004
1005bool ASTReader::ReadSLocEntry(int ID) {
1006 if (ID == 0)
1007 return false;
1008
1009 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1010 Error("source location entry ID out-of-range for AST file");
1011 return true;
1012 }
1013
1014 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1015 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001016 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001017 unsigned BaseOffset = F->SLocEntryBaseOffset;
1018
1019 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001020 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1021 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 Error("incorrectly-formatted source location entry in AST file");
1023 return true;
1024 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001025
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001027 StringRef Blob;
1028 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 default:
1030 Error("incorrectly-formatted source location entry in AST file");
1031 return true;
1032
1033 case SM_SLOC_FILE_ENTRY: {
1034 // We will detect whether a file changed and return 'Failure' for it, but
1035 // we will also try to fail gracefully by setting up the SLocEntry.
1036 unsigned InputID = Record[4];
1037 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001038 const FileEntry *File = IF.getFile();
1039 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001040
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001041 // Note that we only check if a File was returned. If it was out-of-date
1042 // we have complained but we will continue creating a FileID to recover
1043 // gracefully.
1044 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 return true;
1046
1047 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1048 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1049 // This is the module's main file.
1050 IncludeLoc = getImportLocation(F);
1051 }
1052 SrcMgr::CharacteristicKind
1053 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1054 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1055 ID, BaseOffset + Record[0]);
1056 SrcMgr::FileInfo &FileInfo =
1057 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1058 FileInfo.NumCreatedFIDs = Record[5];
1059 if (Record[3])
1060 FileInfo.setHasLineDirectives();
1061
1062 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1063 unsigned NumFileDecls = Record[7];
1064 if (NumFileDecls) {
1065 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1066 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1067 NumFileDecls));
1068 }
1069
1070 const SrcMgr::ContentCache *ContentCache
1071 = SourceMgr.getOrCreateContentCache(File,
1072 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1073 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1074 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1075 unsigned Code = SLocEntryCursor.ReadCode();
1076 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001077 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001078
1079 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1080 Error("AST record has invalid code");
1081 return true;
1082 }
1083
1084 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001085 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001086 SourceMgr.overrideFileContents(File, Buffer);
1087 }
1088
1089 break;
1090 }
1091
1092 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001093 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 unsigned Offset = Record[0];
1095 SrcMgr::CharacteristicKind
1096 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1097 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1098 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1099 IncludeLoc = getImportLocation(F);
1100 }
1101 unsigned Code = SLocEntryCursor.ReadCode();
1102 Record.clear();
1103 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001104 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001105
1106 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1107 Error("AST record has invalid code");
1108 return true;
1109 }
1110
1111 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001112 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1114 BaseOffset + Offset, IncludeLoc);
1115 break;
1116 }
1117
1118 case SM_SLOC_EXPANSION_ENTRY: {
1119 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1120 SourceMgr.createExpansionLoc(SpellingLoc,
1121 ReadSourceLocation(*F, Record[2]),
1122 ReadSourceLocation(*F, Record[3]),
1123 Record[4],
1124 ID,
1125 BaseOffset + Record[0]);
1126 break;
1127 }
1128 }
1129
1130 return false;
1131}
1132
1133std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1134 if (ID == 0)
1135 return std::make_pair(SourceLocation(), "");
1136
1137 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1138 Error("source location entry ID out-of-range for AST file");
1139 return std::make_pair(SourceLocation(), "");
1140 }
1141
1142 // Find which module file this entry lands in.
1143 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1144 if (M->Kind != MK_Module)
1145 return std::make_pair(SourceLocation(), "");
1146
1147 // FIXME: Can we map this down to a particular submodule? That would be
1148 // ideal.
1149 return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1150}
1151
1152/// \brief Find the location where the module F is imported.
1153SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1154 if (F->ImportLoc.isValid())
1155 return F->ImportLoc;
1156
1157 // Otherwise we have a PCH. It's considered to be "imported" at the first
1158 // location of its includer.
1159 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1160 // Main file is the importer. We assume that it is the first entry in the
1161 // entry table. We can't ask the manager, because at the time of PCH loading
1162 // the main file entry doesn't exist yet.
1163 // The very first entry is the invalid instantiation loc, which takes up
1164 // offsets 0 and 1.
1165 return SourceLocation::getFromRawEncoding(2U);
1166 }
1167 //return F->Loaders[0]->FirstLoc;
1168 return F->ImportedBy[0]->FirstLoc;
1169}
1170
1171/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1172/// specified cursor. Read the abbreviations that are at the top of the block
1173/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001174bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 if (Cursor.EnterSubBlock(BlockID)) {
1176 Error("malformed block record in AST file");
1177 return Failure;
1178 }
1179
1180 while (true) {
1181 uint64_t Offset = Cursor.GetCurrentBitNo();
1182 unsigned Code = Cursor.ReadCode();
1183
1184 // We expect all abbrevs to be at the start of the block.
1185 if (Code != llvm::bitc::DEFINE_ABBREV) {
1186 Cursor.JumpToBit(Offset);
1187 return false;
1188 }
1189 Cursor.ReadAbbrevRecord();
1190 }
1191}
1192
Richard Smithe40f2ba2013-08-07 21:41:30 +00001193Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001194 unsigned &Idx) {
1195 Token Tok;
1196 Tok.startToken();
1197 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1198 Tok.setLength(Record[Idx++]);
1199 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1200 Tok.setIdentifierInfo(II);
1201 Tok.setKind((tok::TokenKind)Record[Idx++]);
1202 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1203 return Tok;
1204}
1205
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001206MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001207 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001208
1209 // Keep track of where we are in the stream, then jump back there
1210 // after reading this macro.
1211 SavedStreamPosition SavedPosition(Stream);
1212
1213 Stream.JumpToBit(Offset);
1214 RecordData Record;
1215 SmallVector<IdentifierInfo*, 16> MacroArgs;
1216 MacroInfo *Macro = 0;
1217
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001219 // Advance to the next record, but if we get to the end of the block, don't
1220 // pop it (removing all the abbreviations from the cursor) since we want to
1221 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001222 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001223 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1224
1225 switch (Entry.Kind) {
1226 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1227 case llvm::BitstreamEntry::Error:
1228 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001229 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001230 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001231 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001232 case llvm::BitstreamEntry::Record:
1233 // The interesting case.
1234 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 }
1236
1237 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001238 Record.clear();
1239 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001242 case PP_MACRO_DIRECTIVE_HISTORY:
1243 return Macro;
1244
Guy Benyei11169dd2012-12-18 14:30:41 +00001245 case PP_MACRO_OBJECT_LIKE:
1246 case PP_MACRO_FUNCTION_LIKE: {
1247 // If we already have a macro, that means that we've hit the end
1248 // of the definition of the macro we were looking for. We're
1249 // done.
1250 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001251 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001252
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001253 unsigned NextIndex = 1; // Skip identifier ID.
1254 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001256 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001257 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 MI->setIsUsed(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001259
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1261 // Decode function-like macro info.
1262 bool isC99VarArgs = Record[NextIndex++];
1263 bool isGNUVarArgs = Record[NextIndex++];
1264 bool hasCommaPasting = Record[NextIndex++];
1265 MacroArgs.clear();
1266 unsigned NumArgs = Record[NextIndex++];
1267 for (unsigned i = 0; i != NumArgs; ++i)
1268 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1269
1270 // Install function-like macro info.
1271 MI->setIsFunctionLike();
1272 if (isC99VarArgs) MI->setIsC99Varargs();
1273 if (isGNUVarArgs) MI->setIsGNUVarargs();
1274 if (hasCommaPasting) MI->setHasCommaPasting();
1275 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1276 PP.getPreprocessorAllocator());
1277 }
1278
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 // Remember that we saw this macro last so that we add the tokens that
1280 // form its body to it.
1281 Macro = MI;
1282
1283 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1284 Record[NextIndex]) {
1285 // We have a macro definition. Register the association
1286 PreprocessedEntityID
1287 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1288 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001289 PreprocessingRecord::PPEntityID
1290 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1291 MacroDefinition *PPDef =
1292 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1293 if (PPDef)
1294 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 }
1296
1297 ++NumMacrosRead;
1298 break;
1299 }
1300
1301 case PP_TOKEN: {
1302 // If we see a TOKEN before a PP_MACRO_*, then the file is
1303 // erroneous, just pretend we didn't see this.
1304 if (Macro == 0) break;
1305
John McCallf413f5e2013-05-03 00:10:13 +00001306 unsigned Idx = 0;
1307 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 Macro->AddTokenToBody(Tok);
1309 break;
1310 }
1311 }
1312 }
1313}
1314
1315PreprocessedEntityID
1316ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1317 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1318 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1319 assert(I != M.PreprocessedEntityRemap.end()
1320 && "Invalid index into preprocessed entity index remap");
1321
1322 return LocalID + I->second;
1323}
1324
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001325unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1326 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001327}
1328
1329HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001330HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1331 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1332 FE->getName() };
1333 return ikey;
1334}
Guy Benyei11169dd2012-12-18 14:30:41 +00001335
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001336bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1337 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 return false;
1339
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001340 if (strcmp(a.Filename, b.Filename) == 0)
1341 return true;
1342
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001344 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001345 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1346 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001347 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001348}
1349
1350std::pair<unsigned, unsigned>
1351HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1352 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1353 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001354 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001355}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001356
1357HeaderFileInfoTrait::internal_key_type
1358HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1359 internal_key_type ikey;
1360 ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1361 ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1362 ikey.Filename = (const char *)d;
1363 return ikey;
1364}
1365
Guy Benyei11169dd2012-12-18 14:30:41 +00001366HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001367HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 unsigned DataLen) {
1369 const unsigned char *End = d + DataLen;
1370 using namespace clang::io;
1371 HeaderFileInfo HFI;
1372 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001373 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1374 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 HFI.isImport = (Flags >> 5) & 0x01;
1376 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1377 HFI.DirInfo = (Flags >> 2) & 0x03;
1378 HFI.Resolved = (Flags >> 1) & 0x01;
1379 HFI.IndexHeaderMapHeader = Flags & 0x01;
1380 HFI.NumIncludes = ReadUnalignedLE16(d);
1381 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1382 ReadUnalignedLE32(d));
1383 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1384 // The framework offset is 1 greater than the actual offset,
1385 // since 0 is used as an indicator for "no framework name".
1386 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1387 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1388 }
1389
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001390 if (d != End) {
1391 uint32_t LocalSMID = ReadUnalignedLE32(d);
1392 if (LocalSMID) {
1393 // This header is part of a module. Associate it with the module to enable
1394 // implicit module import.
1395 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1396 Module *Mod = Reader.getSubmodule(GlobalSMID);
1397 HFI.isModuleHeader = true;
1398 FileManager &FileMgr = Reader.getFileManager();
1399 ModuleMap &ModMap =
1400 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001401 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001402 }
1403 }
1404
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1406 (void)End;
1407
1408 // This HeaderFileInfo was externally loaded.
1409 HFI.External = true;
1410 return HFI;
1411}
1412
Richard Smith49f906a2014-03-01 00:08:04 +00001413void
1414ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1415 GlobalMacroID GMacID,
1416 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001418 SubmoduleID *OverrideData = 0;
1419 if (!Overrides.empty()) {
1420 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1421 OverrideData[0] = Overrides.size();
1422 for (unsigned I = 0; I != Overrides.size(); ++I)
1423 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1424 }
1425 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001426}
1427
1428void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1429 ModuleFile *M,
1430 uint64_t MacroDirectivesOffset) {
1431 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1432 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001433}
1434
1435void ASTReader::ReadDefinedMacros() {
1436 // Note that we are loading defined macros.
1437 Deserializing Macros(this);
1438
1439 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1440 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001441 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001442
1443 // If there was no preprocessor block, skip this file.
1444 if (!MacroCursor.getBitStreamReader())
1445 continue;
1446
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001447 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 Cursor.JumpToBit((*I)->MacroStartOffset);
1449
1450 RecordData Record;
1451 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001452 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1453
1454 switch (E.Kind) {
1455 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1456 case llvm::BitstreamEntry::Error:
1457 Error("malformed block record in AST file");
1458 return;
1459 case llvm::BitstreamEntry::EndBlock:
1460 goto NextCursor;
1461
1462 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001463 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001464 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001465 default: // Default behavior: ignore.
1466 break;
1467
1468 case PP_MACRO_OBJECT_LIKE:
1469 case PP_MACRO_FUNCTION_LIKE:
1470 getLocalIdentifier(**I, Record[0]);
1471 break;
1472
1473 case PP_TOKEN:
1474 // Ignore tokens.
1475 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001476 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 break;
1478 }
1479 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001480 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001481 }
1482}
1483
1484namespace {
1485 /// \brief Visitor class used to look up identifirs in an AST file.
1486 class IdentifierLookupVisitor {
1487 StringRef Name;
1488 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001489 unsigned &NumIdentifierLookups;
1490 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001492
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001494 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1495 unsigned &NumIdentifierLookups,
1496 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001497 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001498 NumIdentifierLookups(NumIdentifierLookups),
1499 NumIdentifierLookupHits(NumIdentifierLookupHits),
1500 Found()
1501 {
1502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
1504 static bool visit(ModuleFile &M, void *UserData) {
1505 IdentifierLookupVisitor *This
1506 = static_cast<IdentifierLookupVisitor *>(UserData);
1507
1508 // If we've already searched this module file, skip it now.
1509 if (M.Generation <= This->PriorGeneration)
1510 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001511
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 ASTIdentifierLookupTable *IdTable
1513 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1514 if (!IdTable)
1515 return false;
1516
1517 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1518 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001519 ++This->NumIdentifierLookups;
1520 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 if (Pos == IdTable->end())
1522 return false;
1523
1524 // Dereferencing the iterator has the effect of building the
1525 // IdentifierInfo node and populating it with the various
1526 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001527 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 This->Found = *Pos;
1529 return true;
1530 }
1531
1532 // \brief Retrieve the identifier info found within the module
1533 // files.
1534 IdentifierInfo *getIdentifierInfo() const { return Found; }
1535 };
1536}
1537
1538void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1539 // Note that we are loading an identifier.
1540 Deserializing AnIdentifier(this);
1541
1542 unsigned PriorGeneration = 0;
1543 if (getContext().getLangOpts().Modules)
1544 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001545
1546 // If there is a global index, look there first to determine which modules
1547 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001548 GlobalModuleIndex::HitSet Hits;
1549 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001550 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001551 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1552 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001553 }
1554 }
1555
Douglas Gregor7211ac12013-01-25 23:32:03 +00001556 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001557 NumIdentifierLookups,
1558 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001559 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 markIdentifierUpToDate(&II);
1561}
1562
1563void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1564 if (!II)
1565 return;
1566
1567 II->setOutOfDate(false);
1568
1569 // Update the generation for this identifier.
1570 if (getContext().getLangOpts().Modules)
1571 IdentifierGeneration[II] = CurrentGeneration;
1572}
1573
Richard Smith49f906a2014-03-01 00:08:04 +00001574struct ASTReader::ModuleMacroInfo {
1575 SubmoduleID SubModID;
1576 MacroInfo *MI;
1577 SubmoduleID *Overrides;
1578 // FIXME: Remove this.
1579 ModuleFile *F;
1580
1581 bool isDefine() const { return MI; }
1582
1583 SubmoduleID getSubmoduleID() const { return SubModID; }
1584
1585 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1586 if (!Overrides)
1587 return llvm::ArrayRef<SubmoduleID>();
1588 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1589 }
1590
1591 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1592 if (!MI)
1593 return 0;
1594 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1595 }
1596};
1597
1598ASTReader::ModuleMacroInfo *
1599ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1600 ModuleMacroInfo Info;
1601
1602 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1603 if (ID & 1) {
1604 // Macro undefinition.
1605 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1606 Info.MI = 0;
1607 } else {
1608 // Macro definition.
1609 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1610 assert(GMacID);
1611
1612 // If this macro has already been loaded, don't do so again.
1613 // FIXME: This is highly dubious. Multiple macro definitions can have the
1614 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1615 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1616 return 0;
1617
1618 Info.MI = getMacro(GMacID);
1619 Info.SubModID = Info.MI->getOwningModuleID();
1620 }
1621 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1622 Info.F = PMInfo.M;
1623
1624 return new (Context) ModuleMacroInfo(Info);
1625}
1626
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001627void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1628 const PendingMacroInfo &PMInfo) {
1629 assert(II);
1630
1631 if (PMInfo.M->Kind != MK_Module) {
1632 installPCHMacroDirectives(II, *PMInfo.M,
1633 PMInfo.PCHMacroData.MacroDirectivesOffset);
1634 return;
1635 }
Richard Smith49f906a2014-03-01 00:08:04 +00001636
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001637 // Module Macro.
1638
Richard Smith49f906a2014-03-01 00:08:04 +00001639 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1640 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001641 return;
1642
Richard Smith49f906a2014-03-01 00:08:04 +00001643 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1644 if (Owner && Owner->NameVisibility == Module::Hidden) {
1645 // Macros in the owning module are hidden. Just remember this macro to
1646 // install if we make this module visible.
1647 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1648 } else {
1649 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001650 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001651}
1652
1653void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1654 ModuleFile &M, uint64_t Offset) {
1655 assert(M.Kind != MK_Module);
1656
1657 BitstreamCursor &Cursor = M.MacroCursor;
1658 SavedStreamPosition SavedPosition(Cursor);
1659 Cursor.JumpToBit(Offset);
1660
1661 llvm::BitstreamEntry Entry =
1662 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1663 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1664 Error("malformed block record in AST file");
1665 return;
1666 }
1667
1668 RecordData Record;
1669 PreprocessorRecordTypes RecType =
1670 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1671 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1672 Error("malformed block record in AST file");
1673 return;
1674 }
1675
1676 // Deserialize the macro directives history in reverse source-order.
1677 MacroDirective *Latest = 0, *Earliest = 0;
1678 unsigned Idx = 0, N = Record.size();
1679 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001680 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001681 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001682 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1683 switch (K) {
1684 case MacroDirective::MD_Define: {
1685 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1686 MacroInfo *MI = getMacro(GMacID);
1687 bool isImported = Record[Idx++];
1688 bool isAmbiguous = Record[Idx++];
1689 DefMacroDirective *DefMD =
1690 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1691 DefMD->setAmbiguous(isAmbiguous);
1692 MD = DefMD;
1693 break;
1694 }
1695 case MacroDirective::MD_Undefine:
1696 MD = PP.AllocateUndefMacroDirective(Loc);
1697 break;
1698 case MacroDirective::MD_Visibility: {
1699 bool isPublic = Record[Idx++];
1700 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1701 break;
1702 }
1703 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001704
1705 if (!Latest)
1706 Latest = MD;
1707 if (Earliest)
1708 Earliest->setPrevious(MD);
1709 Earliest = MD;
1710 }
1711
1712 PP.setLoadedMacroDirective(II, Latest);
1713}
1714
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001715/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001716/// modules.
1717static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001718 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001719 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001720 Module *PrevOwner = 0;
1721 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1722 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001723 SourceManager &SrcMgr = Reader.getSourceManager();
1724 bool PrevInSystem
1725 = PrevOwner? PrevOwner->IsSystem
1726 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1727 bool NewInSystem
1728 = NewOwner? NewOwner->IsSystem
1729 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1730 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001731 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001732 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001733}
1734
Richard Smith49f906a2014-03-01 00:08:04 +00001735void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1736 AmbiguousMacros &Ambig,
1737 llvm::ArrayRef<SubmoduleID> Overrides) {
1738 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1739 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001740
Richard Smith49f906a2014-03-01 00:08:04 +00001741 // If this macro is not yet visible, remove it from the hidden names list.
1742 Module *Owner = getSubmodule(OwnerID);
1743 HiddenNames &Hidden = HiddenNamesMap[Owner];
1744 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1745 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001746 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001747 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001748 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001749 }
1750
1751 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001752 Ambig.erase(
1753 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1754 return MD->getInfo()->getOwningModuleID() == OwnerID;
1755 }),
1756 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001757 }
1758}
1759
1760ASTReader::AmbiguousMacros *
1761ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1762 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001763 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001764 if (!Prev && Overrides.empty())
1765 return 0;
1766
1767 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1768 if (PrevDef && PrevDef->isAmbiguous()) {
1769 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1770 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1771 Ambig.push_back(PrevDef);
1772
1773 removeOverriddenMacros(II, Ambig, Overrides);
1774
1775 if (!Ambig.empty())
1776 return &Ambig;
1777
1778 AmbiguousMacroDefs.erase(II);
1779 } else {
1780 // There's no ambiguity yet. Maybe we're introducing one.
1781 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1782 if (PrevDef)
1783 Ambig.push_back(PrevDef);
1784
1785 removeOverriddenMacros(II, Ambig, Overrides);
1786
1787 if (!Ambig.empty()) {
1788 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1789 Result.swap(Ambig);
1790 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001791 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001792 }
Richard Smith49f906a2014-03-01 00:08:04 +00001793
1794 // We ended up with no ambiguity.
1795 return 0;
1796}
1797
1798void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1799 Module *Owner) {
1800 assert(II && Owner);
1801
1802 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1803 if (ImportLoc.isInvalid()) {
1804 // FIXME: If we made macros from this module visible but didn't provide a
1805 // source location for the import, we don't have a location for the macro.
1806 // Use the location at which the containing module file was first imported
1807 // for now.
1808 ImportLoc = MMI->F->DirectImportLoc;
1809 }
1810
1811 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1812 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1813
1814
1815 // Create a synthetic macro definition corresponding to the import (or null
1816 // if this was an undefinition of the macro).
1817 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1818
1819 // If there's no ambiguity, just install the macro.
1820 if (!Prev) {
1821 if (MD)
1822 PP.appendMacroDirective(II, MD);
1823 else
1824 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1825 return;
1826 }
1827 assert(!Prev->empty());
1828
1829 if (!MD) {
1830 // We imported a #undef that didn't remove all prior definitions. The most
1831 // recent prior definition remains, and we install it in the place of the
1832 // imported directive.
1833 MacroInfo *NewMI = Prev->back()->getInfo();
1834 Prev->pop_back();
1835 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1836 }
1837
1838 // We're introducing a macro definition that creates or adds to an ambiguity.
1839 // We can resolve that ambiguity if this macro is token-for-token identical to
1840 // all of the existing definitions.
1841 MacroInfo *NewMI = MD->getInfo();
1842 assert(NewMI && "macro definition with no MacroInfo?");
1843 while (!Prev->empty()) {
1844 MacroInfo *PrevMI = Prev->back()->getInfo();
1845 assert(PrevMI && "macro definition with no MacroInfo?");
1846
1847 // Before marking the macros as ambiguous, check if this is a case where
1848 // both macros are in system headers. If so, we trust that the system
1849 // did not get it wrong. This also handles cases where Clang's own
1850 // headers have a different spelling of certain system macros:
1851 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1852 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1853 //
1854 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1855 // overrides the system limits.h's macros, so there's no conflict here.
1856 if (NewMI != PrevMI &&
1857 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1858 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1859 break;
1860
1861 // The previous definition is the same as this one (or both are defined in
1862 // system modules so we can assume they're equivalent); we don't need to
1863 // track it any more.
1864 Prev->pop_back();
1865 }
1866
1867 if (!Prev->empty())
1868 MD->setAmbiguous(true);
1869
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001870 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001871}
1872
Ben Langmuir198c1682014-03-07 07:27:49 +00001873void ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID,
1874 std::string &Filename, off_t &StoredSize,
1875 time_t &StoredTime, bool &Overridden) {
1876 // 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
1890 assert(Record[0] == ID && "Bogus stored ID or offset");
1891 StoredSize = static_cast<off_t>(Record[1]);
1892 StoredTime = static_cast<time_t>(Record[2]);
1893 Overridden = static_cast<bool>(Record[3]);
1894 Filename = Blob;
1895 MaybeAddSystemRootToFilename(F, Filename);
1896}
1897
1898std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
1899 off_t StoredSize;
1900 time_t StoredTime;
1901 bool Overridden;
1902 std::string Filename;
1903 readInputFileInfo(F, ID, Filename, StoredSize, StoredTime, Overridden);
1904 return Filename;
1905}
1906
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001907InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 // If this ID is bogus, just return an empty input file.
1909 if (ID == 0 || ID > F.InputFilesLoaded.size())
1910 return InputFile();
1911
1912 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001913 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 return F.InputFilesLoaded[ID-1];
1915
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001916 if (F.InputFilesLoaded[ID-1].isNotFound())
1917 return InputFile();
1918
Guy Benyei11169dd2012-12-18 14:30:41 +00001919 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001920 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 SavedStreamPosition SavedPosition(Cursor);
1922 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1923
Ben Langmuir198c1682014-03-07 07:27:49 +00001924 off_t StoredSize;
1925 time_t StoredTime;
1926 bool Overridden;
1927 std::string Filename;
1928 readInputFileInfo(F, ID, Filename, StoredSize, StoredTime, Overridden);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001929
Ben Langmuir198c1682014-03-07 07:27:49 +00001930 const FileEntry *File
1931 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1932 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1933
1934 // If we didn't find the file, resolve it relative to the
1935 // original directory from which this AST file was created.
1936 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1937 F.OriginalDir != CurrentDir) {
1938 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1939 F.OriginalDir,
1940 CurrentDir);
1941 if (!Resolved.empty())
1942 File = FileMgr.getFile(Resolved);
1943 }
1944
1945 // For an overridden file, create a virtual file with the stored
1946 // size/timestamp.
1947 if (Overridden && File == 0) {
1948 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1949 }
1950
1951 if (File == 0) {
1952 if (Complain) {
1953 std::string ErrorStr = "could not find file '";
1954 ErrorStr += Filename;
1955 ErrorStr += "' referenced by AST file";
1956 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001958 // Record that we didn't find the file.
1959 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1960 return InputFile();
1961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001962
Ben Langmuir198c1682014-03-07 07:27:49 +00001963 // Check if there was a request to override the contents of the file
1964 // that was part of the precompiled header. Overridding such a file
1965 // can lead to problems when lexing using the source locations from the
1966 // PCH.
1967 SourceManager &SM = getSourceManager();
1968 if (!Overridden && SM.isFileOverridden(File)) {
1969 if (Complain)
1970 Error(diag::err_fe_pch_file_overridden, Filename);
1971 // After emitting the diagnostic, recover by disabling the override so
1972 // that the original file will be used.
1973 SM.disableFileContentsOverride(File);
1974 // The FileEntry is a virtual file entry with the size of the contents
1975 // that would override the original contents. Set it to the original's
1976 // size/time.
1977 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1978 StoredSize, StoredTime);
1979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001980
Ben Langmuir198c1682014-03-07 07:27:49 +00001981 bool IsOutOfDate = false;
1982
1983 // For an overridden file, there is nothing to validate.
1984 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00001985#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00001986 // In our regression testing, the Windows file system seems to
1987 // have inconsistent modification times that sometimes
1988 // erroneously trigger this error-handling path.
1989 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00001990#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001991 )) {
1992 if (Complain) {
1993 // Build a list of the PCH imports that got us here (in reverse).
1994 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1995 while (ImportStack.back()->ImportedBy.size() > 0)
1996 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001997
Ben Langmuir198c1682014-03-07 07:27:49 +00001998 // The top-level PCH is stale.
1999 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2000 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002001
Ben Langmuir198c1682014-03-07 07:27:49 +00002002 // Print the import stack.
2003 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2004 Diag(diag::note_pch_required_by)
2005 << Filename << ImportStack[0]->FileName;
2006 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002007 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002009 }
2010
Ben Langmuir198c1682014-03-07 07:27:49 +00002011 if (!Diags.isDiagnosticInFlight())
2012 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 }
2014
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 }
2017
Ben Langmuir198c1682014-03-07 07:27:49 +00002018 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2019
2020 // Note that we've loaded this input file.
2021 F.InputFilesLoaded[ID-1] = IF;
2022 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023}
2024
2025const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2026 ModuleFile &M = ModuleMgr.getPrimaryModule();
2027 std::string Filename = filenameStrRef;
2028 MaybeAddSystemRootToFilename(M, Filename);
2029 const FileEntry *File = FileMgr.getFile(Filename);
2030 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2031 M.OriginalDir != CurrentDir) {
2032 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2033 M.OriginalDir,
2034 CurrentDir);
2035 if (!resolved.empty())
2036 File = FileMgr.getFile(resolved);
2037 }
2038
2039 return File;
2040}
2041
2042/// \brief If we are loading a relocatable PCH file, and the filename is
2043/// not an absolute path, add the system root to the beginning of the file
2044/// name.
2045void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2046 std::string &Filename) {
2047 // If this is not a relocatable PCH file, there's nothing to do.
2048 if (!M.RelocatablePCH)
2049 return;
2050
2051 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2052 return;
2053
2054 if (isysroot.empty()) {
2055 // If no system root was given, default to '/'
2056 Filename.insert(Filename.begin(), '/');
2057 return;
2058 }
2059
2060 unsigned Length = isysroot.size();
2061 if (isysroot[Length - 1] != '/')
2062 Filename.insert(Filename.begin(), '/');
2063
2064 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2065}
2066
2067ASTReader::ASTReadResult
2068ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002069 SmallVectorImpl<ImportedModule> &Loaded,
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002071 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002072
2073 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2074 Error("malformed block record in AST file");
2075 return Failure;
2076 }
2077
2078 // Read all of the records and blocks in the control block.
2079 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002080 while (1) {
2081 llvm::BitstreamEntry Entry = Stream.advance();
2082
2083 switch (Entry.Kind) {
2084 case llvm::BitstreamEntry::Error:
2085 Error("malformed block record in AST file");
2086 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002087 case llvm::BitstreamEntry::EndBlock: {
2088 // Validate input files.
2089 const HeaderSearchOptions &HSOpts =
2090 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002091
2092 // All user input files reside at the index range [0, Record[1]), and
2093 // system input files reside at [Record[1], Record[0]).
2094 // Record is the one from INPUT_FILE_OFFSETS.
2095 unsigned NumInputs = Record[0];
2096 unsigned NumUserInputs = Record[1];
2097
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002098 if (!DisableValidation &&
2099 (!HSOpts.ModulesValidateOncePerBuildSession ||
2100 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002101 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002102
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002103 // If we are reading a module, we will create a verification timestamp,
2104 // so we verify all input files. Otherwise, verify only user input
2105 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002106
2107 unsigned N = NumUserInputs;
2108 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002109 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2110 N = NumInputs;
2111
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002112 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002113 InputFile IF = getInputFile(F, I+1, Complain);
2114 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002118
2119 if (Listener && Listener->needsInputFileVisitation()) {
2120 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2121 : NumUserInputs;
2122 for (unsigned I = 0; I < N; ++I)
2123 Listener->visitInputFile(getInputFileName(F, I+1), I >= NumUserInputs);
2124 }
2125
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002127 }
2128
Chris Lattnere7b154b2013-01-19 21:39:22 +00002129 case llvm::BitstreamEntry::SubBlock:
2130 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 case INPUT_FILES_BLOCK_ID:
2132 F.InputFilesCursor = Stream;
2133 if (Stream.SkipBlock() || // Skip with the main cursor
2134 // Read the abbreviations
2135 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2136 Error("malformed block record in AST file");
2137 return Failure;
2138 }
2139 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002140
Guy Benyei11169dd2012-12-18 14:30:41 +00002141 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002142 if (Stream.SkipBlock()) {
2143 Error("malformed block record in AST file");
2144 return Failure;
2145 }
2146 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002148
2149 case llvm::BitstreamEntry::Record:
2150 // The interesting case.
2151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 }
2153
2154 // Read and process a record.
2155 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002156 StringRef Blob;
2157 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 case METADATA: {
2159 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2160 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002161 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2162 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 return VersionMismatch;
2164 }
2165
2166 bool hasErrors = Record[5];
2167 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2168 Diag(diag::err_pch_with_compiler_errors);
2169 return HadErrors;
2170 }
2171
2172 F.RelocatablePCH = Record[4];
2173
2174 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002175 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002176 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2177 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002178 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002179 return VersionMismatch;
2180 }
2181 break;
2182 }
2183
2184 case IMPORTS: {
2185 // Load each of the imported PCH files.
2186 unsigned Idx = 0, N = Record.size();
2187 while (Idx < N) {
2188 // Read information about the AST file.
2189 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2190 // The import location will be the local one for now; we will adjust
2191 // all import locations of module imports after the global source
2192 // location info are setup.
2193 SourceLocation ImportLoc =
2194 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002195 off_t StoredSize = (off_t)Record[Idx++];
2196 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 unsigned Length = Record[Idx++];
2198 SmallString<128> ImportedFile(Record.begin() + Idx,
2199 Record.begin() + Idx + Length);
2200 Idx += Length;
2201
2202 // Load the AST file.
2203 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002204 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002205 ClientLoadCapabilities)) {
2206 case Failure: return Failure;
2207 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002208 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 case OutOfDate: return OutOfDate;
2210 case VersionMismatch: return VersionMismatch;
2211 case ConfigurationMismatch: return ConfigurationMismatch;
2212 case HadErrors: return HadErrors;
2213 case Success: break;
2214 }
2215 }
2216 break;
2217 }
2218
2219 case LANGUAGE_OPTIONS: {
2220 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2221 if (Listener && &F == *ModuleMgr.begin() &&
2222 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002223 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 return ConfigurationMismatch;
2225 break;
2226 }
2227
2228 case TARGET_OPTIONS: {
2229 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2230 if (Listener && &F == *ModuleMgr.begin() &&
2231 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002232 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 return ConfigurationMismatch;
2234 break;
2235 }
2236
2237 case DIAGNOSTIC_OPTIONS: {
2238 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2239 if (Listener && &F == *ModuleMgr.begin() &&
2240 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002241 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 return ConfigurationMismatch;
2243 break;
2244 }
2245
2246 case FILE_SYSTEM_OPTIONS: {
2247 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2248 if (Listener && &F == *ModuleMgr.begin() &&
2249 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002250 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 return ConfigurationMismatch;
2252 break;
2253 }
2254
2255 case HEADER_SEARCH_OPTIONS: {
2256 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2257 if (Listener && &F == *ModuleMgr.begin() &&
2258 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002259 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 return ConfigurationMismatch;
2261 break;
2262 }
2263
2264 case PREPROCESSOR_OPTIONS: {
2265 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2266 if (Listener && &F == *ModuleMgr.begin() &&
2267 ParsePreprocessorOptions(Record, Complain, *Listener,
2268 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002269 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 return ConfigurationMismatch;
2271 break;
2272 }
2273
2274 case ORIGINAL_FILE:
2275 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002276 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2278 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2279 break;
2280
2281 case ORIGINAL_FILE_ID:
2282 F.OriginalSourceFileID = FileID::get(Record[0]);
2283 break;
2284
2285 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002286 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 break;
2288
2289 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002290 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 F.InputFilesLoaded.resize(Record[0]);
2292 break;
2293 }
2294 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002295}
2296
2297bool ASTReader::ReadASTBlock(ModuleFile &F) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002298 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002299
2300 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2301 Error("malformed block record in AST file");
2302 return true;
2303 }
2304
2305 // Read all of the records and blocks for the AST file.
2306 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002307 while (1) {
2308 llvm::BitstreamEntry Entry = Stream.advance();
2309
2310 switch (Entry.Kind) {
2311 case llvm::BitstreamEntry::Error:
2312 Error("error at end of module block in AST file");
2313 return true;
2314 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002315 // Outside of C++, we do not store a lookup map for the translation unit.
2316 // Instead, mark it as needing a lookup map to be built if this module
2317 // contains any declarations lexically within it (which it always does!).
2318 // This usually has no cost, since we very rarely need the lookup map for
2319 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002321 if (DC->hasExternalLexicalStorage() &&
2322 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002323 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002324
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 return false;
2326 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002327 case llvm::BitstreamEntry::SubBlock:
2328 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 case DECLTYPES_BLOCK_ID:
2330 // We lazily load the decls block, but we want to set up the
2331 // DeclsCursor cursor to point into it. Clone our current bitcode
2332 // cursor to it, enter the block and read the abbrevs in that block.
2333 // With the main cursor, we just skip over it.
2334 F.DeclsCursor = Stream;
2335 if (Stream.SkipBlock() || // Skip with the main cursor.
2336 // Read the abbrevs.
2337 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2338 Error("malformed block record in AST file");
2339 return true;
2340 }
2341 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002342
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 case DECL_UPDATES_BLOCK_ID:
2344 if (Stream.SkipBlock()) {
2345 Error("malformed block record in AST file");
2346 return true;
2347 }
2348 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002349
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 case PREPROCESSOR_BLOCK_ID:
2351 F.MacroCursor = Stream;
2352 if (!PP.getExternalSource())
2353 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002354
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 if (Stream.SkipBlock() ||
2356 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2357 Error("malformed block record in AST file");
2358 return true;
2359 }
2360 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2361 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 case PREPROCESSOR_DETAIL_BLOCK_ID:
2364 F.PreprocessorDetailCursor = Stream;
2365 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002366 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002368 Error("malformed preprocessor detail record in AST file");
2369 return true;
2370 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002372 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2373
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 if (!PP.getPreprocessingRecord())
2375 PP.createPreprocessingRecord();
2376 if (!PP.getPreprocessingRecord()->getExternalSource())
2377 PP.getPreprocessingRecord()->SetExternalSource(*this);
2378 break;
2379
2380 case SOURCE_MANAGER_BLOCK_ID:
2381 if (ReadSourceManagerBlock(F))
2382 return true;
2383 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 case SUBMODULE_BLOCK_ID:
2386 if (ReadSubmoduleBlock(F))
2387 return true;
2388 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002391 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 if (Stream.SkipBlock() ||
2393 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2394 Error("malformed comments block in AST file");
2395 return true;
2396 }
2397 CommentsCursors.push_back(std::make_pair(C, &F));
2398 break;
2399 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002400
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402 if (Stream.SkipBlock()) {
2403 Error("malformed block record in AST file");
2404 return true;
2405 }
2406 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 }
2408 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002409
2410 case llvm::BitstreamEntry::Record:
2411 // The interesting case.
2412 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 }
2414
2415 // Read and process a record.
2416 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002417 StringRef Blob;
2418 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 default: // Default behavior: ignore.
2420 break;
2421
2422 case TYPE_OFFSET: {
2423 if (F.LocalNumTypes != 0) {
2424 Error("duplicate TYPE_OFFSET record in AST file");
2425 return true;
2426 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002427 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 F.LocalNumTypes = Record[0];
2429 unsigned LocalBaseTypeIndex = Record[1];
2430 F.BaseTypeIndex = getTotalNumTypes();
2431
2432 if (F.LocalNumTypes > 0) {
2433 // Introduce the global -> local mapping for types within this module.
2434 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2435
2436 // Introduce the local -> global mapping for types within this module.
2437 F.TypeRemap.insertOrReplace(
2438 std::make_pair(LocalBaseTypeIndex,
2439 F.BaseTypeIndex - LocalBaseTypeIndex));
2440
2441 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2442 }
2443 break;
2444 }
2445
2446 case DECL_OFFSET: {
2447 if (F.LocalNumDecls != 0) {
2448 Error("duplicate DECL_OFFSET record in AST file");
2449 return true;
2450 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002451 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 F.LocalNumDecls = Record[0];
2453 unsigned LocalBaseDeclID = Record[1];
2454 F.BaseDeclID = getTotalNumDecls();
2455
2456 if (F.LocalNumDecls > 0) {
2457 // Introduce the global -> local mapping for declarations within this
2458 // module.
2459 GlobalDeclMap.insert(
2460 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2461
2462 // Introduce the local -> global mapping for declarations within this
2463 // module.
2464 F.DeclRemap.insertOrReplace(
2465 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2466
2467 // Introduce the global -> local mapping for declarations within this
2468 // module.
2469 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2470
2471 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2472 }
2473 break;
2474 }
2475
2476 case TU_UPDATE_LEXICAL: {
2477 DeclContext *TU = Context.getTranslationUnitDecl();
2478 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002479 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002481 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 TU->setHasExternalLexicalStorage(true);
2483 break;
2484 }
2485
2486 case UPDATE_VISIBLE: {
2487 unsigned Idx = 0;
2488 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2489 ASTDeclContextNameLookupTable *Table =
2490 ASTDeclContextNameLookupTable::Create(
Chris Lattner0e6c9402013-01-20 02:38:54 +00002491 (const unsigned char *)Blob.data() + Record[Idx++],
2492 (const unsigned char *)Blob.data(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 ASTDeclContextNameLookupTrait(*this, F));
2494 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2495 DeclContext *TU = Context.getTranslationUnitDecl();
2496 F.DeclContextInfos[TU].NameLookupTableData = Table;
2497 TU->setHasExternalVisibleStorage(true);
2498 } else
2499 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2500 break;
2501 }
2502
2503 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002504 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 if (Record[0]) {
2506 F.IdentifierLookupTable
2507 = ASTIdentifierLookupTable::Create(
2508 (const unsigned char *)F.IdentifierTableData + Record[0],
2509 (const unsigned char *)F.IdentifierTableData,
2510 ASTIdentifierLookupTrait(*this, F));
2511
2512 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2513 }
2514 break;
2515
2516 case IDENTIFIER_OFFSET: {
2517 if (F.LocalNumIdentifiers != 0) {
2518 Error("duplicate IDENTIFIER_OFFSET record in AST file");
2519 return true;
2520 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002521 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 F.LocalNumIdentifiers = Record[0];
2523 unsigned LocalBaseIdentifierID = Record[1];
2524 F.BaseIdentifierID = getTotalNumIdentifiers();
2525
2526 if (F.LocalNumIdentifiers > 0) {
2527 // Introduce the global -> local mapping for identifiers within this
2528 // module.
2529 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2530 &F));
2531
2532 // Introduce the local -> global mapping for identifiers within this
2533 // module.
2534 F.IdentifierRemap.insertOrReplace(
2535 std::make_pair(LocalBaseIdentifierID,
2536 F.BaseIdentifierID - LocalBaseIdentifierID));
2537
2538 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2539 + F.LocalNumIdentifiers);
2540 }
2541 break;
2542 }
2543
Ben Langmuir332aafe2014-01-31 01:06:56 +00002544 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002546 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 break;
2548
2549 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002550 if (SpecialTypes.empty()) {
2551 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2552 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2553 break;
2554 }
2555
2556 if (SpecialTypes.size() != Record.size()) {
2557 Error("invalid special-types record");
2558 return true;
2559 }
2560
2561 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2562 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2563 if (!SpecialTypes[I])
2564 SpecialTypes[I] = ID;
2565 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2566 // merge step?
2567 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 break;
2569
2570 case STATISTICS:
2571 TotalNumStatements += Record[0];
2572 TotalNumMacros += Record[1];
2573 TotalLexicalDeclContexts += Record[2];
2574 TotalVisibleDeclContexts += Record[3];
2575 break;
2576
2577 case UNUSED_FILESCOPED_DECLS:
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2580 break;
2581
2582 case DELEGATING_CTORS:
2583 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2584 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2585 break;
2586
2587 case WEAK_UNDECLARED_IDENTIFIERS:
2588 if (Record.size() % 4 != 0) {
2589 Error("invalid weak identifiers record");
2590 return true;
2591 }
2592
2593 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2594 // files. This isn't the way to do it :)
2595 WeakUndeclaredIdentifiers.clear();
2596
2597 // Translate the weak, undeclared identifiers into global IDs.
2598 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2599 WeakUndeclaredIdentifiers.push_back(
2600 getGlobalIdentifierID(F, Record[I++]));
2601 WeakUndeclaredIdentifiers.push_back(
2602 getGlobalIdentifierID(F, Record[I++]));
2603 WeakUndeclaredIdentifiers.push_back(
2604 ReadSourceLocation(F, Record, I).getRawEncoding());
2605 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2606 }
2607 break;
2608
Richard Smith78165b52013-01-10 23:43:47 +00002609 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002611 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 break;
2613
2614 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002615 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 F.LocalNumSelectors = Record[0];
2617 unsigned LocalBaseSelectorID = Record[1];
2618 F.BaseSelectorID = getTotalNumSelectors();
2619
2620 if (F.LocalNumSelectors > 0) {
2621 // Introduce the global -> local mapping for selectors within this
2622 // module.
2623 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2624
2625 // Introduce the local -> global mapping for selectors within this
2626 // module.
2627 F.SelectorRemap.insertOrReplace(
2628 std::make_pair(LocalBaseSelectorID,
2629 F.BaseSelectorID - LocalBaseSelectorID));
2630
2631 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2632 }
2633 break;
2634 }
2635
2636 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002637 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 if (Record[0])
2639 F.SelectorLookupTable
2640 = ASTSelectorLookupTable::Create(
2641 F.SelectorLookupTableData + Record[0],
2642 F.SelectorLookupTableData,
2643 ASTSelectorLookupTrait(*this, F));
2644 TotalNumMethodPoolEntries += Record[1];
2645 break;
2646
2647 case REFERENCED_SELECTOR_POOL:
2648 if (!Record.empty()) {
2649 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2650 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2651 Record[Idx++]));
2652 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2653 getRawEncoding());
2654 }
2655 }
2656 break;
2657
2658 case PP_COUNTER_VALUE:
2659 if (!Record.empty() && Listener)
2660 Listener->ReadCounter(F, Record[0]);
2661 break;
2662
2663 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002664 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 F.NumFileSortedDecls = Record[0];
2666 break;
2667
2668 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002669 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 F.LocalNumSLocEntries = Record[0];
2671 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002672 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2674 SLocSpaceSize);
2675 // Make our entry in the range map. BaseID is negative and growing, so
2676 // we invert it. Because we invert it, though, we need the other end of
2677 // the range.
2678 unsigned RangeStart =
2679 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2680 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2681 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2682
2683 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2684 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2685 GlobalSLocOffsetMap.insert(
2686 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2687 - SLocSpaceSize,&F));
2688
2689 // Initialize the remapping table.
2690 // Invalid stays invalid.
2691 F.SLocRemap.insert(std::make_pair(0U, 0));
2692 // This module. Base was 2 when being compiled.
2693 F.SLocRemap.insert(std::make_pair(2U,
2694 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2695
2696 TotalNumSLocEntries += F.LocalNumSLocEntries;
2697 break;
2698 }
2699
2700 case MODULE_OFFSET_MAP: {
2701 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002702 const unsigned char *Data = (const unsigned char*)Blob.data();
2703 const unsigned char *DataEnd = Data + Blob.size();
Guy Benyei11169dd2012-12-18 14:30:41 +00002704
2705 // Continuous range maps we may be updating in our module.
2706 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2707 ContinuousRangeMap<uint32_t, int, 2>::Builder
2708 IdentifierRemap(F.IdentifierRemap);
2709 ContinuousRangeMap<uint32_t, int, 2>::Builder
2710 MacroRemap(F.MacroRemap);
2711 ContinuousRangeMap<uint32_t, int, 2>::Builder
2712 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2713 ContinuousRangeMap<uint32_t, int, 2>::Builder
2714 SubmoduleRemap(F.SubmoduleRemap);
2715 ContinuousRangeMap<uint32_t, int, 2>::Builder
2716 SelectorRemap(F.SelectorRemap);
2717 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2718 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2719
2720 while(Data < DataEnd) {
2721 uint16_t Len = io::ReadUnalignedLE16(Data);
2722 StringRef Name = StringRef((const char*)Data, Len);
2723 Data += Len;
2724 ModuleFile *OM = ModuleMgr.lookup(Name);
2725 if (!OM) {
2726 Error("SourceLocation remap refers to unknown module");
2727 return true;
2728 }
2729
2730 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2731 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2732 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2733 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2734 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2735 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2736 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2737 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2738
2739 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2740 SLocRemap.insert(std::make_pair(SLocOffset,
2741 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2742 IdentifierRemap.insert(
2743 std::make_pair(IdentifierIDOffset,
2744 OM->BaseIdentifierID - IdentifierIDOffset));
2745 MacroRemap.insert(std::make_pair(MacroIDOffset,
2746 OM->BaseMacroID - MacroIDOffset));
2747 PreprocessedEntityRemap.insert(
2748 std::make_pair(PreprocessedEntityIDOffset,
2749 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2750 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2751 OM->BaseSubmoduleID - SubmoduleIDOffset));
2752 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2753 OM->BaseSelectorID - SelectorIDOffset));
2754 DeclRemap.insert(std::make_pair(DeclIDOffset,
2755 OM->BaseDeclID - DeclIDOffset));
2756
2757 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2758 OM->BaseTypeIndex - TypeIndexOffset));
2759
2760 // Global -> local mappings.
2761 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2762 }
2763 break;
2764 }
2765
2766 case SOURCE_MANAGER_LINE_TABLE:
2767 if (ParseLineTable(F, Record))
2768 return true;
2769 break;
2770
2771 case SOURCE_LOCATION_PRELOADS: {
2772 // Need to transform from the local view (1-based IDs) to the global view,
2773 // which is based off F.SLocEntryBaseID.
2774 if (!F.PreloadSLocEntries.empty()) {
2775 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2776 return true;
2777 }
2778
2779 F.PreloadSLocEntries.swap(Record);
2780 break;
2781 }
2782
2783 case EXT_VECTOR_DECLS:
2784 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2785 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2786 break;
2787
2788 case VTABLE_USES:
2789 if (Record.size() % 3 != 0) {
2790 Error("Invalid VTABLE_USES record");
2791 return true;
2792 }
2793
2794 // Later tables overwrite earlier ones.
2795 // FIXME: Modules will have some trouble with this. This is clearly not
2796 // the right way to do this.
2797 VTableUses.clear();
2798
2799 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2800 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2801 VTableUses.push_back(
2802 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2803 VTableUses.push_back(Record[Idx++]);
2804 }
2805 break;
2806
2807 case DYNAMIC_CLASSES:
2808 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2809 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2810 break;
2811
2812 case PENDING_IMPLICIT_INSTANTIATIONS:
2813 if (PendingInstantiations.size() % 2 != 0) {
2814 Error("Invalid existing PendingInstantiations");
2815 return true;
2816 }
2817
2818 if (Record.size() % 2 != 0) {
2819 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2820 return true;
2821 }
2822
2823 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2824 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2825 PendingInstantiations.push_back(
2826 ReadSourceLocation(F, Record, I).getRawEncoding());
2827 }
2828 break;
2829
2830 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002831 if (Record.size() != 2) {
2832 Error("Invalid SEMA_DECL_REFS block");
2833 return true;
2834 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2836 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2837 break;
2838
2839 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002840 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2841 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2842 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002843
2844 unsigned LocalBasePreprocessedEntityID = Record[0];
2845
2846 unsigned StartingID;
2847 if (!PP.getPreprocessingRecord())
2848 PP.createPreprocessingRecord();
2849 if (!PP.getPreprocessingRecord()->getExternalSource())
2850 PP.getPreprocessingRecord()->SetExternalSource(*this);
2851 StartingID
2852 = PP.getPreprocessingRecord()
2853 ->allocateLoadedEntities(F.NumPreprocessedEntities);
2854 F.BasePreprocessedEntityID = StartingID;
2855
2856 if (F.NumPreprocessedEntities > 0) {
2857 // Introduce the global -> local mapping for preprocessed entities in
2858 // this module.
2859 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2860
2861 // Introduce the local -> global mapping for preprocessed entities in
2862 // this module.
2863 F.PreprocessedEntityRemap.insertOrReplace(
2864 std::make_pair(LocalBasePreprocessedEntityID,
2865 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2866 }
2867
2868 break;
2869 }
2870
2871 case DECL_UPDATE_OFFSETS: {
2872 if (Record.size() % 2 != 0) {
2873 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2874 return true;
2875 }
2876 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2877 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2878 .push_back(std::make_pair(&F, Record[I+1]));
2879 break;
2880 }
2881
2882 case DECL_REPLACEMENTS: {
2883 if (Record.size() % 3 != 0) {
2884 Error("invalid DECL_REPLACEMENTS block in AST file");
2885 return true;
2886 }
2887 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2888 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2889 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2890 break;
2891 }
2892
2893 case OBJC_CATEGORIES_MAP: {
2894 if (F.LocalNumObjCCategoriesInMap != 0) {
2895 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2896 return true;
2897 }
2898
2899 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002900 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 break;
2902 }
2903
2904 case OBJC_CATEGORIES:
2905 F.ObjCCategories.swap(Record);
2906 break;
2907
2908 case CXX_BASE_SPECIFIER_OFFSETS: {
2909 if (F.LocalNumCXXBaseSpecifiers != 0) {
2910 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2911 return true;
2912 }
2913
2914 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002915 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002916 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2917 break;
2918 }
2919
2920 case DIAG_PRAGMA_MAPPINGS:
2921 if (F.PragmaDiagMappings.empty())
2922 F.PragmaDiagMappings.swap(Record);
2923 else
2924 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2925 Record.begin(), Record.end());
2926 break;
2927
2928 case CUDA_SPECIAL_DECL_REFS:
2929 // Later tables overwrite earlier ones.
2930 // FIXME: Modules will have trouble with this.
2931 CUDASpecialDeclRefs.clear();
2932 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2933 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2934 break;
2935
2936 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002937 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 if (Record[0]) {
2940 F.HeaderFileInfoTable
2941 = HeaderFileInfoLookupTable::Create(
2942 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2943 (const unsigned char *)F.HeaderFileInfoTableData,
2944 HeaderFileInfoTrait(*this, F,
2945 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002947
2948 PP.getHeaderSearchInfo().SetExternalSource(this);
2949 if (!PP.getHeaderSearchInfo().getExternalLookup())
2950 PP.getHeaderSearchInfo().SetExternalLookup(this);
2951 }
2952 break;
2953 }
2954
2955 case FP_PRAGMA_OPTIONS:
2956 // Later tables overwrite earlier ones.
2957 FPPragmaOptions.swap(Record);
2958 break;
2959
2960 case OPENCL_EXTENSIONS:
2961 // Later tables overwrite earlier ones.
2962 OpenCLExtensions.swap(Record);
2963 break;
2964
2965 case TENTATIVE_DEFINITIONS:
2966 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2967 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2968 break;
2969
2970 case KNOWN_NAMESPACES:
2971 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2972 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2973 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00002974
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002975 case UNDEFINED_BUT_USED:
2976 if (UndefinedButUsed.size() % 2 != 0) {
2977 Error("Invalid existing UndefinedButUsed");
Nick Lewycky8334af82013-01-26 00:35:08 +00002978 return true;
2979 }
2980
2981 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002982 Error("invalid undefined-but-used record");
Nick Lewycky8334af82013-01-26 00:35:08 +00002983 return true;
2984 }
2985 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00002986 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2987 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00002988 ReadSourceLocation(F, Record, I).getRawEncoding());
2989 }
2990 break;
2991
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 case IMPORTED_MODULES: {
2993 if (F.Kind != MK_Module) {
2994 // If we aren't loading a module (which has its own exports), make
2995 // all of the imported modules visible.
2996 // FIXME: Deal with macros-only imports.
2997 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2998 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2999 ImportedModules.push_back(GlobalID);
3000 }
3001 }
3002 break;
3003 }
3004
3005 case LOCAL_REDECLARATIONS: {
3006 F.RedeclarationChains.swap(Record);
3007 break;
3008 }
3009
3010 case LOCAL_REDECLARATIONS_MAP: {
3011 if (F.LocalNumRedeclarationsInMap != 0) {
3012 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3013 return true;
3014 }
3015
3016 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003017 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 break;
3019 }
3020
3021 case MERGED_DECLARATIONS: {
3022 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3023 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3024 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3025 for (unsigned N = Record[Idx++]; N > 0; --N)
3026 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3027 }
3028 break;
3029 }
3030
3031 case MACRO_OFFSET: {
3032 if (F.LocalNumMacros != 0) {
3033 Error("duplicate MACRO_OFFSET record in AST file");
3034 return true;
3035 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003036 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 F.LocalNumMacros = Record[0];
3038 unsigned LocalBaseMacroID = Record[1];
3039 F.BaseMacroID = getTotalNumMacros();
3040
3041 if (F.LocalNumMacros > 0) {
3042 // Introduce the global -> local mapping for macros within this module.
3043 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3044
3045 // Introduce the local -> global mapping for macros within this module.
3046 F.MacroRemap.insertOrReplace(
3047 std::make_pair(LocalBaseMacroID,
3048 F.BaseMacroID - LocalBaseMacroID));
3049
3050 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3051 }
3052 break;
3053 }
3054
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003055 case MACRO_TABLE: {
3056 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 break;
3058 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003059
3060 case LATE_PARSED_TEMPLATE: {
3061 LateParsedTemplates.append(Record.begin(), Record.end());
3062 break;
3063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 }
3065 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003066}
3067
Douglas Gregorc1489562013-02-12 23:36:21 +00003068/// \brief Move the given method to the back of the global list of methods.
3069static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3070 // Find the entry for this selector in the method pool.
3071 Sema::GlobalMethodPool::iterator Known
3072 = S.MethodPool.find(Method->getSelector());
3073 if (Known == S.MethodPool.end())
3074 return;
3075
3076 // Retrieve the appropriate method list.
3077 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3078 : Known->second.second;
3079 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003080 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003081 if (!Found) {
3082 if (List->Method == Method) {
3083 Found = true;
3084 } else {
3085 // Keep searching.
3086 continue;
3087 }
3088 }
3089
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003090 if (List->getNext())
3091 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003092 else
3093 List->Method = Method;
3094 }
3095}
3096
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003097void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003098 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3099 Decl *D = Names.HiddenDecls[I];
3100 bool wasHidden = D->Hidden;
3101 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003102
Richard Smith49f906a2014-03-01 00:08:04 +00003103 if (wasHidden && SemaObj) {
3104 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3105 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003106 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
3108 }
Richard Smith49f906a2014-03-01 00:08:04 +00003109
3110 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3111 E = Names.HiddenMacros.end();
3112 I != E; ++I)
3113 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003114}
3115
Richard Smith49f906a2014-03-01 00:08:04 +00003116void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003117 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003118 SourceLocation ImportLoc,
3119 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003121 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003122 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003124 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125
3126 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003127 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 // there is nothing more to do.
3129 continue;
3130 }
Richard Smith49f906a2014-03-01 00:08:04 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 if (!Mod->isAvailable()) {
3133 // Modules that aren't available cannot be made visible.
3134 continue;
3135 }
3136
3137 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003138 if (NameVisibility >= Module::MacrosVisible &&
3139 Mod->NameVisibility < Module::MacrosVisible)
3140 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003142
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 // If we've already deserialized any names from this module,
3144 // mark them as visible.
3145 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3146 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003147 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 HiddenNamesMap.erase(Hidden);
3149 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003152 SmallVector<Module *, 16> Exports;
3153 Mod->getExportedModules(Exports);
3154 for (SmallVectorImpl<Module *>::iterator
3155 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3156 Module *Exported = *I;
3157 if (Visited.insert(Exported))
3158 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003160
3161 // Detect any conflicts.
3162 if (Complain) {
3163 assert(ImportLoc.isValid() && "Missing import location");
3164 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3165 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3166 Diag(ImportLoc, diag::warn_module_conflict)
3167 << Mod->getFullModuleName()
3168 << Mod->Conflicts[I].Other->getFullModuleName()
3169 << Mod->Conflicts[I].Message;
3170 // FIXME: Need note where the other module was imported.
3171 }
3172 }
3173 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 }
3175}
3176
Douglas Gregore060e572013-01-25 01:03:03 +00003177bool ASTReader::loadGlobalIndex() {
3178 if (GlobalIndex)
3179 return false;
3180
3181 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3182 !Context.getLangOpts().Modules)
3183 return true;
3184
3185 // Try to load the global index.
3186 TriedLoadingGlobalIndex = true;
3187 StringRef ModuleCachePath
3188 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3189 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003190 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003191 if (!Result.first)
3192 return true;
3193
3194 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003195 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003196 return false;
3197}
3198
3199bool ASTReader::isGlobalIndexUnavailable() const {
3200 return Context.getLangOpts().Modules && UseGlobalIndex &&
3201 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3202}
3203
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003204static void updateModuleTimestamp(ModuleFile &MF) {
3205 // Overwrite the timestamp file contents so that file's mtime changes.
3206 std::string TimestampFilename = MF.getTimestampFilename();
3207 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003208 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003209 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003210 if (!ErrorInfo.empty())
3211 return;
3212 OS << "Timestamp file\n";
3213}
3214
Guy Benyei11169dd2012-12-18 14:30:41 +00003215ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3216 ModuleKind Type,
3217 SourceLocation ImportLoc,
3218 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003219 llvm::SaveAndRestore<SourceLocation>
3220 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 // Bump the generation number.
3223 unsigned PreviousGeneration = CurrentGeneration++;
3224
3225 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003226 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3228 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003229 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 ClientLoadCapabilities)) {
3231 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003232 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 case OutOfDate:
3234 case VersionMismatch:
3235 case ConfigurationMismatch:
3236 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003237 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3238 Context.getLangOpts().Modules
3239 ? &PP.getHeaderSearchInfo().getModuleMap()
3240 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003241
3242 // If we find that any modules are unusable, the global index is going
3243 // to be out-of-date. Just remove it.
3244 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003245 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 return ReadResult;
3247
3248 case Success:
3249 break;
3250 }
3251
3252 // Here comes stuff that we only do once the entire chain is loaded.
3253
3254 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003255 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3256 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 M != MEnd; ++M) {
3258 ModuleFile &F = *M->Mod;
3259
3260 // Read the AST block.
3261 if (ReadASTBlock(F))
3262 return Failure;
3263
3264 // Once read, set the ModuleFile bit base offset and update the size in
3265 // bits of all files we've seen.
3266 F.GlobalBitOffset = TotalModulesSizeInBits;
3267 TotalModulesSizeInBits += F.SizeInBits;
3268 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3269
3270 // Preload SLocEntries.
3271 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3272 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3273 // Load it through the SourceManager and don't call ReadSLocEntry()
3274 // directly because the entry may have already been loaded in which case
3275 // calling ReadSLocEntry() directly would trigger an assertion in
3276 // SourceManager.
3277 SourceMgr.getLoadedSLocEntryByID(Index);
3278 }
3279 }
3280
Douglas Gregor603cd862013-03-22 18:50:14 +00003281 // Setup the import locations and notify the module manager that we've
3282 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003283 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3284 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 M != MEnd; ++M) {
3286 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003287
3288 ModuleMgr.moduleFileAccepted(&F);
3289
3290 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003291 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 if (!M->ImportedBy)
3293 F.ImportLoc = M->ImportLoc;
3294 else
3295 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3296 M->ImportLoc.getRawEncoding());
3297 }
3298
3299 // Mark all of the identifiers in the identifier table as being out of date,
3300 // so that various accessors know to check the loaded modules when the
3301 // identifier is used.
3302 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3303 IdEnd = PP.getIdentifierTable().end();
3304 Id != IdEnd; ++Id)
3305 Id->second->setOutOfDate(true);
3306
3307 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003308 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3309 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3311 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003312
3313 switch (Unresolved.Kind) {
3314 case UnresolvedModuleRef::Conflict:
3315 if (ResolvedMod) {
3316 Module::Conflict Conflict;
3317 Conflict.Other = ResolvedMod;
3318 Conflict.Message = Unresolved.String.str();
3319 Unresolved.Mod->Conflicts.push_back(Conflict);
3320 }
3321 continue;
3322
3323 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 if (ResolvedMod)
3325 Unresolved.Mod->Imports.push_back(ResolvedMod);
3326 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003327
Douglas Gregorfb912652013-03-20 21:10:35 +00003328 case UnresolvedModuleRef::Export:
3329 if (ResolvedMod || Unresolved.IsWildcard)
3330 Unresolved.Mod->Exports.push_back(
3331 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3332 continue;
3333 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003335 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003336
3337 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3338 // Might be unnecessary as use declarations are only used to build the
3339 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003340
3341 InitializeContext();
3342
Richard Smith3d8e97e2013-10-18 06:54:39 +00003343 if (SemaObj)
3344 UpdateSema();
3345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 if (DeserializationListener)
3347 DeserializationListener->ReaderInitialized(this);
3348
3349 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3350 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3351 PrimaryModule.OriginalSourceFileID
3352 = FileID::get(PrimaryModule.SLocEntryBaseID
3353 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3354
3355 // If this AST file is a precompiled preamble, then set the
3356 // preamble file ID of the source manager to the file source file
3357 // from which the preamble was built.
3358 if (Type == MK_Preamble) {
3359 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3360 } else if (Type == MK_MainFile) {
3361 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3362 }
3363 }
3364
3365 // For any Objective-C class definitions we have already loaded, make sure
3366 // that we load any additional categories.
3367 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3368 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3369 ObjCClassesLoaded[I],
3370 PreviousGeneration);
3371 }
Douglas Gregore060e572013-01-25 01:03:03 +00003372
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003373 if (PP.getHeaderSearchInfo()
3374 .getHeaderSearchOpts()
3375 .ModulesValidateOncePerBuildSession) {
3376 // Now we are certain that the module and all modules it depends on are
3377 // up to date. Create or update timestamp files for modules that are
3378 // located in the module cache (not for PCH files that could be anywhere
3379 // in the filesystem).
3380 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3381 ImportedModule &M = Loaded[I];
3382 if (M.Mod->Kind == MK_Module) {
3383 updateModuleTimestamp(*M.Mod);
3384 }
3385 }
3386 }
3387
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 return Success;
3389}
3390
3391ASTReader::ASTReadResult
3392ASTReader::ReadASTCore(StringRef FileName,
3393 ModuleKind Type,
3394 SourceLocation ImportLoc,
3395 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003396 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003397 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 unsigned ClientLoadCapabilities) {
3399 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003400 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003401 ModuleManager::AddModuleResult AddResult
3402 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3403 CurrentGeneration, ExpectedSize, ExpectedModTime,
3404 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003405
Douglas Gregor7029ce12013-03-19 00:28:20 +00003406 switch (AddResult) {
3407 case ModuleManager::AlreadyLoaded:
3408 return Success;
3409
3410 case ModuleManager::NewlyLoaded:
3411 // Load module file below.
3412 break;
3413
3414 case ModuleManager::Missing:
3415 // The module file was missing; if the client handle handle, that, return
3416 // it.
3417 if (ClientLoadCapabilities & ARR_Missing)
3418 return Missing;
3419
3420 // Otherwise, return an error.
3421 {
3422 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3423 + ErrorStr;
3424 Error(Msg);
3425 }
3426 return Failure;
3427
3428 case ModuleManager::OutOfDate:
3429 // We couldn't load the module file because it is out-of-date. If the
3430 // client can handle out-of-date, return it.
3431 if (ClientLoadCapabilities & ARR_OutOfDate)
3432 return OutOfDate;
3433
3434 // Otherwise, return an error.
3435 {
3436 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3437 + ErrorStr;
3438 Error(Msg);
3439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 return Failure;
3441 }
3442
Douglas Gregor7029ce12013-03-19 00:28:20 +00003443 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003444
3445 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3446 // module?
3447 if (FileName != "-") {
3448 CurrentDir = llvm::sys::path::parent_path(FileName);
3449 if (CurrentDir.empty()) CurrentDir = ".";
3450 }
3451
3452 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003453 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 Stream.init(F.StreamFile);
3455 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3456
3457 // Sniff for the signature.
3458 if (Stream.Read(8) != 'C' ||
3459 Stream.Read(8) != 'P' ||
3460 Stream.Read(8) != 'C' ||
3461 Stream.Read(8) != 'H') {
3462 Diag(diag::err_not_a_pch_file) << FileName;
3463 return Failure;
3464 }
3465
3466 // This is used for compatibility with older PCH formats.
3467 bool HaveReadControlBlock = false;
3468
Chris Lattnerefa77172013-01-20 00:00:22 +00003469 while (1) {
3470 llvm::BitstreamEntry Entry = Stream.advance();
3471
3472 switch (Entry.Kind) {
3473 case llvm::BitstreamEntry::Error:
3474 case llvm::BitstreamEntry::EndBlock:
3475 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 Error("invalid record at top-level of AST file");
3477 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003478
3479 case llvm::BitstreamEntry::SubBlock:
3480 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 }
3482
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003484 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3486 if (Stream.ReadBlockInfoBlock()) {
3487 Error("malformed BlockInfoBlock in AST file");
3488 return Failure;
3489 }
3490 break;
3491 case CONTROL_BLOCK_ID:
3492 HaveReadControlBlock = true;
3493 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3494 case Success:
3495 break;
3496
3497 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003498 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 case OutOfDate: return OutOfDate;
3500 case VersionMismatch: return VersionMismatch;
3501 case ConfigurationMismatch: return ConfigurationMismatch;
3502 case HadErrors: return HadErrors;
3503 }
3504 break;
3505 case AST_BLOCK_ID:
3506 if (!HaveReadControlBlock) {
3507 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003508 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 return VersionMismatch;
3510 }
3511
3512 // Record that we've loaded this module.
3513 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3514 return Success;
3515
3516 default:
3517 if (Stream.SkipBlock()) {
3518 Error("malformed block record in AST file");
3519 return Failure;
3520 }
3521 break;
3522 }
3523 }
3524
3525 return Success;
3526}
3527
3528void ASTReader::InitializeContext() {
3529 // If there's a listener, notify them that we "read" the translation unit.
3530 if (DeserializationListener)
3531 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3532 Context.getTranslationUnitDecl());
3533
3534 // Make sure we load the declaration update records for the translation unit,
3535 // if there are any.
3536 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3537 Context.getTranslationUnitDecl());
3538
3539 // FIXME: Find a better way to deal with collisions between these
3540 // built-in types. Right now, we just ignore the problem.
3541
3542 // Load the special types.
3543 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3544 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3545 if (!Context.CFConstantStringTypeDecl)
3546 Context.setCFConstantStringType(GetType(String));
3547 }
3548
3549 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3550 QualType FileType = GetType(File);
3551 if (FileType.isNull()) {
3552 Error("FILE type is NULL");
3553 return;
3554 }
3555
3556 if (!Context.FILEDecl) {
3557 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3558 Context.setFILEDecl(Typedef->getDecl());
3559 else {
3560 const TagType *Tag = FileType->getAs<TagType>();
3561 if (!Tag) {
3562 Error("Invalid FILE type in AST file");
3563 return;
3564 }
3565 Context.setFILEDecl(Tag->getDecl());
3566 }
3567 }
3568 }
3569
3570 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3571 QualType Jmp_bufType = GetType(Jmp_buf);
3572 if (Jmp_bufType.isNull()) {
3573 Error("jmp_buf type is NULL");
3574 return;
3575 }
3576
3577 if (!Context.jmp_bufDecl) {
3578 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3579 Context.setjmp_bufDecl(Typedef->getDecl());
3580 else {
3581 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3582 if (!Tag) {
3583 Error("Invalid jmp_buf type in AST file");
3584 return;
3585 }
3586 Context.setjmp_bufDecl(Tag->getDecl());
3587 }
3588 }
3589 }
3590
3591 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3592 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3593 if (Sigjmp_bufType.isNull()) {
3594 Error("sigjmp_buf type is NULL");
3595 return;
3596 }
3597
3598 if (!Context.sigjmp_bufDecl) {
3599 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3600 Context.setsigjmp_bufDecl(Typedef->getDecl());
3601 else {
3602 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3603 assert(Tag && "Invalid sigjmp_buf type in AST file");
3604 Context.setsigjmp_bufDecl(Tag->getDecl());
3605 }
3606 }
3607 }
3608
3609 if (unsigned ObjCIdRedef
3610 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3611 if (Context.ObjCIdRedefinitionType.isNull())
3612 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3613 }
3614
3615 if (unsigned ObjCClassRedef
3616 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3617 if (Context.ObjCClassRedefinitionType.isNull())
3618 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3619 }
3620
3621 if (unsigned ObjCSelRedef
3622 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3623 if (Context.ObjCSelRedefinitionType.isNull())
3624 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3625 }
3626
3627 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3628 QualType Ucontext_tType = GetType(Ucontext_t);
3629 if (Ucontext_tType.isNull()) {
3630 Error("ucontext_t type is NULL");
3631 return;
3632 }
3633
3634 if (!Context.ucontext_tDecl) {
3635 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3636 Context.setucontext_tDecl(Typedef->getDecl());
3637 else {
3638 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3639 assert(Tag && "Invalid ucontext_t type in AST file");
3640 Context.setucontext_tDecl(Tag->getDecl());
3641 }
3642 }
3643 }
3644 }
3645
3646 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3647
3648 // If there were any CUDA special declarations, deserialize them.
3649 if (!CUDASpecialDeclRefs.empty()) {
3650 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3651 Context.setcudaConfigureCallDecl(
3652 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3653 }
3654
3655 // Re-export any modules that were imported by a non-module AST file.
3656 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3657 if (Module *Imported = getSubmodule(ImportedModules[I]))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003658 makeModuleVisible(Imported, Module::AllVisible,
Douglas Gregorfb912652013-03-20 21:10:35 +00003659 /*ImportLoc=*/SourceLocation(),
3660 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 }
3662 ImportedModules.clear();
3663}
3664
3665void ASTReader::finalizeForWriting() {
3666 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3667 HiddenEnd = HiddenNamesMap.end();
3668 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003669 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 }
3671 HiddenNamesMap.clear();
3672}
3673
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003674/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3675/// cursor into the start of the given block ID, returning false on success and
3676/// true on failure.
3677static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003678 while (1) {
3679 llvm::BitstreamEntry Entry = Cursor.advance();
3680 switch (Entry.Kind) {
3681 case llvm::BitstreamEntry::Error:
3682 case llvm::BitstreamEntry::EndBlock:
3683 return true;
3684
3685 case llvm::BitstreamEntry::Record:
3686 // Ignore top-level records.
3687 Cursor.skipRecord(Entry.ID);
3688 break;
3689
3690 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003691 if (Entry.ID == BlockID) {
3692 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003693 return true;
3694 // Found it!
3695 return false;
3696 }
3697
3698 if (Cursor.SkipBlock())
3699 return true;
3700 }
3701 }
3702}
3703
Guy Benyei11169dd2012-12-18 14:30:41 +00003704/// \brief Retrieve the name of the original source file name
3705/// directly from the AST file, without actually loading the AST
3706/// file.
3707std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3708 FileManager &FileMgr,
3709 DiagnosticsEngine &Diags) {
3710 // Open the AST file.
3711 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003712 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3714 if (!Buffer) {
3715 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3716 return std::string();
3717 }
3718
3719 // Initialize the stream
3720 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003721 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3723 (const unsigned char *)Buffer->getBufferEnd());
3724 Stream.init(StreamFile);
3725
3726 // Sniff for the signature.
3727 if (Stream.Read(8) != 'C' ||
3728 Stream.Read(8) != 'P' ||
3729 Stream.Read(8) != 'C' ||
3730 Stream.Read(8) != 'H') {
3731 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3732 return std::string();
3733 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003734
Chris Lattnere7b154b2013-01-19 21:39:22 +00003735 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003736 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003737 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3738 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003739 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003740
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003741 // Scan for ORIGINAL_FILE inside the control block.
3742 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003743 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003744 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003745 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3746 return std::string();
3747
3748 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3749 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3750 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003754 StringRef Blob;
3755 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3756 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003758}
3759
3760namespace {
3761 class SimplePCHValidator : public ASTReaderListener {
3762 const LangOptions &ExistingLangOpts;
3763 const TargetOptions &ExistingTargetOpts;
3764 const PreprocessorOptions &ExistingPPOpts;
3765 FileManager &FileMgr;
3766
3767 public:
3768 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3769 const TargetOptions &ExistingTargetOpts,
3770 const PreprocessorOptions &ExistingPPOpts,
3771 FileManager &FileMgr)
3772 : ExistingLangOpts(ExistingLangOpts),
3773 ExistingTargetOpts(ExistingTargetOpts),
3774 ExistingPPOpts(ExistingPPOpts),
3775 FileMgr(FileMgr)
3776 {
3777 }
3778
3779 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3780 bool Complain) {
3781 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3782 }
3783 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3784 bool Complain) {
3785 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3786 }
3787 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3788 bool Complain,
3789 std::string &SuggestedPredefines) {
3790 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003791 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 }
3793 };
3794}
3795
3796bool ASTReader::readASTFileControlBlock(StringRef Filename,
3797 FileManager &FileMgr,
3798 ASTReaderListener &Listener) {
3799 // Open the AST file.
3800 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003801 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3803 if (!Buffer) {
3804 return true;
3805 }
3806
3807 // Initialize the stream
3808 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003809 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003810 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3811 (const unsigned char *)Buffer->getBufferEnd());
3812 Stream.init(StreamFile);
3813
3814 // Sniff for the signature.
3815 if (Stream.Read(8) != 'C' ||
3816 Stream.Read(8) != 'P' ||
3817 Stream.Read(8) != 'C' ||
3818 Stream.Read(8) != 'H') {
3819 return true;
3820 }
3821
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003822 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003823 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003824 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003825
3826 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003827 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003828 BitstreamCursor InputFilesCursor;
3829 if (NeedsInputFiles) {
3830 InputFilesCursor = Stream;
3831 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3832 return true;
3833
3834 // Read the abbreviations
3835 while (true) {
3836 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3837 unsigned Code = InputFilesCursor.ReadCode();
3838
3839 // We expect all abbrevs to be at the start of the block.
3840 if (Code != llvm::bitc::DEFINE_ABBREV) {
3841 InputFilesCursor.JumpToBit(Offset);
3842 break;
3843 }
3844 InputFilesCursor.ReadAbbrevRecord();
3845 }
3846 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003847
3848 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003850 while (1) {
3851 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3852 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3853 return false;
3854
3855 if (Entry.Kind != llvm::BitstreamEntry::Record)
3856 return true;
3857
Guy Benyei11169dd2012-12-18 14:30:41 +00003858 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003859 StringRef Blob;
3860 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003861 switch ((ControlRecordTypes)RecCode) {
3862 case METADATA: {
3863 if (Record[0] != VERSION_MAJOR)
3864 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003865
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003866 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003867 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003868
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003869 break;
3870 }
3871 case LANGUAGE_OPTIONS:
3872 if (ParseLanguageOptions(Record, false, Listener))
3873 return true;
3874 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003875
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003876 case TARGET_OPTIONS:
3877 if (ParseTargetOptions(Record, false, Listener))
3878 return true;
3879 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003880
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003881 case DIAGNOSTIC_OPTIONS:
3882 if (ParseDiagnosticOptions(Record, false, Listener))
3883 return true;
3884 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003885
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003886 case FILE_SYSTEM_OPTIONS:
3887 if (ParseFileSystemOptions(Record, false, Listener))
3888 return true;
3889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003890
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003891 case HEADER_SEARCH_OPTIONS:
3892 if (ParseHeaderSearchOptions(Record, false, Listener))
3893 return true;
3894 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003895
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003896 case PREPROCESSOR_OPTIONS: {
3897 std::string IgnoredSuggestedPredefines;
3898 if (ParsePreprocessorOptions(Record, false, Listener,
3899 IgnoredSuggestedPredefines))
3900 return true;
3901 break;
3902 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003903
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003904 case INPUT_FILE_OFFSETS: {
3905 if (!NeedsInputFiles)
3906 break;
3907
3908 unsigned NumInputFiles = Record[0];
3909 unsigned NumUserFiles = Record[1];
3910 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3911 for (unsigned I = 0; I != NumInputFiles; ++I) {
3912 // Go find this input file.
3913 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00003914
3915 if (isSystemFile && !NeedsSystemInputFiles)
3916 break; // the rest are system input files
3917
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003918 BitstreamCursor &Cursor = InputFilesCursor;
3919 SavedStreamPosition SavedPosition(Cursor);
3920 Cursor.JumpToBit(InputFileOffs[I]);
3921
3922 unsigned Code = Cursor.ReadCode();
3923 RecordData Record;
3924 StringRef Blob;
3925 bool shouldContinue = false;
3926 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3927 case INPUT_FILE:
3928 shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3929 break;
3930 }
3931 if (!shouldContinue)
3932 break;
3933 }
3934 break;
3935 }
3936
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003937 default:
3938 // No other validation to perform.
3939 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 }
3941 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003942}
3943
3944
3945bool ASTReader::isAcceptableASTFile(StringRef Filename,
3946 FileManager &FileMgr,
3947 const LangOptions &LangOpts,
3948 const TargetOptions &TargetOpts,
3949 const PreprocessorOptions &PPOpts) {
3950 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3951 return !readASTFileControlBlock(Filename, FileMgr, validator);
3952}
3953
3954bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3955 // Enter the submodule block.
3956 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3957 Error("malformed submodule block record in AST file");
3958 return true;
3959 }
3960
3961 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3962 bool First = true;
3963 Module *CurrentModule = 0;
3964 RecordData Record;
3965 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003966 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3967
3968 switch (Entry.Kind) {
3969 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3970 case llvm::BitstreamEntry::Error:
3971 Error("malformed block record in AST file");
3972 return true;
3973 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 return false;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003975 case llvm::BitstreamEntry::Record:
3976 // The interesting case.
3977 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003979
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003981 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003983 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 default: // Default behavior: ignore.
3985 break;
3986
3987 case SUBMODULE_DEFINITION: {
3988 if (First) {
3989 Error("missing submodule metadata record at beginning of block");
3990 return true;
3991 }
3992
Douglas Gregor8d932422013-03-20 03:59:18 +00003993 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 Error("malformed module definition");
3995 return true;
3996 }
3997
Chris Lattner0e6c9402013-01-20 02:38:54 +00003998 StringRef Name = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
4000 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
4001 bool IsFramework = Record[2];
4002 bool IsExplicit = Record[3];
4003 bool IsSystem = Record[4];
4004 bool InferSubmodules = Record[5];
4005 bool InferExplicitSubmodules = Record[6];
4006 bool InferExportWildcard = Record[7];
Douglas Gregor8d932422013-03-20 03:59:18 +00004007 bool ConfigMacrosExhaustive = Record[8];
4008
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 Module *ParentModule = 0;
4010 if (Parent)
4011 ParentModule = getSubmodule(Parent);
4012
4013 // Retrieve this (sub)module from the module map, creating it if
4014 // necessary.
4015 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4016 IsFramework,
4017 IsExplicit).first;
4018 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4019 if (GlobalIndex >= SubmodulesLoaded.size() ||
4020 SubmodulesLoaded[GlobalIndex]) {
4021 Error("too many submodules");
4022 return true;
4023 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004024
Douglas Gregor7029ce12013-03-19 00:28:20 +00004025 if (!ParentModule) {
4026 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4027 if (CurFile != F.File) {
4028 if (!Diags.isDiagnosticInFlight()) {
4029 Diag(diag::err_module_file_conflict)
4030 << CurrentModule->getTopLevelModuleName()
4031 << CurFile->getName()
4032 << F.File->getName();
4033 }
4034 return true;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004035 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004036 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004037
4038 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004039 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004040
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 CurrentModule->IsFromModuleFile = true;
4042 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4043 CurrentModule->InferSubmodules = InferSubmodules;
4044 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4045 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004046 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 if (DeserializationListener)
4048 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4049
4050 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004051
Douglas Gregorfb912652013-03-20 21:10:35 +00004052 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004053 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004054 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004055 CurrentModule->UnresolvedConflicts.clear();
4056 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 break;
4058 }
4059
4060 case SUBMODULE_UMBRELLA_HEADER: {
4061 if (First) {
4062 Error("missing submodule metadata record at beginning of block");
4063 return true;
4064 }
4065
4066 if (!CurrentModule)
4067 break;
4068
Chris Lattner0e6c9402013-01-20 02:38:54 +00004069 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 if (!CurrentModule->getUmbrellaHeader())
4071 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4072 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4073 Error("mismatched umbrella headers in submodule");
4074 return true;
4075 }
4076 }
4077 break;
4078 }
4079
4080 case SUBMODULE_HEADER: {
4081 if (First) {
4082 Error("missing submodule metadata record at beginning of block");
4083 return true;
4084 }
4085
4086 if (!CurrentModule)
4087 break;
4088
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004089 // We lazily associate headers with their modules via the HeaderInfoTable.
4090 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4091 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004092 break;
4093 }
4094
4095 case SUBMODULE_EXCLUDED_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
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004110 case SUBMODULE_PRIVATE_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
4119 // 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.
4122 break;
4123 }
4124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 case SUBMODULE_TOPHEADER: {
4126 if (First) {
4127 Error("missing submodule metadata record at beginning of block");
4128 return true;
4129 }
4130
4131 if (!CurrentModule)
4132 break;
4133
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004134 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 break;
4136 }
4137
4138 case SUBMODULE_UMBRELLA_DIR: {
4139 if (First) {
4140 Error("missing submodule metadata record at beginning of block");
4141 return true;
4142 }
4143
4144 if (!CurrentModule)
4145 break;
4146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004148 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 if (!CurrentModule->getUmbrellaDir())
4150 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4151 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4152 Error("mismatched umbrella directories in submodule");
4153 return true;
4154 }
4155 }
4156 break;
4157 }
4158
4159 case SUBMODULE_METADATA: {
4160 if (!First) {
4161 Error("submodule metadata record not at beginning of block");
4162 return true;
4163 }
4164 First = false;
4165
4166 F.BaseSubmoduleID = getTotalNumSubmodules();
4167 F.LocalNumSubmodules = Record[0];
4168 unsigned LocalBaseSubmoduleID = Record[1];
4169 if (F.LocalNumSubmodules > 0) {
4170 // Introduce the global -> local mapping for submodules within this
4171 // module.
4172 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4173
4174 // Introduce the local -> global mapping for submodules within this
4175 // module.
4176 F.SubmoduleRemap.insertOrReplace(
4177 std::make_pair(LocalBaseSubmoduleID,
4178 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4179
4180 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4181 }
4182 break;
4183 }
4184
4185 case SUBMODULE_IMPORTS: {
4186 if (First) {
4187 Error("missing submodule metadata record at beginning of block");
4188 return true;
4189 }
4190
4191 if (!CurrentModule)
4192 break;
4193
4194 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004195 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 Unresolved.File = &F;
4197 Unresolved.Mod = CurrentModule;
4198 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004199 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004201 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 }
4203 break;
4204 }
4205
4206 case SUBMODULE_EXPORTS: {
4207 if (First) {
4208 Error("missing submodule metadata record at beginning of block");
4209 return true;
4210 }
4211
4212 if (!CurrentModule)
4213 break;
4214
4215 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004216 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Unresolved.File = &F;
4218 Unresolved.Mod = CurrentModule;
4219 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004220 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004222 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 }
4224
4225 // Once we've loaded the set of exports, there's no reason to keep
4226 // the parsed, unresolved exports around.
4227 CurrentModule->UnresolvedExports.clear();
4228 break;
4229 }
4230 case SUBMODULE_REQUIRES: {
4231 if (First) {
4232 Error("missing submodule metadata record at beginning of block");
4233 return true;
4234 }
4235
4236 if (!CurrentModule)
4237 break;
4238
Richard Smitha3feee22013-10-28 22:18:19 +00004239 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 Context.getTargetInfo());
4241 break;
4242 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004243
4244 case SUBMODULE_LINK_LIBRARY:
4245 if (First) {
4246 Error("missing submodule metadata record at beginning of block");
4247 return true;
4248 }
4249
4250 if (!CurrentModule)
4251 break;
4252
4253 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004254 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004255 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004256
4257 case SUBMODULE_CONFIG_MACRO:
4258 if (First) {
4259 Error("missing submodule metadata record at beginning of block");
4260 return true;
4261 }
4262
4263 if (!CurrentModule)
4264 break;
4265
4266 CurrentModule->ConfigMacros.push_back(Blob.str());
4267 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004268
4269 case SUBMODULE_CONFLICT: {
4270 if (First) {
4271 Error("missing submodule metadata record at beginning of block");
4272 return true;
4273 }
4274
4275 if (!CurrentModule)
4276 break;
4277
4278 UnresolvedModuleRef Unresolved;
4279 Unresolved.File = &F;
4280 Unresolved.Mod = CurrentModule;
4281 Unresolved.ID = Record[0];
4282 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4283 Unresolved.IsWildcard = false;
4284 Unresolved.String = Blob;
4285 UnresolvedModuleRefs.push_back(Unresolved);
4286 break;
4287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 }
4289 }
4290}
4291
4292/// \brief Parse the record that corresponds to a LangOptions data
4293/// structure.
4294///
4295/// This routine parses the language options from the AST file and then gives
4296/// them to the AST listener if one is set.
4297///
4298/// \returns true if the listener deems the file unacceptable, false otherwise.
4299bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4300 bool Complain,
4301 ASTReaderListener &Listener) {
4302 LangOptions LangOpts;
4303 unsigned Idx = 0;
4304#define LANGOPT(Name, Bits, Default, Description) \
4305 LangOpts.Name = Record[Idx++];
4306#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4307 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4308#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004309#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4310#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004311
4312 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4313 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4314 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4315
4316 unsigned Length = Record[Idx++];
4317 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4318 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004319
4320 Idx += Length;
4321
4322 // Comment options.
4323 for (unsigned N = Record[Idx++]; N; --N) {
4324 LangOpts.CommentOpts.BlockCommandNames.push_back(
4325 ReadString(Record, Idx));
4326 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004327 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004328
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 return Listener.ReadLanguageOptions(LangOpts, Complain);
4330}
4331
4332bool ASTReader::ParseTargetOptions(const RecordData &Record,
4333 bool Complain,
4334 ASTReaderListener &Listener) {
4335 unsigned Idx = 0;
4336 TargetOptions TargetOpts;
4337 TargetOpts.Triple = ReadString(Record, Idx);
4338 TargetOpts.CPU = ReadString(Record, Idx);
4339 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4341 for (unsigned N = Record[Idx++]; N; --N) {
4342 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4343 }
4344 for (unsigned N = Record[Idx++]; N; --N) {
4345 TargetOpts.Features.push_back(ReadString(Record, Idx));
4346 }
4347
4348 return Listener.ReadTargetOptions(TargetOpts, Complain);
4349}
4350
4351bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4352 ASTReaderListener &Listener) {
4353 DiagnosticOptions DiagOpts;
4354 unsigned Idx = 0;
4355#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4356#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4357 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4358#include "clang/Basic/DiagnosticOptions.def"
4359
4360 for (unsigned N = Record[Idx++]; N; --N) {
4361 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4362 }
4363
4364 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4365}
4366
4367bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4368 ASTReaderListener &Listener) {
4369 FileSystemOptions FSOpts;
4370 unsigned Idx = 0;
4371 FSOpts.WorkingDir = ReadString(Record, Idx);
4372 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4373}
4374
4375bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4376 bool Complain,
4377 ASTReaderListener &Listener) {
4378 HeaderSearchOptions HSOpts;
4379 unsigned Idx = 0;
4380 HSOpts.Sysroot = ReadString(Record, Idx);
4381
4382 // Include entries.
4383 for (unsigned N = Record[Idx++]; N; --N) {
4384 std::string Path = ReadString(Record, Idx);
4385 frontend::IncludeDirGroup Group
4386 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 bool IsFramework = Record[Idx++];
4388 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004390 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004391 }
4392
4393 // System header prefixes.
4394 for (unsigned N = Record[Idx++]; N; --N) {
4395 std::string Prefix = ReadString(Record, Idx);
4396 bool IsSystemHeader = Record[Idx++];
4397 HSOpts.SystemHeaderPrefixes.push_back(
4398 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4399 }
4400
4401 HSOpts.ResourceDir = ReadString(Record, Idx);
4402 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004403 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 HSOpts.DisableModuleHash = Record[Idx++];
4405 HSOpts.UseBuiltinIncludes = Record[Idx++];
4406 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4407 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4408 HSOpts.UseLibcxx = Record[Idx++];
4409
4410 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4411}
4412
4413bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4414 bool Complain,
4415 ASTReaderListener &Listener,
4416 std::string &SuggestedPredefines) {
4417 PreprocessorOptions PPOpts;
4418 unsigned Idx = 0;
4419
4420 // Macro definitions/undefs
4421 for (unsigned N = Record[Idx++]; N; --N) {
4422 std::string Macro = ReadString(Record, Idx);
4423 bool IsUndef = Record[Idx++];
4424 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4425 }
4426
4427 // Includes
4428 for (unsigned N = Record[Idx++]; N; --N) {
4429 PPOpts.Includes.push_back(ReadString(Record, Idx));
4430 }
4431
4432 // Macro Includes
4433 for (unsigned N = Record[Idx++]; N; --N) {
4434 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4435 }
4436
4437 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004438 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4440 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4441 PPOpts.ObjCXXARCStandardLibrary =
4442 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4443 SuggestedPredefines.clear();
4444 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4445 SuggestedPredefines);
4446}
4447
4448std::pair<ModuleFile *, unsigned>
4449ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4450 GlobalPreprocessedEntityMapType::iterator
4451 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4452 assert(I != GlobalPreprocessedEntityMap.end() &&
4453 "Corrupted global preprocessed entity map");
4454 ModuleFile *M = I->second;
4455 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4456 return std::make_pair(M, LocalIndex);
4457}
4458
4459std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4460ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4461 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4462 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4463 Mod.NumPreprocessedEntities);
4464
4465 return std::make_pair(PreprocessingRecord::iterator(),
4466 PreprocessingRecord::iterator());
4467}
4468
4469std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4470ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4471 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4472 ModuleDeclIterator(this, &Mod,
4473 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4474}
4475
4476PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4477 PreprocessedEntityID PPID = Index+1;
4478 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4479 ModuleFile &M = *PPInfo.first;
4480 unsigned LocalIndex = PPInfo.second;
4481 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4482
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 if (!PP.getPreprocessingRecord()) {
4484 Error("no preprocessing record");
4485 return 0;
4486 }
4487
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004488 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4489 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4490
4491 llvm::BitstreamEntry Entry =
4492 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4493 if (Entry.Kind != llvm::BitstreamEntry::Record)
4494 return 0;
4495
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 // Read the record.
4497 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4498 ReadSourceLocation(M, PPOffs.End));
4499 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004500 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 RecordData Record;
4502 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004503 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4504 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 switch (RecType) {
4506 case PPD_MACRO_EXPANSION: {
4507 bool isBuiltin = Record[0];
4508 IdentifierInfo *Name = 0;
4509 MacroDefinition *Def = 0;
4510 if (isBuiltin)
4511 Name = getLocalIdentifier(M, Record[1]);
4512 else {
4513 PreprocessedEntityID
4514 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4515 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4516 }
4517
4518 MacroExpansion *ME;
4519 if (isBuiltin)
4520 ME = new (PPRec) MacroExpansion(Name, Range);
4521 else
4522 ME = new (PPRec) MacroExpansion(Def, Range);
4523
4524 return ME;
4525 }
4526
4527 case PPD_MACRO_DEFINITION: {
4528 // Decode the identifier info and then check again; if the macro is
4529 // still defined and associated with the identifier,
4530 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4531 MacroDefinition *MD
4532 = new (PPRec) MacroDefinition(II, Range);
4533
4534 if (DeserializationListener)
4535 DeserializationListener->MacroDefinitionRead(PPID, MD);
4536
4537 return MD;
4538 }
4539
4540 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004541 const char *FullFileNameStart = Blob.data() + Record[0];
4542 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 const FileEntry *File = 0;
4544 if (!FullFileName.empty())
4545 File = PP.getFileManager().getFile(FullFileName);
4546
4547 // FIXME: Stable encoding
4548 InclusionDirective::InclusionKind Kind
4549 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4550 InclusionDirective *ID
4551 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004552 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 Record[1], Record[3],
4554 File,
4555 Range);
4556 return ID;
4557 }
4558 }
4559
4560 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4561}
4562
4563/// \brief \arg SLocMapI points at a chunk of a module that contains no
4564/// preprocessed entities or the entities it contains are not the ones we are
4565/// looking for. Find the next module that contains entities and return the ID
4566/// of the first entry.
4567PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4568 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4569 ++SLocMapI;
4570 for (GlobalSLocOffsetMapType::const_iterator
4571 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4572 ModuleFile &M = *SLocMapI->second;
4573 if (M.NumPreprocessedEntities)
4574 return M.BasePreprocessedEntityID;
4575 }
4576
4577 return getTotalNumPreprocessedEntities();
4578}
4579
4580namespace {
4581
4582template <unsigned PPEntityOffset::*PPLoc>
4583struct PPEntityComp {
4584 const ASTReader &Reader;
4585 ModuleFile &M;
4586
4587 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4588
4589 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4590 SourceLocation LHS = getLoc(L);
4591 SourceLocation RHS = getLoc(R);
4592 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4593 }
4594
4595 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4596 SourceLocation LHS = getLoc(L);
4597 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4598 }
4599
4600 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4601 SourceLocation RHS = getLoc(R);
4602 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4603 }
4604
4605 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4606 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4607 }
4608};
4609
4610}
4611
4612/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4613PreprocessedEntityID
4614ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4615 if (SourceMgr.isLocalSourceLocation(BLoc))
4616 return getTotalNumPreprocessedEntities();
4617
4618 GlobalSLocOffsetMapType::const_iterator
4619 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004620 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4622 "Corrupted global sloc offset map");
4623
4624 if (SLocMapI->second->NumPreprocessedEntities == 0)
4625 return findNextPreprocessedEntity(SLocMapI);
4626
4627 ModuleFile &M = *SLocMapI->second;
4628 typedef const PPEntityOffset *pp_iterator;
4629 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4630 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4631
4632 size_t Count = M.NumPreprocessedEntities;
4633 size_t Half;
4634 pp_iterator First = pp_begin;
4635 pp_iterator PPI;
4636
4637 // Do a binary search manually instead of using std::lower_bound because
4638 // The end locations of entities may be unordered (when a macro expansion
4639 // is inside another macro argument), but for this case it is not important
4640 // whether we get the first macro expansion or its containing macro.
4641 while (Count > 0) {
4642 Half = Count/2;
4643 PPI = First;
4644 std::advance(PPI, Half);
4645 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4646 BLoc)){
4647 First = PPI;
4648 ++First;
4649 Count = Count - Half - 1;
4650 } else
4651 Count = Half;
4652 }
4653
4654 if (PPI == pp_end)
4655 return findNextPreprocessedEntity(SLocMapI);
4656
4657 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4658}
4659
4660/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4661PreprocessedEntityID
4662ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4663 if (SourceMgr.isLocalSourceLocation(ELoc))
4664 return getTotalNumPreprocessedEntities();
4665
4666 GlobalSLocOffsetMapType::const_iterator
4667 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004668 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4670 "Corrupted global sloc offset map");
4671
4672 if (SLocMapI->second->NumPreprocessedEntities == 0)
4673 return findNextPreprocessedEntity(SLocMapI);
4674
4675 ModuleFile &M = *SLocMapI->second;
4676 typedef const PPEntityOffset *pp_iterator;
4677 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4678 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4679 pp_iterator PPI =
4680 std::upper_bound(pp_begin, pp_end, ELoc,
4681 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4682
4683 if (PPI == pp_end)
4684 return findNextPreprocessedEntity(SLocMapI);
4685
4686 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4687}
4688
4689/// \brief Returns a pair of [Begin, End) indices of preallocated
4690/// preprocessed entities that \arg Range encompasses.
4691std::pair<unsigned, unsigned>
4692 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4693 if (Range.isInvalid())
4694 return std::make_pair(0,0);
4695 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4696
4697 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4698 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4699 return std::make_pair(BeginID, EndID);
4700}
4701
4702/// \brief Optionally returns true or false if the preallocated preprocessed
4703/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004704Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 FileID FID) {
4706 if (FID.isInvalid())
4707 return false;
4708
4709 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4710 ModuleFile &M = *PPInfo.first;
4711 unsigned LocalIndex = PPInfo.second;
4712 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4713
4714 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4715 if (Loc.isInvalid())
4716 return false;
4717
4718 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4719 return true;
4720 else
4721 return false;
4722}
4723
4724namespace {
4725 /// \brief Visitor used to search for information about a header file.
4726 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 const FileEntry *FE;
4728
David Blaikie05785d12013-02-20 22:23:23 +00004729 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004730
4731 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004732 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4733 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004734
4735 static bool visit(ModuleFile &M, void *UserData) {
4736 HeaderFileInfoVisitor *This
4737 = static_cast<HeaderFileInfoVisitor *>(UserData);
4738
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 HeaderFileInfoLookupTable *Table
4740 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4741 if (!Table)
4742 return false;
4743
4744 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004745 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 if (Pos == Table->end())
4747 return false;
4748
4749 This->HFI = *Pos;
4750 return true;
4751 }
4752
David Blaikie05785d12013-02-20 22:23:23 +00004753 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 };
4755}
4756
4757HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004758 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004760 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004762
4763 return HeaderFileInfo();
4764}
4765
4766void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4767 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004768 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4770 ModuleFile &F = *(*I);
4771 unsigned Idx = 0;
4772 DiagStates.clear();
4773 assert(!Diag.DiagStates.empty());
4774 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4775 while (Idx < F.PragmaDiagMappings.size()) {
4776 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4777 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4778 if (DiagStateID != 0) {
4779 Diag.DiagStatePoints.push_back(
4780 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4781 FullSourceLoc(Loc, SourceMgr)));
4782 continue;
4783 }
4784
4785 assert(DiagStateID == 0);
4786 // A new DiagState was created here.
4787 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4788 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4789 DiagStates.push_back(NewState);
4790 Diag.DiagStatePoints.push_back(
4791 DiagnosticsEngine::DiagStatePoint(NewState,
4792 FullSourceLoc(Loc, SourceMgr)));
4793 while (1) {
4794 assert(Idx < F.PragmaDiagMappings.size() &&
4795 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4796 if (Idx >= F.PragmaDiagMappings.size()) {
4797 break; // Something is messed up but at least avoid infinite loop in
4798 // release build.
4799 }
4800 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4801 if (DiagID == (unsigned)-1) {
4802 break; // no more diag/map pairs for this location.
4803 }
4804 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4805 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4806 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4807 }
4808 }
4809 }
4810}
4811
4812/// \brief Get the correct cursor and offset for loading a type.
4813ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4814 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4815 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4816 ModuleFile *M = I->second;
4817 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4818}
4819
4820/// \brief Read and return the type with the given index..
4821///
4822/// The index is the type ID, shifted and minus the number of predefs. This
4823/// routine actually reads the record corresponding to the type at the given
4824/// location. It is a helper routine for GetType, which deals with reading type
4825/// IDs.
4826QualType ASTReader::readTypeRecord(unsigned Index) {
4827 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004828 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004829
4830 // Keep track of where we are in the stream, then jump back there
4831 // after reading this type.
4832 SavedStreamPosition SavedPosition(DeclsCursor);
4833
4834 ReadingKindTracker ReadingKind(Read_Type, *this);
4835
4836 // Note that we are loading a type record.
4837 Deserializing AType(this);
4838
4839 unsigned Idx = 0;
4840 DeclsCursor.JumpToBit(Loc.Offset);
4841 RecordData Record;
4842 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004843 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 case TYPE_EXT_QUAL: {
4845 if (Record.size() != 2) {
4846 Error("Incorrect encoding of extended qualifier type");
4847 return QualType();
4848 }
4849 QualType Base = readType(*Loc.F, Record, Idx);
4850 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4851 return Context.getQualifiedType(Base, Quals);
4852 }
4853
4854 case TYPE_COMPLEX: {
4855 if (Record.size() != 1) {
4856 Error("Incorrect encoding of complex type");
4857 return QualType();
4858 }
4859 QualType ElemType = readType(*Loc.F, Record, Idx);
4860 return Context.getComplexType(ElemType);
4861 }
4862
4863 case TYPE_POINTER: {
4864 if (Record.size() != 1) {
4865 Error("Incorrect encoding of pointer type");
4866 return QualType();
4867 }
4868 QualType PointeeType = readType(*Loc.F, Record, Idx);
4869 return Context.getPointerType(PointeeType);
4870 }
4871
Reid Kleckner8a365022013-06-24 17:51:48 +00004872 case TYPE_DECAYED: {
4873 if (Record.size() != 1) {
4874 Error("Incorrect encoding of decayed type");
4875 return QualType();
4876 }
4877 QualType OriginalType = readType(*Loc.F, Record, Idx);
4878 QualType DT = Context.getAdjustedParameterType(OriginalType);
4879 if (!isa<DecayedType>(DT))
4880 Error("Decayed type does not decay");
4881 return DT;
4882 }
4883
Reid Kleckner0503a872013-12-05 01:23:43 +00004884 case TYPE_ADJUSTED: {
4885 if (Record.size() != 2) {
4886 Error("Incorrect encoding of adjusted type");
4887 return QualType();
4888 }
4889 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4890 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4891 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4892 }
4893
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 case TYPE_BLOCK_POINTER: {
4895 if (Record.size() != 1) {
4896 Error("Incorrect encoding of block pointer type");
4897 return QualType();
4898 }
4899 QualType PointeeType = readType(*Loc.F, Record, Idx);
4900 return Context.getBlockPointerType(PointeeType);
4901 }
4902
4903 case TYPE_LVALUE_REFERENCE: {
4904 if (Record.size() != 2) {
4905 Error("Incorrect encoding of lvalue reference type");
4906 return QualType();
4907 }
4908 QualType PointeeType = readType(*Loc.F, Record, Idx);
4909 return Context.getLValueReferenceType(PointeeType, Record[1]);
4910 }
4911
4912 case TYPE_RVALUE_REFERENCE: {
4913 if (Record.size() != 1) {
4914 Error("Incorrect encoding of rvalue reference type");
4915 return QualType();
4916 }
4917 QualType PointeeType = readType(*Loc.F, Record, Idx);
4918 return Context.getRValueReferenceType(PointeeType);
4919 }
4920
4921 case TYPE_MEMBER_POINTER: {
4922 if (Record.size() != 2) {
4923 Error("Incorrect encoding of member pointer type");
4924 return QualType();
4925 }
4926 QualType PointeeType = readType(*Loc.F, Record, Idx);
4927 QualType ClassType = readType(*Loc.F, Record, Idx);
4928 if (PointeeType.isNull() || ClassType.isNull())
4929 return QualType();
4930
4931 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4932 }
4933
4934 case TYPE_CONSTANT_ARRAY: {
4935 QualType ElementType = readType(*Loc.F, Record, Idx);
4936 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4937 unsigned IndexTypeQuals = Record[2];
4938 unsigned Idx = 3;
4939 llvm::APInt Size = ReadAPInt(Record, Idx);
4940 return Context.getConstantArrayType(ElementType, Size,
4941 ASM, IndexTypeQuals);
4942 }
4943
4944 case TYPE_INCOMPLETE_ARRAY: {
4945 QualType ElementType = readType(*Loc.F, Record, Idx);
4946 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4947 unsigned IndexTypeQuals = Record[2];
4948 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4949 }
4950
4951 case TYPE_VARIABLE_ARRAY: {
4952 QualType ElementType = readType(*Loc.F, Record, Idx);
4953 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4954 unsigned IndexTypeQuals = Record[2];
4955 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4956 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4957 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4958 ASM, IndexTypeQuals,
4959 SourceRange(LBLoc, RBLoc));
4960 }
4961
4962 case TYPE_VECTOR: {
4963 if (Record.size() != 3) {
4964 Error("incorrect encoding of vector type in AST file");
4965 return QualType();
4966 }
4967
4968 QualType ElementType = readType(*Loc.F, Record, Idx);
4969 unsigned NumElements = Record[1];
4970 unsigned VecKind = Record[2];
4971 return Context.getVectorType(ElementType, NumElements,
4972 (VectorType::VectorKind)VecKind);
4973 }
4974
4975 case TYPE_EXT_VECTOR: {
4976 if (Record.size() != 3) {
4977 Error("incorrect encoding of extended vector type in AST file");
4978 return QualType();
4979 }
4980
4981 QualType ElementType = readType(*Loc.F, Record, Idx);
4982 unsigned NumElements = Record[1];
4983 return Context.getExtVectorType(ElementType, NumElements);
4984 }
4985
4986 case TYPE_FUNCTION_NO_PROTO: {
4987 if (Record.size() != 6) {
4988 Error("incorrect encoding of no-proto function type");
4989 return QualType();
4990 }
4991 QualType ResultType = readType(*Loc.F, Record, Idx);
4992 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4993 (CallingConv)Record[4], Record[5]);
4994 return Context.getFunctionNoProtoType(ResultType, Info);
4995 }
4996
4997 case TYPE_FUNCTION_PROTO: {
4998 QualType ResultType = readType(*Loc.F, Record, Idx);
4999
5000 FunctionProtoType::ExtProtoInfo EPI;
5001 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5002 /*hasregparm*/ Record[2],
5003 /*regparm*/ Record[3],
5004 static_cast<CallingConv>(Record[4]),
5005 /*produces*/ Record[5]);
5006
5007 unsigned Idx = 6;
5008 unsigned NumParams = Record[Idx++];
5009 SmallVector<QualType, 16> ParamTypes;
5010 for (unsigned I = 0; I != NumParams; ++I)
5011 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5012
5013 EPI.Variadic = Record[Idx++];
5014 EPI.HasTrailingReturn = Record[Idx++];
5015 EPI.TypeQuals = Record[Idx++];
5016 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5017 ExceptionSpecificationType EST =
5018 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5019 EPI.ExceptionSpecType = EST;
5020 SmallVector<QualType, 2> Exceptions;
5021 if (EST == EST_Dynamic) {
5022 EPI.NumExceptions = Record[Idx++];
5023 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5024 Exceptions.push_back(readType(*Loc.F, Record, Idx));
5025 EPI.Exceptions = Exceptions.data();
5026 } else if (EST == EST_ComputedNoexcept) {
5027 EPI.NoexceptExpr = ReadExpr(*Loc.F);
5028 } else if (EST == EST_Uninstantiated) {
5029 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5030 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5031 } else if (EST == EST_Unevaluated) {
5032 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5033 }
Jordan Rose5c382722013-03-08 21:51:21 +00005034 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 }
5036
5037 case TYPE_UNRESOLVED_USING: {
5038 unsigned Idx = 0;
5039 return Context.getTypeDeclType(
5040 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5041 }
5042
5043 case TYPE_TYPEDEF: {
5044 if (Record.size() != 2) {
5045 Error("incorrect encoding of typedef type");
5046 return QualType();
5047 }
5048 unsigned Idx = 0;
5049 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5050 QualType Canonical = readType(*Loc.F, Record, Idx);
5051 if (!Canonical.isNull())
5052 Canonical = Context.getCanonicalType(Canonical);
5053 return Context.getTypedefType(Decl, Canonical);
5054 }
5055
5056 case TYPE_TYPEOF_EXPR:
5057 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5058
5059 case TYPE_TYPEOF: {
5060 if (Record.size() != 1) {
5061 Error("incorrect encoding of typeof(type) in AST file");
5062 return QualType();
5063 }
5064 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5065 return Context.getTypeOfType(UnderlyingType);
5066 }
5067
5068 case TYPE_DECLTYPE: {
5069 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5070 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5071 }
5072
5073 case TYPE_UNARY_TRANSFORM: {
5074 QualType BaseType = readType(*Loc.F, Record, Idx);
5075 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5076 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5077 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5078 }
5079
Richard Smith74aeef52013-04-26 16:15:35 +00005080 case TYPE_AUTO: {
5081 QualType Deduced = readType(*Loc.F, Record, Idx);
5082 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005083 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005084 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005086
5087 case TYPE_RECORD: {
5088 if (Record.size() != 2) {
5089 Error("incorrect encoding of record type");
5090 return QualType();
5091 }
5092 unsigned Idx = 0;
5093 bool IsDependent = Record[Idx++];
5094 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5095 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5096 QualType T = Context.getRecordType(RD);
5097 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5098 return T;
5099 }
5100
5101 case TYPE_ENUM: {
5102 if (Record.size() != 2) {
5103 Error("incorrect encoding of enum type");
5104 return QualType();
5105 }
5106 unsigned Idx = 0;
5107 bool IsDependent = Record[Idx++];
5108 QualType T
5109 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5110 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5111 return T;
5112 }
5113
5114 case TYPE_ATTRIBUTED: {
5115 if (Record.size() != 3) {
5116 Error("incorrect encoding of attributed type");
5117 return QualType();
5118 }
5119 QualType modifiedType = readType(*Loc.F, Record, Idx);
5120 QualType equivalentType = readType(*Loc.F, Record, Idx);
5121 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5122 return Context.getAttributedType(kind, modifiedType, equivalentType);
5123 }
5124
5125 case TYPE_PAREN: {
5126 if (Record.size() != 1) {
5127 Error("incorrect encoding of paren type");
5128 return QualType();
5129 }
5130 QualType InnerType = readType(*Loc.F, Record, Idx);
5131 return Context.getParenType(InnerType);
5132 }
5133
5134 case TYPE_PACK_EXPANSION: {
5135 if (Record.size() != 2) {
5136 Error("incorrect encoding of pack expansion type");
5137 return QualType();
5138 }
5139 QualType Pattern = readType(*Loc.F, Record, Idx);
5140 if (Pattern.isNull())
5141 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005142 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 if (Record[1])
5144 NumExpansions = Record[1] - 1;
5145 return Context.getPackExpansionType(Pattern, NumExpansions);
5146 }
5147
5148 case TYPE_ELABORATED: {
5149 unsigned Idx = 0;
5150 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5151 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5152 QualType NamedType = readType(*Loc.F, Record, Idx);
5153 return Context.getElaboratedType(Keyword, NNS, NamedType);
5154 }
5155
5156 case TYPE_OBJC_INTERFACE: {
5157 unsigned Idx = 0;
5158 ObjCInterfaceDecl *ItfD
5159 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5160 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5161 }
5162
5163 case TYPE_OBJC_OBJECT: {
5164 unsigned Idx = 0;
5165 QualType Base = readType(*Loc.F, Record, Idx);
5166 unsigned NumProtos = Record[Idx++];
5167 SmallVector<ObjCProtocolDecl*, 4> Protos;
5168 for (unsigned I = 0; I != NumProtos; ++I)
5169 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5170 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5171 }
5172
5173 case TYPE_OBJC_OBJECT_POINTER: {
5174 unsigned Idx = 0;
5175 QualType Pointee = readType(*Loc.F, Record, Idx);
5176 return Context.getObjCObjectPointerType(Pointee);
5177 }
5178
5179 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5180 unsigned Idx = 0;
5181 QualType Parm = readType(*Loc.F, Record, Idx);
5182 QualType Replacement = readType(*Loc.F, Record, Idx);
5183 return
5184 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
5185 Replacement);
5186 }
5187
5188 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5189 unsigned Idx = 0;
5190 QualType Parm = readType(*Loc.F, Record, Idx);
5191 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5192 return Context.getSubstTemplateTypeParmPackType(
5193 cast<TemplateTypeParmType>(Parm),
5194 ArgPack);
5195 }
5196
5197 case TYPE_INJECTED_CLASS_NAME: {
5198 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5199 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5200 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5201 // for AST reading, too much interdependencies.
5202 return
5203 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5204 }
5205
5206 case TYPE_TEMPLATE_TYPE_PARM: {
5207 unsigned Idx = 0;
5208 unsigned Depth = Record[Idx++];
5209 unsigned Index = Record[Idx++];
5210 bool Pack = Record[Idx++];
5211 TemplateTypeParmDecl *D
5212 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5213 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5214 }
5215
5216 case TYPE_DEPENDENT_NAME: {
5217 unsigned Idx = 0;
5218 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5219 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5220 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5221 QualType Canon = readType(*Loc.F, Record, Idx);
5222 if (!Canon.isNull())
5223 Canon = Context.getCanonicalType(Canon);
5224 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5225 }
5226
5227 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5228 unsigned Idx = 0;
5229 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5230 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5231 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5232 unsigned NumArgs = Record[Idx++];
5233 SmallVector<TemplateArgument, 8> Args;
5234 Args.reserve(NumArgs);
5235 while (NumArgs--)
5236 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5237 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5238 Args.size(), Args.data());
5239 }
5240
5241 case TYPE_DEPENDENT_SIZED_ARRAY: {
5242 unsigned Idx = 0;
5243
5244 // ArrayType
5245 QualType ElementType = readType(*Loc.F, Record, Idx);
5246 ArrayType::ArraySizeModifier ASM
5247 = (ArrayType::ArraySizeModifier)Record[Idx++];
5248 unsigned IndexTypeQuals = Record[Idx++];
5249
5250 // DependentSizedArrayType
5251 Expr *NumElts = ReadExpr(*Loc.F);
5252 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5253
5254 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5255 IndexTypeQuals, Brackets);
5256 }
5257
5258 case TYPE_TEMPLATE_SPECIALIZATION: {
5259 unsigned Idx = 0;
5260 bool IsDependent = Record[Idx++];
5261 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5262 SmallVector<TemplateArgument, 8> Args;
5263 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5264 QualType Underlying = readType(*Loc.F, Record, Idx);
5265 QualType T;
5266 if (Underlying.isNull())
5267 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5268 Args.size());
5269 else
5270 T = Context.getTemplateSpecializationType(Name, Args.data(),
5271 Args.size(), Underlying);
5272 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5273 return T;
5274 }
5275
5276 case TYPE_ATOMIC: {
5277 if (Record.size() != 1) {
5278 Error("Incorrect encoding of atomic type");
5279 return QualType();
5280 }
5281 QualType ValueType = readType(*Loc.F, Record, Idx);
5282 return Context.getAtomicType(ValueType);
5283 }
5284 }
5285 llvm_unreachable("Invalid TypeCode!");
5286}
5287
5288class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5289 ASTReader &Reader;
5290 ModuleFile &F;
5291 const ASTReader::RecordData &Record;
5292 unsigned &Idx;
5293
5294 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5295 unsigned &I) {
5296 return Reader.ReadSourceLocation(F, R, I);
5297 }
5298
5299 template<typename T>
5300 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5301 return Reader.ReadDeclAs<T>(F, Record, Idx);
5302 }
5303
5304public:
5305 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5306 const ASTReader::RecordData &Record, unsigned &Idx)
5307 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5308 { }
5309
5310 // We want compile-time assurance that we've enumerated all of
5311 // these, so unfortunately we have to declare them first, then
5312 // define them out-of-line.
5313#define ABSTRACT_TYPELOC(CLASS, PARENT)
5314#define TYPELOC(CLASS, PARENT) \
5315 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5316#include "clang/AST/TypeLocNodes.def"
5317
5318 void VisitFunctionTypeLoc(FunctionTypeLoc);
5319 void VisitArrayTypeLoc(ArrayTypeLoc);
5320};
5321
5322void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5323 // nothing to do
5324}
5325void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5326 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5327 if (TL.needsExtraLocalData()) {
5328 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5329 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5330 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5331 TL.setModeAttr(Record[Idx++]);
5332 }
5333}
5334void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5335 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5336}
5337void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5338 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5339}
Reid Kleckner8a365022013-06-24 17:51:48 +00005340void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5341 // nothing to do
5342}
Reid Kleckner0503a872013-12-05 01:23:43 +00005343void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5344 // nothing to do
5345}
Guy Benyei11169dd2012-12-18 14:30:41 +00005346void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5347 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5348}
5349void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5350 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5351}
5352void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5353 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5354}
5355void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5356 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5357 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5358}
5359void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5360 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5361 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5362 if (Record[Idx++])
5363 TL.setSizeExpr(Reader.ReadExpr(F));
5364 else
5365 TL.setSizeExpr(0);
5366}
5367void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5368 VisitArrayTypeLoc(TL);
5369}
5370void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5371 VisitArrayTypeLoc(TL);
5372}
5373void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5374 VisitArrayTypeLoc(TL);
5375}
5376void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5377 DependentSizedArrayTypeLoc TL) {
5378 VisitArrayTypeLoc(TL);
5379}
5380void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5381 DependentSizedExtVectorTypeLoc TL) {
5382 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5383}
5384void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5385 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5386}
5387void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5388 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5389}
5390void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5391 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5392 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5393 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5394 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005395 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5396 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005397 }
5398}
5399void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5400 VisitFunctionTypeLoc(TL);
5401}
5402void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5403 VisitFunctionTypeLoc(TL);
5404}
5405void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5406 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5407}
5408void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5409 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5410}
5411void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5412 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5413 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5414 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5415}
5416void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5417 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5418 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5419 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5420 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5421}
5422void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5423 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5424}
5425void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5426 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5427 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5428 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5429 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5430}
5431void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5432 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5433}
5434void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5435 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5436}
5437void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5438 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5439}
5440void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5441 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5442 if (TL.hasAttrOperand()) {
5443 SourceRange range;
5444 range.setBegin(ReadSourceLocation(Record, Idx));
5445 range.setEnd(ReadSourceLocation(Record, Idx));
5446 TL.setAttrOperandParensRange(range);
5447 }
5448 if (TL.hasAttrExprOperand()) {
5449 if (Record[Idx++])
5450 TL.setAttrExprOperand(Reader.ReadExpr(F));
5451 else
5452 TL.setAttrExprOperand(0);
5453 } else if (TL.hasAttrEnumOperand())
5454 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5455}
5456void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5457 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5458}
5459void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5460 SubstTemplateTypeParmTypeLoc TL) {
5461 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5462}
5463void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5464 SubstTemplateTypeParmPackTypeLoc TL) {
5465 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5466}
5467void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5468 TemplateSpecializationTypeLoc TL) {
5469 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5470 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5471 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5472 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5473 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5474 TL.setArgLocInfo(i,
5475 Reader.GetTemplateArgumentLocInfo(F,
5476 TL.getTypePtr()->getArg(i).getKind(),
5477 Record, Idx));
5478}
5479void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5480 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5481 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5482}
5483void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5484 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5485 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5486}
5487void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5488 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5489}
5490void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5491 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5492 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5493 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5494}
5495void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5496 DependentTemplateSpecializationTypeLoc TL) {
5497 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5498 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5499 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5500 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5501 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5502 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5503 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5504 TL.setArgLocInfo(I,
5505 Reader.GetTemplateArgumentLocInfo(F,
5506 TL.getTypePtr()->getArg(I).getKind(),
5507 Record, Idx));
5508}
5509void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5510 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5511}
5512void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5513 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5514}
5515void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5516 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5517 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5518 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5519 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5520 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5521}
5522void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5523 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5524}
5525void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5526 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5527 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5528 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5529}
5530
5531TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5532 const RecordData &Record,
5533 unsigned &Idx) {
5534 QualType InfoTy = readType(F, Record, Idx);
5535 if (InfoTy.isNull())
5536 return 0;
5537
5538 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5539 TypeLocReader TLR(*this, F, Record, Idx);
5540 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5541 TLR.Visit(TL);
5542 return TInfo;
5543}
5544
5545QualType ASTReader::GetType(TypeID ID) {
5546 unsigned FastQuals = ID & Qualifiers::FastMask;
5547 unsigned Index = ID >> Qualifiers::FastWidth;
5548
5549 if (Index < NUM_PREDEF_TYPE_IDS) {
5550 QualType T;
5551 switch ((PredefinedTypeIDs)Index) {
5552 case PREDEF_TYPE_NULL_ID: return QualType();
5553 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5554 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5555
5556 case PREDEF_TYPE_CHAR_U_ID:
5557 case PREDEF_TYPE_CHAR_S_ID:
5558 // FIXME: Check that the signedness of CharTy is correct!
5559 T = Context.CharTy;
5560 break;
5561
5562 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5563 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5564 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5565 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5566 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5567 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5568 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5569 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5570 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5571 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5572 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5573 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5574 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5575 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5576 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5577 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5578 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5579 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5580 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5581 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5582 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5583 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5584 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5585 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5586 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5587 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5588 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5589 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005590 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5591 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5592 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5593 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5594 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5595 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005596 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005597 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005598 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5599
5600 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5601 T = Context.getAutoRRefDeductType();
5602 break;
5603
5604 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5605 T = Context.ARCUnbridgedCastTy;
5606 break;
5607
5608 case PREDEF_TYPE_VA_LIST_TAG:
5609 T = Context.getVaListTagType();
5610 break;
5611
5612 case PREDEF_TYPE_BUILTIN_FN:
5613 T = Context.BuiltinFnTy;
5614 break;
5615 }
5616
5617 assert(!T.isNull() && "Unknown predefined type");
5618 return T.withFastQualifiers(FastQuals);
5619 }
5620
5621 Index -= NUM_PREDEF_TYPE_IDS;
5622 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5623 if (TypesLoaded[Index].isNull()) {
5624 TypesLoaded[Index] = readTypeRecord(Index);
5625 if (TypesLoaded[Index].isNull())
5626 return QualType();
5627
5628 TypesLoaded[Index]->setFromAST();
5629 if (DeserializationListener)
5630 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5631 TypesLoaded[Index]);
5632 }
5633
5634 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5635}
5636
5637QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5638 return GetType(getGlobalTypeID(F, LocalID));
5639}
5640
5641serialization::TypeID
5642ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5643 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5644 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5645
5646 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5647 return LocalID;
5648
5649 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5650 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5651 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5652
5653 unsigned GlobalIndex = LocalIndex + I->second;
5654 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5655}
5656
5657TemplateArgumentLocInfo
5658ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5659 TemplateArgument::ArgKind Kind,
5660 const RecordData &Record,
5661 unsigned &Index) {
5662 switch (Kind) {
5663 case TemplateArgument::Expression:
5664 return ReadExpr(F);
5665 case TemplateArgument::Type:
5666 return GetTypeSourceInfo(F, Record, Index);
5667 case TemplateArgument::Template: {
5668 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5669 Index);
5670 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5671 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5672 SourceLocation());
5673 }
5674 case TemplateArgument::TemplateExpansion: {
5675 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5676 Index);
5677 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5678 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5679 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5680 EllipsisLoc);
5681 }
5682 case TemplateArgument::Null:
5683 case TemplateArgument::Integral:
5684 case TemplateArgument::Declaration:
5685 case TemplateArgument::NullPtr:
5686 case TemplateArgument::Pack:
5687 // FIXME: Is this right?
5688 return TemplateArgumentLocInfo();
5689 }
5690 llvm_unreachable("unexpected template argument loc");
5691}
5692
5693TemplateArgumentLoc
5694ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5695 const RecordData &Record, unsigned &Index) {
5696 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5697
5698 if (Arg.getKind() == TemplateArgument::Expression) {
5699 if (Record[Index++]) // bool InfoHasSameExpr.
5700 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5701 }
5702 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5703 Record, Index));
5704}
5705
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005706const ASTTemplateArgumentListInfo*
5707ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5708 const RecordData &Record,
5709 unsigned &Index) {
5710 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5711 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5712 unsigned NumArgsAsWritten = Record[Index++];
5713 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5714 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5715 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5716 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5717}
5718
Guy Benyei11169dd2012-12-18 14:30:41 +00005719Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5720 return GetDecl(ID);
5721}
5722
5723uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5724 unsigned &Idx){
5725 if (Idx >= Record.size())
5726 return 0;
5727
5728 unsigned LocalID = Record[Idx++];
5729 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5730}
5731
5732CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5733 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005734 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005735 SavedStreamPosition SavedPosition(Cursor);
5736 Cursor.JumpToBit(Loc.Offset);
5737 ReadingKindTracker ReadingKind(Read_Decl, *this);
5738 RecordData Record;
5739 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005740 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005741 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5742 Error("Malformed AST file: missing C++ base specifiers");
5743 return 0;
5744 }
5745
5746 unsigned Idx = 0;
5747 unsigned NumBases = Record[Idx++];
5748 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5749 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5750 for (unsigned I = 0; I != NumBases; ++I)
5751 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5752 return Bases;
5753}
5754
5755serialization::DeclID
5756ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5757 if (LocalID < NUM_PREDEF_DECL_IDS)
5758 return LocalID;
5759
5760 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5761 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5762 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5763
5764 return LocalID + I->second;
5765}
5766
5767bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5768 ModuleFile &M) const {
5769 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5770 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5771 return &M == I->second;
5772}
5773
Douglas Gregor9f782892013-01-21 15:25:38 +00005774ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005775 if (!D->isFromASTFile())
5776 return 0;
5777 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5778 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5779 return I->second;
5780}
5781
5782SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5783 if (ID < NUM_PREDEF_DECL_IDS)
5784 return SourceLocation();
5785
5786 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5787
5788 if (Index > DeclsLoaded.size()) {
5789 Error("declaration ID out-of-range for AST file");
5790 return SourceLocation();
5791 }
5792
5793 if (Decl *D = DeclsLoaded[Index])
5794 return D->getLocation();
5795
5796 unsigned RawLocation = 0;
5797 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5798 return ReadSourceLocation(*Rec.F, RawLocation);
5799}
5800
5801Decl *ASTReader::GetDecl(DeclID ID) {
5802 if (ID < NUM_PREDEF_DECL_IDS) {
5803 switch ((PredefinedDeclIDs)ID) {
5804 case PREDEF_DECL_NULL_ID:
5805 return 0;
5806
5807 case PREDEF_DECL_TRANSLATION_UNIT_ID:
5808 return Context.getTranslationUnitDecl();
5809
5810 case PREDEF_DECL_OBJC_ID_ID:
5811 return Context.getObjCIdDecl();
5812
5813 case PREDEF_DECL_OBJC_SEL_ID:
5814 return Context.getObjCSelDecl();
5815
5816 case PREDEF_DECL_OBJC_CLASS_ID:
5817 return Context.getObjCClassDecl();
5818
5819 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5820 return Context.getObjCProtocolDecl();
5821
5822 case PREDEF_DECL_INT_128_ID:
5823 return Context.getInt128Decl();
5824
5825 case PREDEF_DECL_UNSIGNED_INT_128_ID:
5826 return Context.getUInt128Decl();
5827
5828 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5829 return Context.getObjCInstanceTypeDecl();
5830
5831 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5832 return Context.getBuiltinVaListDecl();
5833 }
5834 }
5835
5836 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5837
5838 if (Index >= DeclsLoaded.size()) {
5839 assert(0 && "declaration ID out-of-range for AST file");
5840 Error("declaration ID out-of-range for AST file");
5841 return 0;
5842 }
5843
5844 if (!DeclsLoaded[Index]) {
5845 ReadDeclRecord(ID);
5846 if (DeserializationListener)
5847 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5848 }
5849
5850 return DeclsLoaded[Index];
5851}
5852
5853DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5854 DeclID GlobalID) {
5855 if (GlobalID < NUM_PREDEF_DECL_IDS)
5856 return GlobalID;
5857
5858 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5859 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5860 ModuleFile *Owner = I->second;
5861
5862 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5863 = M.GlobalToLocalDeclIDs.find(Owner);
5864 if (Pos == M.GlobalToLocalDeclIDs.end())
5865 return 0;
5866
5867 return GlobalID - Owner->BaseDeclID + Pos->second;
5868}
5869
5870serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5871 const RecordData &Record,
5872 unsigned &Idx) {
5873 if (Idx >= Record.size()) {
5874 Error("Corrupted AST file");
5875 return 0;
5876 }
5877
5878 return getGlobalDeclID(F, Record[Idx++]);
5879}
5880
5881/// \brief Resolve the offset of a statement into a statement.
5882///
5883/// This operation will read a new statement from the external
5884/// source each time it is called, and is meant to be used via a
5885/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5886Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5887 // Switch case IDs are per Decl.
5888 ClearSwitchCaseIDs();
5889
5890 // Offset here is a global offset across the entire chain.
5891 RecordLocation Loc = getLocalBitOffset(Offset);
5892 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5893 return ReadStmtFromStream(*Loc.F);
5894}
5895
5896namespace {
5897 class FindExternalLexicalDeclsVisitor {
5898 ASTReader &Reader;
5899 const DeclContext *DC;
5900 bool (*isKindWeWant)(Decl::Kind);
5901
5902 SmallVectorImpl<Decl*> &Decls;
5903 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5904
5905 public:
5906 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5907 bool (*isKindWeWant)(Decl::Kind),
5908 SmallVectorImpl<Decl*> &Decls)
5909 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5910 {
5911 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5912 PredefsVisited[I] = false;
5913 }
5914
5915 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5916 if (Preorder)
5917 return false;
5918
5919 FindExternalLexicalDeclsVisitor *This
5920 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5921
5922 ModuleFile::DeclContextInfosMap::iterator Info
5923 = M.DeclContextInfos.find(This->DC);
5924 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5925 return false;
5926
5927 // Load all of the declaration IDs
5928 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5929 *IDE = ID + Info->second.NumLexicalDecls;
5930 ID != IDE; ++ID) {
5931 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5932 continue;
5933
5934 // Don't add predefined declarations to the lexical context more
5935 // than once.
5936 if (ID->second < NUM_PREDEF_DECL_IDS) {
5937 if (This->PredefsVisited[ID->second])
5938 continue;
5939
5940 This->PredefsVisited[ID->second] = true;
5941 }
5942
5943 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5944 if (!This->DC->isDeclInLexicalTraversal(D))
5945 This->Decls.push_back(D);
5946 }
5947 }
5948
5949 return false;
5950 }
5951 };
5952}
5953
5954ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5955 bool (*isKindWeWant)(Decl::Kind),
5956 SmallVectorImpl<Decl*> &Decls) {
5957 // There might be lexical decls in multiple modules, for the TU at
5958 // least. Walk all of the modules in the order they were loaded.
5959 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5960 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5961 ++NumLexicalDeclContextsRead;
5962 return ELR_Success;
5963}
5964
5965namespace {
5966
5967class DeclIDComp {
5968 ASTReader &Reader;
5969 ModuleFile &Mod;
5970
5971public:
5972 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5973
5974 bool operator()(LocalDeclID L, LocalDeclID R) const {
5975 SourceLocation LHS = getLocation(L);
5976 SourceLocation RHS = getLocation(R);
5977 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5978 }
5979
5980 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5981 SourceLocation RHS = getLocation(R);
5982 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5983 }
5984
5985 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5986 SourceLocation LHS = getLocation(L);
5987 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5988 }
5989
5990 SourceLocation getLocation(LocalDeclID ID) const {
5991 return Reader.getSourceManager().getFileLoc(
5992 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5993 }
5994};
5995
5996}
5997
5998void ASTReader::FindFileRegionDecls(FileID File,
5999 unsigned Offset, unsigned Length,
6000 SmallVectorImpl<Decl *> &Decls) {
6001 SourceManager &SM = getSourceManager();
6002
6003 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6004 if (I == FileDeclIDs.end())
6005 return;
6006
6007 FileDeclsInfo &DInfo = I->second;
6008 if (DInfo.Decls.empty())
6009 return;
6010
6011 SourceLocation
6012 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6013 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6014
6015 DeclIDComp DIDComp(*this, *DInfo.Mod);
6016 ArrayRef<serialization::LocalDeclID>::iterator
6017 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6018 BeginLoc, DIDComp);
6019 if (BeginIt != DInfo.Decls.begin())
6020 --BeginIt;
6021
6022 // If we are pointing at a top-level decl inside an objc container, we need
6023 // to backtrack until we find it otherwise we will fail to report that the
6024 // region overlaps with an objc container.
6025 while (BeginIt != DInfo.Decls.begin() &&
6026 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6027 ->isTopLevelDeclInObjCContainer())
6028 --BeginIt;
6029
6030 ArrayRef<serialization::LocalDeclID>::iterator
6031 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6032 EndLoc, DIDComp);
6033 if (EndIt != DInfo.Decls.end())
6034 ++EndIt;
6035
6036 for (ArrayRef<serialization::LocalDeclID>::iterator
6037 DIt = BeginIt; DIt != EndIt; ++DIt)
6038 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6039}
6040
6041namespace {
6042 /// \brief ModuleFile visitor used to perform name lookup into a
6043 /// declaration context.
6044 class DeclContextNameLookupVisitor {
6045 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006046 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 DeclarationName Name;
6048 SmallVectorImpl<NamedDecl *> &Decls;
6049
6050 public:
6051 DeclContextNameLookupVisitor(ASTReader &Reader,
6052 SmallVectorImpl<const DeclContext *> &Contexts,
6053 DeclarationName Name,
6054 SmallVectorImpl<NamedDecl *> &Decls)
6055 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6056
6057 static bool visit(ModuleFile &M, void *UserData) {
6058 DeclContextNameLookupVisitor *This
6059 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6060
6061 // Check whether we have any visible declaration information for
6062 // this context in this module.
6063 ModuleFile::DeclContextInfosMap::iterator Info;
6064 bool FoundInfo = false;
6065 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6066 Info = M.DeclContextInfos.find(This->Contexts[I]);
6067 if (Info != M.DeclContextInfos.end() &&
6068 Info->second.NameLookupTableData) {
6069 FoundInfo = true;
6070 break;
6071 }
6072 }
6073
6074 if (!FoundInfo)
6075 return false;
6076
6077 // Look for this name within this module.
6078 ASTDeclContextNameLookupTable *LookupTable =
6079 Info->second.NameLookupTableData;
6080 ASTDeclContextNameLookupTable::iterator Pos
6081 = LookupTable->find(This->Name);
6082 if (Pos == LookupTable->end())
6083 return false;
6084
6085 bool FoundAnything = false;
6086 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6087 for (; Data.first != Data.second; ++Data.first) {
6088 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6089 if (!ND)
6090 continue;
6091
6092 if (ND->getDeclName() != This->Name) {
6093 // A name might be null because the decl's redeclarable part is
6094 // currently read before reading its name. The lookup is triggered by
6095 // building that decl (likely indirectly), and so it is later in the
6096 // sense of "already existing" and can be ignored here.
6097 continue;
6098 }
6099
6100 // Record this declaration.
6101 FoundAnything = true;
6102 This->Decls.push_back(ND);
6103 }
6104
6105 return FoundAnything;
6106 }
6107 };
6108}
6109
Douglas Gregor9f782892013-01-21 15:25:38 +00006110/// \brief Retrieve the "definitive" module file for the definition of the
6111/// given declaration context, if there is one.
6112///
6113/// The "definitive" module file is the only place where we need to look to
6114/// find information about the declarations within the given declaration
6115/// context. For example, C++ and Objective-C classes, C structs/unions, and
6116/// Objective-C protocols, categories, and extensions are all defined in a
6117/// single place in the source code, so they have definitive module files
6118/// associated with them. C++ namespaces, on the other hand, can have
6119/// definitions in multiple different module files.
6120///
6121/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6122/// NDEBUG checking.
6123static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6124 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006125 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6126 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006127
6128 return 0;
6129}
6130
Richard Smith9ce12e32013-02-07 03:30:24 +00006131bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006132ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6133 DeclarationName Name) {
6134 assert(DC->hasExternalVisibleStorage() &&
6135 "DeclContext has no visible decls in storage");
6136 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006137 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006138
6139 SmallVector<NamedDecl *, 64> Decls;
6140
6141 // Compute the declaration contexts we need to look into. Multiple such
6142 // declaration contexts occur when two declaration contexts from disjoint
6143 // modules get merged, e.g., when two namespaces with the same name are
6144 // independently defined in separate modules.
6145 SmallVector<const DeclContext *, 2> Contexts;
6146 Contexts.push_back(DC);
6147
6148 if (DC->isNamespace()) {
6149 MergedDeclsMap::iterator Merged
6150 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6151 if (Merged != MergedDecls.end()) {
6152 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6153 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6154 }
6155 }
6156
6157 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006158
6159 // If we can definitively determine which module file to look into,
6160 // only look there. Otherwise, look in all module files.
6161 ModuleFile *Definitive;
6162 if (Contexts.size() == 1 &&
6163 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6164 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6165 } else {
6166 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006168 ++NumVisibleDeclContextsRead;
6169 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006170 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006171}
6172
6173namespace {
6174 /// \brief ModuleFile visitor used to retrieve all visible names in a
6175 /// declaration context.
6176 class DeclContextAllNamesVisitor {
6177 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006178 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006179 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006180 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006181
6182 public:
6183 DeclContextAllNamesVisitor(ASTReader &Reader,
6184 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006185 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006186 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006187
6188 static bool visit(ModuleFile &M, void *UserData) {
6189 DeclContextAllNamesVisitor *This
6190 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6191
6192 // Check whether we have any visible declaration information for
6193 // this context in this module.
6194 ModuleFile::DeclContextInfosMap::iterator Info;
6195 bool FoundInfo = false;
6196 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6197 Info = M.DeclContextInfos.find(This->Contexts[I]);
6198 if (Info != M.DeclContextInfos.end() &&
6199 Info->second.NameLookupTableData) {
6200 FoundInfo = true;
6201 break;
6202 }
6203 }
6204
6205 if (!FoundInfo)
6206 return false;
6207
6208 ASTDeclContextNameLookupTable *LookupTable =
6209 Info->second.NameLookupTableData;
6210 bool FoundAnything = false;
6211 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006212 I = LookupTable->data_begin(), E = LookupTable->data_end();
6213 I != E;
6214 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 ASTDeclContextNameLookupTrait::data_type Data = *I;
6216 for (; Data.first != Data.second; ++Data.first) {
6217 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6218 *Data.first);
6219 if (!ND)
6220 continue;
6221
6222 // Record this declaration.
6223 FoundAnything = true;
6224 This->Decls[ND->getDeclName()].push_back(ND);
6225 }
6226 }
6227
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006228 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 }
6230 };
6231}
6232
6233void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6234 if (!DC->hasExternalVisibleStorage())
6235 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006236 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006237
6238 // Compute the declaration contexts we need to look into. Multiple such
6239 // declaration contexts occur when two declaration contexts from disjoint
6240 // modules get merged, e.g., when two namespaces with the same name are
6241 // independently defined in separate modules.
6242 SmallVector<const DeclContext *, 2> Contexts;
6243 Contexts.push_back(DC);
6244
6245 if (DC->isNamespace()) {
6246 MergedDeclsMap::iterator Merged
6247 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6248 if (Merged != MergedDecls.end()) {
6249 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6250 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6251 }
6252 }
6253
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006254 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6255 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006256 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6257 ++NumVisibleDeclContextsRead;
6258
Craig Topper79be4cd2013-07-05 04:33:53 +00006259 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006260 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6261 }
6262 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6263}
6264
6265/// \brief Under non-PCH compilation the consumer receives the objc methods
6266/// before receiving the implementation, and codegen depends on this.
6267/// We simulate this by deserializing and passing to consumer the methods of the
6268/// implementation before passing the deserialized implementation decl.
6269static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6270 ASTConsumer *Consumer) {
6271 assert(ImplD && Consumer);
6272
6273 for (ObjCImplDecl::method_iterator
6274 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
6275 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
6276
6277 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6278}
6279
6280void ASTReader::PassInterestingDeclsToConsumer() {
6281 assert(Consumer);
6282 while (!InterestingDecls.empty()) {
6283 Decl *D = InterestingDecls.front();
6284 InterestingDecls.pop_front();
6285
6286 PassInterestingDeclToConsumer(D);
6287 }
6288}
6289
6290void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6291 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6292 PassObjCImplDeclToConsumer(ImplD, Consumer);
6293 else
6294 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6295}
6296
6297void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6298 this->Consumer = Consumer;
6299
6300 if (!Consumer)
6301 return;
6302
Ben Langmuir332aafe2014-01-31 01:06:56 +00006303 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 // Force deserialization of this decl, which will cause it to be queued for
6305 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006306 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006308 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006309
6310 PassInterestingDeclsToConsumer();
6311}
6312
6313void ASTReader::PrintStats() {
6314 std::fprintf(stderr, "*** AST File Statistics:\n");
6315
6316 unsigned NumTypesLoaded
6317 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6318 QualType());
6319 unsigned NumDeclsLoaded
6320 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6321 (Decl *)0);
6322 unsigned NumIdentifiersLoaded
6323 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6324 IdentifiersLoaded.end(),
6325 (IdentifierInfo *)0);
6326 unsigned NumMacrosLoaded
6327 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6328 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006329 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 unsigned NumSelectorsLoaded
6331 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6332 SelectorsLoaded.end(),
6333 Selector());
6334
6335 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6336 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6337 NumSLocEntriesRead, TotalNumSLocEntries,
6338 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6339 if (!TypesLoaded.empty())
6340 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6341 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6342 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6343 if (!DeclsLoaded.empty())
6344 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6345 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6346 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6347 if (!IdentifiersLoaded.empty())
6348 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6349 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6350 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6351 if (!MacrosLoaded.empty())
6352 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6353 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6354 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6355 if (!SelectorsLoaded.empty())
6356 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6357 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6358 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6359 if (TotalNumStatements)
6360 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6361 NumStatementsRead, TotalNumStatements,
6362 ((float)NumStatementsRead/TotalNumStatements * 100));
6363 if (TotalNumMacros)
6364 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6365 NumMacrosRead, TotalNumMacros,
6366 ((float)NumMacrosRead/TotalNumMacros * 100));
6367 if (TotalLexicalDeclContexts)
6368 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6369 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6370 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6371 * 100));
6372 if (TotalVisibleDeclContexts)
6373 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6374 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6375 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6376 * 100));
6377 if (TotalNumMethodPoolEntries) {
6378 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6379 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6380 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6381 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006383 if (NumMethodPoolLookups) {
6384 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6385 NumMethodPoolHits, NumMethodPoolLookups,
6386 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6387 }
6388 if (NumMethodPoolTableLookups) {
6389 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6390 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6391 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6392 * 100.0));
6393 }
6394
Douglas Gregor00a50f72013-01-25 00:38:33 +00006395 if (NumIdentifierLookupHits) {
6396 std::fprintf(stderr,
6397 " %u / %u identifier table lookups succeeded (%f%%)\n",
6398 NumIdentifierLookupHits, NumIdentifierLookups,
6399 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6400 }
6401
Douglas Gregore060e572013-01-25 01:03:03 +00006402 if (GlobalIndex) {
6403 std::fprintf(stderr, "\n");
6404 GlobalIndex->printStats();
6405 }
6406
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 std::fprintf(stderr, "\n");
6408 dump();
6409 std::fprintf(stderr, "\n");
6410}
6411
6412template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6413static void
6414dumpModuleIDMap(StringRef Name,
6415 const ContinuousRangeMap<Key, ModuleFile *,
6416 InitialCapacity> &Map) {
6417 if (Map.begin() == Map.end())
6418 return;
6419
6420 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6421 llvm::errs() << Name << ":\n";
6422 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6423 I != IEnd; ++I) {
6424 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6425 << "\n";
6426 }
6427}
6428
6429void ASTReader::dump() {
6430 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6431 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6432 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6433 dumpModuleIDMap("Global type map", GlobalTypeMap);
6434 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6435 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6436 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6437 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6438 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6439 dumpModuleIDMap("Global preprocessed entity map",
6440 GlobalPreprocessedEntityMap);
6441
6442 llvm::errs() << "\n*** PCH/Modules Loaded:";
6443 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6444 MEnd = ModuleMgr.end();
6445 M != MEnd; ++M)
6446 (*M)->dump();
6447}
6448
6449/// Return the amount of memory used by memory buffers, breaking down
6450/// by heap-backed versus mmap'ed memory.
6451void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6452 for (ModuleConstIterator I = ModuleMgr.begin(),
6453 E = ModuleMgr.end(); I != E; ++I) {
6454 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6455 size_t bytes = buf->getBufferSize();
6456 switch (buf->getBufferKind()) {
6457 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6458 sizes.malloc_bytes += bytes;
6459 break;
6460 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6461 sizes.mmap_bytes += bytes;
6462 break;
6463 }
6464 }
6465 }
6466}
6467
6468void ASTReader::InitializeSema(Sema &S) {
6469 SemaObj = &S;
6470 S.addExternalSource(this);
6471
6472 // Makes sure any declarations that were deserialized "too early"
6473 // still get added to the identifier's declaration chains.
6474 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006475 pushExternalDeclIntoScope(PreloadedDecls[I],
6476 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 }
6478 PreloadedDecls.clear();
6479
Richard Smith3d8e97e2013-10-18 06:54:39 +00006480 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 if (!FPPragmaOptions.empty()) {
6482 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6483 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6484 }
6485
Richard Smith3d8e97e2013-10-18 06:54:39 +00006486 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 if (!OpenCLExtensions.empty()) {
6488 unsigned I = 0;
6489#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6490#include "clang/Basic/OpenCLExtensions.def"
6491
6492 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6493 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006494
6495 UpdateSema();
6496}
6497
6498void ASTReader::UpdateSema() {
6499 assert(SemaObj && "no Sema to update");
6500
6501 // Load the offsets of the declarations that Sema references.
6502 // They will be lazily deserialized when needed.
6503 if (!SemaDeclRefs.empty()) {
6504 assert(SemaDeclRefs.size() % 2 == 0);
6505 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6506 if (!SemaObj->StdNamespace)
6507 SemaObj->StdNamespace = SemaDeclRefs[I];
6508 if (!SemaObj->StdBadAlloc)
6509 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6510 }
6511 SemaDeclRefs.clear();
6512 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006513}
6514
6515IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6516 // Note that we are loading an identifier.
6517 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006518 StringRef Name(NameStart, NameEnd - NameStart);
6519
6520 // If there is a global index, look there first to determine which modules
6521 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006522 GlobalModuleIndex::HitSet Hits;
6523 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006524 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006525 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6526 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006527 }
6528 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006529 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006530 NumIdentifierLookups,
6531 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006532 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 IdentifierInfo *II = Visitor.getIdentifierInfo();
6534 markIdentifierUpToDate(II);
6535 return II;
6536}
6537
6538namespace clang {
6539 /// \brief An identifier-lookup iterator that enumerates all of the
6540 /// identifiers stored within a set of AST files.
6541 class ASTIdentifierIterator : public IdentifierIterator {
6542 /// \brief The AST reader whose identifiers are being enumerated.
6543 const ASTReader &Reader;
6544
6545 /// \brief The current index into the chain of AST files stored in
6546 /// the AST reader.
6547 unsigned Index;
6548
6549 /// \brief The current position within the identifier lookup table
6550 /// of the current AST file.
6551 ASTIdentifierLookupTable::key_iterator Current;
6552
6553 /// \brief The end position within the identifier lookup table of
6554 /// the current AST file.
6555 ASTIdentifierLookupTable::key_iterator End;
6556
6557 public:
6558 explicit ASTIdentifierIterator(const ASTReader &Reader);
6559
6560 virtual StringRef Next();
6561 };
6562}
6563
6564ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6565 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6566 ASTIdentifierLookupTable *IdTable
6567 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6568 Current = IdTable->key_begin();
6569 End = IdTable->key_end();
6570}
6571
6572StringRef ASTIdentifierIterator::Next() {
6573 while (Current == End) {
6574 // If we have exhausted all of our AST files, we're done.
6575 if (Index == 0)
6576 return StringRef();
6577
6578 --Index;
6579 ASTIdentifierLookupTable *IdTable
6580 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6581 IdentifierLookupTable;
6582 Current = IdTable->key_begin();
6583 End = IdTable->key_end();
6584 }
6585
6586 // We have any identifiers remaining in the current AST file; return
6587 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006588 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006590 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006591}
6592
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006593IdentifierIterator *ASTReader::getIdentifiers() {
6594 if (!loadGlobalIndex())
6595 return GlobalIndex->createIdentifierIterator();
6596
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 return new ASTIdentifierIterator(*this);
6598}
6599
6600namespace clang { namespace serialization {
6601 class ReadMethodPoolVisitor {
6602 ASTReader &Reader;
6603 Selector Sel;
6604 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006605 unsigned InstanceBits;
6606 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006607 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6608 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006609
6610 public:
6611 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6612 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006613 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6614 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006615
6616 static bool visit(ModuleFile &M, void *UserData) {
6617 ReadMethodPoolVisitor *This
6618 = static_cast<ReadMethodPoolVisitor *>(UserData);
6619
6620 if (!M.SelectorLookupTable)
6621 return false;
6622
6623 // If we've already searched this module file, skip it now.
6624 if (M.Generation <= This->PriorGeneration)
6625 return true;
6626
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006627 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 ASTSelectorLookupTable *PoolTable
6629 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6630 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6631 if (Pos == PoolTable->end())
6632 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006633
6634 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 ++This->Reader.NumSelectorsRead;
6636 // FIXME: Not quite happy with the statistics here. We probably should
6637 // disable this tracking when called via LoadSelector.
6638 // Also, should entries without methods count as misses?
6639 ++This->Reader.NumMethodPoolEntriesRead;
6640 ASTSelectorLookupTrait::data_type Data = *Pos;
6641 if (This->Reader.DeserializationListener)
6642 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6643 This->Sel);
6644
6645 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6646 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006647 This->InstanceBits = Data.InstanceBits;
6648 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 return true;
6650 }
6651
6652 /// \brief Retrieve the instance methods found by this visitor.
6653 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6654 return InstanceMethods;
6655 }
6656
6657 /// \brief Retrieve the instance methods found by this visitor.
6658 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6659 return FactoryMethods;
6660 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006661
6662 unsigned getInstanceBits() const { return InstanceBits; }
6663 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 };
6665} } // end namespace clang::serialization
6666
6667/// \brief Add the given set of methods to the method list.
6668static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6669 ObjCMethodList &List) {
6670 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6671 S.addMethodToGlobalList(&List, Methods[I]);
6672 }
6673}
6674
6675void ASTReader::ReadMethodPool(Selector Sel) {
6676 // Get the selector generation and update it to the current generation.
6677 unsigned &Generation = SelectorGeneration[Sel];
6678 unsigned PriorGeneration = Generation;
6679 Generation = CurrentGeneration;
6680
6681 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006682 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6684 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6685
6686 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006687 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006689
6690 ++NumMethodPoolHits;
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 if (!getSema())
6693 return;
6694
6695 Sema &S = *getSema();
6696 Sema::GlobalMethodPool::iterator Pos
6697 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6698
6699 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6700 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006701 Pos->second.first.setBits(Visitor.getInstanceBits());
6702 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006703}
6704
6705void ASTReader::ReadKnownNamespaces(
6706 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6707 Namespaces.clear();
6708
6709 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6710 if (NamespaceDecl *Namespace
6711 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6712 Namespaces.push_back(Namespace);
6713 }
6714}
6715
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006716void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006717 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006718 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6719 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006720 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006721 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006722 Undefined.insert(std::make_pair(D, Loc));
6723 }
6724}
Nick Lewycky8334af82013-01-26 00:35:08 +00006725
Guy Benyei11169dd2012-12-18 14:30:41 +00006726void ASTReader::ReadTentativeDefinitions(
6727 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6728 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6729 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6730 if (Var)
6731 TentativeDefs.push_back(Var);
6732 }
6733 TentativeDefinitions.clear();
6734}
6735
6736void ASTReader::ReadUnusedFileScopedDecls(
6737 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6738 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6739 DeclaratorDecl *D
6740 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6741 if (D)
6742 Decls.push_back(D);
6743 }
6744 UnusedFileScopedDecls.clear();
6745}
6746
6747void ASTReader::ReadDelegatingConstructors(
6748 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6749 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6750 CXXConstructorDecl *D
6751 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6752 if (D)
6753 Decls.push_back(D);
6754 }
6755 DelegatingCtorDecls.clear();
6756}
6757
6758void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6759 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6760 TypedefNameDecl *D
6761 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6762 if (D)
6763 Decls.push_back(D);
6764 }
6765 ExtVectorDecls.clear();
6766}
6767
6768void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6769 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6770 CXXRecordDecl *D
6771 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6772 if (D)
6773 Decls.push_back(D);
6774 }
6775 DynamicClasses.clear();
6776}
6777
6778void
Richard Smith78165b52013-01-10 23:43:47 +00006779ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6780 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6781 NamedDecl *D
6782 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 if (D)
6784 Decls.push_back(D);
6785 }
Richard Smith78165b52013-01-10 23:43:47 +00006786 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006787}
6788
6789void ASTReader::ReadReferencedSelectors(
6790 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6791 if (ReferencedSelectorsData.empty())
6792 return;
6793
6794 // If there are @selector references added them to its pool. This is for
6795 // implementation of -Wselector.
6796 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6797 unsigned I = 0;
6798 while (I < DataSize) {
6799 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6800 SourceLocation SelLoc
6801 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6802 Sels.push_back(std::make_pair(Sel, SelLoc));
6803 }
6804 ReferencedSelectorsData.clear();
6805}
6806
6807void ASTReader::ReadWeakUndeclaredIdentifiers(
6808 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6809 if (WeakUndeclaredIdentifiers.empty())
6810 return;
6811
6812 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6813 IdentifierInfo *WeakId
6814 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6815 IdentifierInfo *AliasId
6816 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6817 SourceLocation Loc
6818 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6819 bool Used = WeakUndeclaredIdentifiers[I++];
6820 WeakInfo WI(AliasId, Loc);
6821 WI.setUsed(Used);
6822 WeakIDs.push_back(std::make_pair(WeakId, WI));
6823 }
6824 WeakUndeclaredIdentifiers.clear();
6825}
6826
6827void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6828 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6829 ExternalVTableUse VT;
6830 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6831 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6832 VT.DefinitionRequired = VTableUses[Idx++];
6833 VTables.push_back(VT);
6834 }
6835
6836 VTableUses.clear();
6837}
6838
6839void ASTReader::ReadPendingInstantiations(
6840 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6841 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6842 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6843 SourceLocation Loc
6844 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6845
6846 Pending.push_back(std::make_pair(D, Loc));
6847 }
6848 PendingInstantiations.clear();
6849}
6850
Richard Smithe40f2ba2013-08-07 21:41:30 +00006851void ASTReader::ReadLateParsedTemplates(
6852 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6853 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6854 /* In loop */) {
6855 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6856
6857 LateParsedTemplate *LT = new LateParsedTemplate;
6858 LT->D = GetDecl(LateParsedTemplates[Idx++]);
6859
6860 ModuleFile *F = getOwningModuleFile(LT->D);
6861 assert(F && "No module");
6862
6863 unsigned TokN = LateParsedTemplates[Idx++];
6864 LT->Toks.reserve(TokN);
6865 for (unsigned T = 0; T < TokN; ++T)
6866 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6867
6868 LPTMap[FD] = LT;
6869 }
6870
6871 LateParsedTemplates.clear();
6872}
6873
Guy Benyei11169dd2012-12-18 14:30:41 +00006874void ASTReader::LoadSelector(Selector Sel) {
6875 // It would be complicated to avoid reading the methods anyway. So don't.
6876 ReadMethodPool(Sel);
6877}
6878
6879void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6880 assert(ID && "Non-zero identifier ID required");
6881 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6882 IdentifiersLoaded[ID - 1] = II;
6883 if (DeserializationListener)
6884 DeserializationListener->IdentifierRead(ID, II);
6885}
6886
6887/// \brief Set the globally-visible declarations associated with the given
6888/// identifier.
6889///
6890/// If the AST reader is currently in a state where the given declaration IDs
6891/// cannot safely be resolved, they are queued until it is safe to resolve
6892/// them.
6893///
6894/// \param II an IdentifierInfo that refers to one or more globally-visible
6895/// declarations.
6896///
6897/// \param DeclIDs the set of declaration IDs with the name @p II that are
6898/// visible at global scope.
6899///
Douglas Gregor6168bd22013-02-18 15:53:43 +00006900/// \param Decls if non-null, this vector will be populated with the set of
6901/// deserialized declarations. These declarations will not be pushed into
6902/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00006903void
6904ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6905 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00006906 SmallVectorImpl<Decl *> *Decls) {
6907 if (NumCurrentElementsDeserializing && !Decls) {
6908 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 return;
6910 }
6911
6912 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6913 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6914 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00006915 // If we're simply supposed to record the declarations, do so now.
6916 if (Decls) {
6917 Decls->push_back(D);
6918 continue;
6919 }
6920
Guy Benyei11169dd2012-12-18 14:30:41 +00006921 // Introduce this declaration into the translation-unit scope
6922 // and add it to the declaration chain for this identifier, so
6923 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006924 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 } else {
6926 // Queue this declaration so that it will be added to the
6927 // translation unit scope and identifier's declaration chain
6928 // once a Sema object is known.
6929 PreloadedDecls.push_back(D);
6930 }
6931 }
6932}
6933
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006934IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006935 if (ID == 0)
6936 return 0;
6937
6938 if (IdentifiersLoaded.empty()) {
6939 Error("no identifier table in AST file");
6940 return 0;
6941 }
6942
6943 ID -= 1;
6944 if (!IdentifiersLoaded[ID]) {
6945 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6946 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6947 ModuleFile *M = I->second;
6948 unsigned Index = ID - M->BaseIdentifierID;
6949 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6950
6951 // All of the strings in the AST file are preceded by a 16-bit length.
6952 // Extract that 16-bit length to avoid having to execute strlen().
6953 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6954 // unsigned integers. This is important to avoid integer overflow when
6955 // we cast them to 'unsigned'.
6956 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6957 unsigned StrLen = (((unsigned) StrLenPtr[0])
6958 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006959 IdentifiersLoaded[ID]
6960 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 if (DeserializationListener)
6962 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6963 }
6964
6965 return IdentifiersLoaded[ID];
6966}
6967
Douglas Gregorc8a992f2013-01-21 16:52:34 +00006968IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6969 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00006970}
6971
6972IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6973 if (LocalID < NUM_PREDEF_IDENT_IDS)
6974 return LocalID;
6975
6976 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6977 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6978 assert(I != M.IdentifierRemap.end()
6979 && "Invalid index into identifier index remap");
6980
6981 return LocalID + I->second;
6982}
6983
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006984MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 if (ID == 0)
6986 return 0;
6987
6988 if (MacrosLoaded.empty()) {
6989 Error("no macro table in AST file");
6990 return 0;
6991 }
6992
6993 ID -= NUM_PREDEF_MACRO_IDS;
6994 if (!MacrosLoaded[ID]) {
6995 GlobalMacroMapType::iterator I
6996 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6997 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6998 ModuleFile *M = I->second;
6999 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007000 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7001
7002 if (DeserializationListener)
7003 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7004 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007005 }
7006
7007 return MacrosLoaded[ID];
7008}
7009
7010MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7011 if (LocalID < NUM_PREDEF_MACRO_IDS)
7012 return LocalID;
7013
7014 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7015 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7016 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7017
7018 return LocalID + I->second;
7019}
7020
7021serialization::SubmoduleID
7022ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7023 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7024 return LocalID;
7025
7026 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7027 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7028 assert(I != M.SubmoduleRemap.end()
7029 && "Invalid index into submodule index remap");
7030
7031 return LocalID + I->second;
7032}
7033
7034Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7035 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7036 assert(GlobalID == 0 && "Unhandled global submodule ID");
7037 return 0;
7038 }
7039
7040 if (GlobalID > SubmodulesLoaded.size()) {
7041 Error("submodule ID out of range in AST file");
7042 return 0;
7043 }
7044
7045 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7046}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007047
7048Module *ASTReader::getModule(unsigned ID) {
7049 return getSubmodule(ID);
7050}
7051
Guy Benyei11169dd2012-12-18 14:30:41 +00007052Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7053 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7054}
7055
7056Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7057 if (ID == 0)
7058 return Selector();
7059
7060 if (ID > SelectorsLoaded.size()) {
7061 Error("selector ID out of range in AST file");
7062 return Selector();
7063 }
7064
7065 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7066 // Load this selector from the selector table.
7067 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7068 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7069 ModuleFile &M = *I->second;
7070 ASTSelectorLookupTrait Trait(*this, M);
7071 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7072 SelectorsLoaded[ID - 1] =
7073 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7074 if (DeserializationListener)
7075 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7076 }
7077
7078 return SelectorsLoaded[ID - 1];
7079}
7080
7081Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7082 return DecodeSelector(ID);
7083}
7084
7085uint32_t ASTReader::GetNumExternalSelectors() {
7086 // ID 0 (the null selector) is considered an external selector.
7087 return getTotalNumSelectors() + 1;
7088}
7089
7090serialization::SelectorID
7091ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7092 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7093 return LocalID;
7094
7095 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7096 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7097 assert(I != M.SelectorRemap.end()
7098 && "Invalid index into selector index remap");
7099
7100 return LocalID + I->second;
7101}
7102
7103DeclarationName
7104ASTReader::ReadDeclarationName(ModuleFile &F,
7105 const RecordData &Record, unsigned &Idx) {
7106 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7107 switch (Kind) {
7108 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007109 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007110
7111 case DeclarationName::ObjCZeroArgSelector:
7112 case DeclarationName::ObjCOneArgSelector:
7113 case DeclarationName::ObjCMultiArgSelector:
7114 return DeclarationName(ReadSelector(F, Record, Idx));
7115
7116 case DeclarationName::CXXConstructorName:
7117 return Context.DeclarationNames.getCXXConstructorName(
7118 Context.getCanonicalType(readType(F, Record, Idx)));
7119
7120 case DeclarationName::CXXDestructorName:
7121 return Context.DeclarationNames.getCXXDestructorName(
7122 Context.getCanonicalType(readType(F, Record, Idx)));
7123
7124 case DeclarationName::CXXConversionFunctionName:
7125 return Context.DeclarationNames.getCXXConversionFunctionName(
7126 Context.getCanonicalType(readType(F, Record, Idx)));
7127
7128 case DeclarationName::CXXOperatorName:
7129 return Context.DeclarationNames.getCXXOperatorName(
7130 (OverloadedOperatorKind)Record[Idx++]);
7131
7132 case DeclarationName::CXXLiteralOperatorName:
7133 return Context.DeclarationNames.getCXXLiteralOperatorName(
7134 GetIdentifierInfo(F, Record, Idx));
7135
7136 case DeclarationName::CXXUsingDirective:
7137 return DeclarationName::getUsingDirectiveName();
7138 }
7139
7140 llvm_unreachable("Invalid NameKind!");
7141}
7142
7143void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7144 DeclarationNameLoc &DNLoc,
7145 DeclarationName Name,
7146 const RecordData &Record, unsigned &Idx) {
7147 switch (Name.getNameKind()) {
7148 case DeclarationName::CXXConstructorName:
7149 case DeclarationName::CXXDestructorName:
7150 case DeclarationName::CXXConversionFunctionName:
7151 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7152 break;
7153
7154 case DeclarationName::CXXOperatorName:
7155 DNLoc.CXXOperatorName.BeginOpNameLoc
7156 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7157 DNLoc.CXXOperatorName.EndOpNameLoc
7158 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7159 break;
7160
7161 case DeclarationName::CXXLiteralOperatorName:
7162 DNLoc.CXXLiteralOperatorName.OpNameLoc
7163 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7164 break;
7165
7166 case DeclarationName::Identifier:
7167 case DeclarationName::ObjCZeroArgSelector:
7168 case DeclarationName::ObjCOneArgSelector:
7169 case DeclarationName::ObjCMultiArgSelector:
7170 case DeclarationName::CXXUsingDirective:
7171 break;
7172 }
7173}
7174
7175void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7176 DeclarationNameInfo &NameInfo,
7177 const RecordData &Record, unsigned &Idx) {
7178 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7179 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7180 DeclarationNameLoc DNLoc;
7181 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7182 NameInfo.setInfo(DNLoc);
7183}
7184
7185void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7186 const RecordData &Record, unsigned &Idx) {
7187 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7188 unsigned NumTPLists = Record[Idx++];
7189 Info.NumTemplParamLists = NumTPLists;
7190 if (NumTPLists) {
7191 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7192 for (unsigned i=0; i != NumTPLists; ++i)
7193 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7194 }
7195}
7196
7197TemplateName
7198ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7199 unsigned &Idx) {
7200 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7201 switch (Kind) {
7202 case TemplateName::Template:
7203 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7204
7205 case TemplateName::OverloadedTemplate: {
7206 unsigned size = Record[Idx++];
7207 UnresolvedSet<8> Decls;
7208 while (size--)
7209 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7210
7211 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7212 }
7213
7214 case TemplateName::QualifiedTemplate: {
7215 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7216 bool hasTemplKeyword = Record[Idx++];
7217 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7218 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7219 }
7220
7221 case TemplateName::DependentTemplate: {
7222 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7223 if (Record[Idx++]) // isIdentifier
7224 return Context.getDependentTemplateName(NNS,
7225 GetIdentifierInfo(F, Record,
7226 Idx));
7227 return Context.getDependentTemplateName(NNS,
7228 (OverloadedOperatorKind)Record[Idx++]);
7229 }
7230
7231 case TemplateName::SubstTemplateTemplateParm: {
7232 TemplateTemplateParmDecl *param
7233 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7234 if (!param) return TemplateName();
7235 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7236 return Context.getSubstTemplateTemplateParm(param, replacement);
7237 }
7238
7239 case TemplateName::SubstTemplateTemplateParmPack: {
7240 TemplateTemplateParmDecl *Param
7241 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7242 if (!Param)
7243 return TemplateName();
7244
7245 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7246 if (ArgPack.getKind() != TemplateArgument::Pack)
7247 return TemplateName();
7248
7249 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7250 }
7251 }
7252
7253 llvm_unreachable("Unhandled template name kind!");
7254}
7255
7256TemplateArgument
7257ASTReader::ReadTemplateArgument(ModuleFile &F,
7258 const RecordData &Record, unsigned &Idx) {
7259 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7260 switch (Kind) {
7261 case TemplateArgument::Null:
7262 return TemplateArgument();
7263 case TemplateArgument::Type:
7264 return TemplateArgument(readType(F, Record, Idx));
7265 case TemplateArgument::Declaration: {
7266 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7267 bool ForReferenceParam = Record[Idx++];
7268 return TemplateArgument(D, ForReferenceParam);
7269 }
7270 case TemplateArgument::NullPtr:
7271 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7272 case TemplateArgument::Integral: {
7273 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7274 QualType T = readType(F, Record, Idx);
7275 return TemplateArgument(Context, Value, T);
7276 }
7277 case TemplateArgument::Template:
7278 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7279 case TemplateArgument::TemplateExpansion: {
7280 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007281 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 if (unsigned NumExpansions = Record[Idx++])
7283 NumTemplateExpansions = NumExpansions - 1;
7284 return TemplateArgument(Name, NumTemplateExpansions);
7285 }
7286 case TemplateArgument::Expression:
7287 return TemplateArgument(ReadExpr(F));
7288 case TemplateArgument::Pack: {
7289 unsigned NumArgs = Record[Idx++];
7290 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7291 for (unsigned I = 0; I != NumArgs; ++I)
7292 Args[I] = ReadTemplateArgument(F, Record, Idx);
7293 return TemplateArgument(Args, NumArgs);
7294 }
7295 }
7296
7297 llvm_unreachable("Unhandled template argument kind!");
7298}
7299
7300TemplateParameterList *
7301ASTReader::ReadTemplateParameterList(ModuleFile &F,
7302 const RecordData &Record, unsigned &Idx) {
7303 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7304 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7305 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7306
7307 unsigned NumParams = Record[Idx++];
7308 SmallVector<NamedDecl *, 16> Params;
7309 Params.reserve(NumParams);
7310 while (NumParams--)
7311 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7312
7313 TemplateParameterList* TemplateParams =
7314 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7315 Params.data(), Params.size(), RAngleLoc);
7316 return TemplateParams;
7317}
7318
7319void
7320ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007321ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 ModuleFile &F, const RecordData &Record,
7323 unsigned &Idx) {
7324 unsigned NumTemplateArgs = Record[Idx++];
7325 TemplArgs.reserve(NumTemplateArgs);
7326 while (NumTemplateArgs--)
7327 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7328}
7329
7330/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007331void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 const RecordData &Record, unsigned &Idx) {
7333 unsigned NumDecls = Record[Idx++];
7334 Set.reserve(Context, NumDecls);
7335 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007336 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007337 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007338 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007339 }
7340}
7341
7342CXXBaseSpecifier
7343ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7344 const RecordData &Record, unsigned &Idx) {
7345 bool isVirtual = static_cast<bool>(Record[Idx++]);
7346 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7347 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7348 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7349 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7350 SourceRange Range = ReadSourceRange(F, Record, Idx);
7351 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7352 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7353 EllipsisLoc);
7354 Result.setInheritConstructors(inheritConstructors);
7355 return Result;
7356}
7357
7358std::pair<CXXCtorInitializer **, unsigned>
7359ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7360 unsigned &Idx) {
7361 CXXCtorInitializer **CtorInitializers = 0;
7362 unsigned NumInitializers = Record[Idx++];
7363 if (NumInitializers) {
7364 CtorInitializers
7365 = new (Context) CXXCtorInitializer*[NumInitializers];
7366 for (unsigned i=0; i != NumInitializers; ++i) {
7367 TypeSourceInfo *TInfo = 0;
7368 bool IsBaseVirtual = false;
7369 FieldDecl *Member = 0;
7370 IndirectFieldDecl *IndirectMember = 0;
7371
7372 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7373 switch (Type) {
7374 case CTOR_INITIALIZER_BASE:
7375 TInfo = GetTypeSourceInfo(F, Record, Idx);
7376 IsBaseVirtual = Record[Idx++];
7377 break;
7378
7379 case CTOR_INITIALIZER_DELEGATING:
7380 TInfo = GetTypeSourceInfo(F, Record, Idx);
7381 break;
7382
7383 case CTOR_INITIALIZER_MEMBER:
7384 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7385 break;
7386
7387 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7388 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7389 break;
7390 }
7391
7392 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7393 Expr *Init = ReadExpr(F);
7394 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7395 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7396 bool IsWritten = Record[Idx++];
7397 unsigned SourceOrderOrNumArrayIndices;
7398 SmallVector<VarDecl *, 8> Indices;
7399 if (IsWritten) {
7400 SourceOrderOrNumArrayIndices = Record[Idx++];
7401 } else {
7402 SourceOrderOrNumArrayIndices = Record[Idx++];
7403 Indices.reserve(SourceOrderOrNumArrayIndices);
7404 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7405 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7406 }
7407
7408 CXXCtorInitializer *BOMInit;
7409 if (Type == CTOR_INITIALIZER_BASE) {
7410 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7411 LParenLoc, Init, RParenLoc,
7412 MemberOrEllipsisLoc);
7413 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7414 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7415 Init, RParenLoc);
7416 } else if (IsWritten) {
7417 if (Member)
7418 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7419 LParenLoc, Init, RParenLoc);
7420 else
7421 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7422 MemberOrEllipsisLoc, LParenLoc,
7423 Init, RParenLoc);
7424 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007425 if (IndirectMember) {
7426 assert(Indices.empty() && "Indirect field improperly initialized");
7427 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7428 MemberOrEllipsisLoc, LParenLoc,
7429 Init, RParenLoc);
7430 } else {
7431 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7432 LParenLoc, Init, RParenLoc,
7433 Indices.data(), Indices.size());
7434 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007435 }
7436
7437 if (IsWritten)
7438 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7439 CtorInitializers[i] = BOMInit;
7440 }
7441 }
7442
7443 return std::make_pair(CtorInitializers, NumInitializers);
7444}
7445
7446NestedNameSpecifier *
7447ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7448 const RecordData &Record, unsigned &Idx) {
7449 unsigned N = Record[Idx++];
7450 NestedNameSpecifier *NNS = 0, *Prev = 0;
7451 for (unsigned I = 0; I != N; ++I) {
7452 NestedNameSpecifier::SpecifierKind Kind
7453 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7454 switch (Kind) {
7455 case NestedNameSpecifier::Identifier: {
7456 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7457 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7458 break;
7459 }
7460
7461 case NestedNameSpecifier::Namespace: {
7462 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7463 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7464 break;
7465 }
7466
7467 case NestedNameSpecifier::NamespaceAlias: {
7468 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7469 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7470 break;
7471 }
7472
7473 case NestedNameSpecifier::TypeSpec:
7474 case NestedNameSpecifier::TypeSpecWithTemplate: {
7475 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7476 if (!T)
7477 return 0;
7478
7479 bool Template = Record[Idx++];
7480 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7481 break;
7482 }
7483
7484 case NestedNameSpecifier::Global: {
7485 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7486 // No associated value, and there can't be a prefix.
7487 break;
7488 }
7489 }
7490 Prev = NNS;
7491 }
7492 return NNS;
7493}
7494
7495NestedNameSpecifierLoc
7496ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7497 unsigned &Idx) {
7498 unsigned N = Record[Idx++];
7499 NestedNameSpecifierLocBuilder Builder;
7500 for (unsigned I = 0; I != N; ++I) {
7501 NestedNameSpecifier::SpecifierKind Kind
7502 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7503 switch (Kind) {
7504 case NestedNameSpecifier::Identifier: {
7505 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7506 SourceRange Range = ReadSourceRange(F, Record, Idx);
7507 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7508 break;
7509 }
7510
7511 case NestedNameSpecifier::Namespace: {
7512 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7513 SourceRange Range = ReadSourceRange(F, Record, Idx);
7514 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7515 break;
7516 }
7517
7518 case NestedNameSpecifier::NamespaceAlias: {
7519 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7520 SourceRange Range = ReadSourceRange(F, Record, Idx);
7521 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7522 break;
7523 }
7524
7525 case NestedNameSpecifier::TypeSpec:
7526 case NestedNameSpecifier::TypeSpecWithTemplate: {
7527 bool Template = Record[Idx++];
7528 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7529 if (!T)
7530 return NestedNameSpecifierLoc();
7531 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7532
7533 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7534 Builder.Extend(Context,
7535 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7536 T->getTypeLoc(), ColonColonLoc);
7537 break;
7538 }
7539
7540 case NestedNameSpecifier::Global: {
7541 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7542 Builder.MakeGlobal(Context, ColonColonLoc);
7543 break;
7544 }
7545 }
7546 }
7547
7548 return Builder.getWithLocInContext(Context);
7549}
7550
7551SourceRange
7552ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7553 unsigned &Idx) {
7554 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7555 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7556 return SourceRange(beg, end);
7557}
7558
7559/// \brief Read an integral value
7560llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7561 unsigned BitWidth = Record[Idx++];
7562 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7563 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7564 Idx += NumWords;
7565 return Result;
7566}
7567
7568/// \brief Read a signed integral value
7569llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7570 bool isUnsigned = Record[Idx++];
7571 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7572}
7573
7574/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007575llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7576 const llvm::fltSemantics &Sem,
7577 unsigned &Idx) {
7578 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007579}
7580
7581// \brief Read a string
7582std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7583 unsigned Len = Record[Idx++];
7584 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7585 Idx += Len;
7586 return Result;
7587}
7588
7589VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7590 unsigned &Idx) {
7591 unsigned Major = Record[Idx++];
7592 unsigned Minor = Record[Idx++];
7593 unsigned Subminor = Record[Idx++];
7594 if (Minor == 0)
7595 return VersionTuple(Major);
7596 if (Subminor == 0)
7597 return VersionTuple(Major, Minor - 1);
7598 return VersionTuple(Major, Minor - 1, Subminor - 1);
7599}
7600
7601CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7602 const RecordData &Record,
7603 unsigned &Idx) {
7604 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7605 return CXXTemporary::Create(Context, Decl);
7606}
7607
7608DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007609 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007610}
7611
7612DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7613 return Diags.Report(Loc, DiagID);
7614}
7615
7616/// \brief Retrieve the identifier table associated with the
7617/// preprocessor.
7618IdentifierTable &ASTReader::getIdentifierTable() {
7619 return PP.getIdentifierTable();
7620}
7621
7622/// \brief Record that the given ID maps to the given switch-case
7623/// statement.
7624void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7625 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7626 "Already have a SwitchCase with this ID");
7627 (*CurrSwitchCaseStmts)[ID] = SC;
7628}
7629
7630/// \brief Retrieve the switch-case statement with the given ID.
7631SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7632 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7633 return (*CurrSwitchCaseStmts)[ID];
7634}
7635
7636void ASTReader::ClearSwitchCaseIDs() {
7637 CurrSwitchCaseStmts->clear();
7638}
7639
7640void ASTReader::ReadComments() {
7641 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007642 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 serialization::ModuleFile *> >::iterator
7644 I = CommentsCursors.begin(),
7645 E = CommentsCursors.end();
7646 I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007647 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 serialization::ModuleFile &F = *I->second;
7649 SavedStreamPosition SavedPosition(Cursor);
7650
7651 RecordData Record;
7652 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007653 llvm::BitstreamEntry Entry =
7654 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7655
7656 switch (Entry.Kind) {
7657 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7658 case llvm::BitstreamEntry::Error:
7659 Error("malformed block record in AST file");
7660 return;
7661 case llvm::BitstreamEntry::EndBlock:
7662 goto NextCursor;
7663 case llvm::BitstreamEntry::Record:
7664 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007665 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 }
7667
7668 // Read a record.
7669 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007670 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 case COMMENTS_RAW_COMMENT: {
7672 unsigned Idx = 0;
7673 SourceRange SR = ReadSourceRange(F, Record, Idx);
7674 RawComment::CommentKind Kind =
7675 (RawComment::CommentKind) Record[Idx++];
7676 bool IsTrailingComment = Record[Idx++];
7677 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007678 Comments.push_back(new (Context) RawComment(
7679 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7680 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007681 break;
7682 }
7683 }
7684 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007685 NextCursor:;
Guy Benyei11169dd2012-12-18 14:30:41 +00007686 }
7687 Context.Comments.addCommentsToFront(Comments);
7688}
7689
7690void ASTReader::finishPendingActions() {
7691 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007692 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7693 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 // If any identifiers with corresponding top-level declarations have
7695 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007696 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7697 TopLevelDeclsMap;
7698 TopLevelDeclsMap TopLevelDecls;
7699
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007701 // FIXME: std::move
7702 IdentifierInfo *II = PendingIdentifierInfos.back().first;
7703 SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
Douglas Gregorcb15f082013-02-19 18:26:28 +00007704 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007705
7706 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 }
7708
7709 // Load pending declaration chains.
7710 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7711 loadPendingDeclChain(PendingDeclChains[I]);
7712 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7713 }
7714 PendingDeclChains.clear();
7715
Douglas Gregor6168bd22013-02-18 15:53:43 +00007716 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00007717 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7718 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007719 IdentifierInfo *II = TLD->first;
7720 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007721 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00007722 }
7723 }
7724
Guy Benyei11169dd2012-12-18 14:30:41 +00007725 // Load any pending macro definitions.
7726 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007727 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7728 SmallVector<PendingMacroInfo, 2> GlobalIDs;
7729 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7730 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007731 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00007732 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007733 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7734 if (Info.M->Kind != MK_Module)
7735 resolvePendingMacro(II, Info);
7736 }
7737 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00007738 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007739 ++IDIdx) {
7740 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7741 if (Info.M->Kind == MK_Module)
7742 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00007743 }
7744 }
7745 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00007746
7747 // Wire up the DeclContexts for Decls that we delayed setting until
7748 // recursive loading is completed.
7749 while (!PendingDeclContextInfos.empty()) {
7750 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7751 PendingDeclContextInfos.pop_front();
7752 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7753 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7754 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7755 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00007756
7757 // For each declaration from a merged context, check that the canonical
7758 // definition of that context also contains a declaration of the same
7759 // entity.
7760 while (!PendingOdrMergeChecks.empty()) {
7761 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7762
7763 // FIXME: Skip over implicit declarations for now. This matters for things
7764 // like implicitly-declared special member functions. This isn't entirely
7765 // correct; we can end up with multiple unmerged declarations of the same
7766 // implicit entity.
7767 if (D->isImplicit())
7768 continue;
7769
7770 DeclContext *CanonDef = D->getDeclContext();
7771 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7772
7773 bool Found = false;
7774 const Decl *DCanon = D->getCanonicalDecl();
7775
7776 llvm::SmallVector<const NamedDecl*, 4> Candidates;
7777 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7778 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00007779 for (auto RI : (*I)->redecls()) {
7780 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00007781 // This declaration is present in the canonical definition. If it's
7782 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00007783 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00007784 Found = true;
7785 else
Aaron Ballman86c93902014-03-06 23:45:36 +00007786 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00007787 break;
7788 }
7789 }
7790 }
7791
7792 if (!Found) {
7793 D->setInvalidDecl();
7794
7795 Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7796 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7797 << D << D->getOwningModule()->getFullModuleName()
7798 << CanonDef << !CanonDefModule
7799 << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7800
7801 if (Candidates.empty())
7802 Diag(cast<Decl>(CanonDef)->getLocation(),
7803 diag::note_module_odr_violation_no_possible_decls) << D;
7804 else {
7805 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7806 Diag(Candidates[I]->getLocation(),
7807 diag::note_module_odr_violation_possible_decl)
7808 << Candidates[I];
7809 }
7810 }
7811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007812 }
7813
7814 // If we deserialized any C++ or Objective-C class definitions, any
7815 // Objective-C protocol definitions, or any redeclarable templates, make sure
7816 // that all redeclarations point to the definitions. Note that this can only
7817 // happen now, after the redeclaration chains have been fully wired.
7818 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7819 DEnd = PendingDefinitions.end();
7820 D != DEnd; ++D) {
7821 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7822 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7823 // Make sure that the TagType points at the definition.
7824 const_cast<TagType*>(TagT)->decl = TD;
7825 }
7826
Aaron Ballman86c93902014-03-06 23:45:36 +00007827 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7828 for (auto R : RD->redecls())
7829 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00007830
7831 }
7832
7833 continue;
7834 }
7835
Aaron Ballman86c93902014-03-06 23:45:36 +00007836 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 // Make sure that the ObjCInterfaceType points at the definition.
7838 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7839 ->Decl = ID;
7840
Aaron Ballman86c93902014-03-06 23:45:36 +00007841 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007842 R->Data = ID->Data;
7843
7844 continue;
7845 }
7846
Aaron Ballman86c93902014-03-06 23:45:36 +00007847 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7848 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007849 R->Data = PD->Data;
7850
7851 continue;
7852 }
7853
Aaron Ballman86c93902014-03-06 23:45:36 +00007854 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7855 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 R->Common = RTD->Common;
7857 }
7858 PendingDefinitions.clear();
7859
7860 // Load the bodies of any functions or methods we've encountered. We do
7861 // this now (delayed) so that we can be sure that the declaration chains
7862 // have been fully wired up.
7863 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7864 PBEnd = PendingBodies.end();
7865 PB != PBEnd; ++PB) {
7866 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7867 // FIXME: Check for =delete/=default?
7868 // FIXME: Complain about ODR violations here?
7869 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7870 FD->setLazyBody(PB->second);
7871 continue;
7872 }
7873
7874 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7875 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7876 MD->setLazyBody(PB->second);
7877 }
7878 PendingBodies.clear();
7879}
7880
7881void ASTReader::FinishedDeserializing() {
7882 assert(NumCurrentElementsDeserializing &&
7883 "FinishedDeserializing not paired with StartedDeserializing");
7884 if (NumCurrentElementsDeserializing == 1) {
7885 // We decrease NumCurrentElementsDeserializing only after pending actions
7886 // are finished, to avoid recursively re-calling finishPendingActions().
7887 finishPendingActions();
7888 }
7889 --NumCurrentElementsDeserializing;
7890
7891 if (NumCurrentElementsDeserializing == 0 &&
7892 Consumer && !PassingDeclsToConsumer) {
7893 // Guard variable to avoid recursively redoing the process of passing
7894 // decls to consumer.
7895 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7896 true);
7897
7898 while (!InterestingDecls.empty()) {
7899 // We are not in recursive loading, so it's safe to pass the "interesting"
7900 // decls to the consumer.
7901 Decl *D = InterestingDecls.front();
7902 InterestingDecls.pop_front();
7903 PassInterestingDeclToConsumer(D);
7904 }
7905 }
7906}
7907
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007908void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00007909 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007910
7911 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7912 SemaObj->TUScope->AddDecl(D);
7913 } else if (SemaObj->TUScope) {
7914 // Adding the decl to IdResolver may have failed because it was already in
7915 // (even though it was not added in scope). If it is already in, make sure
7916 // it gets in the scope as well.
7917 if (std::find(SemaObj->IdResolver.begin(Name),
7918 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7919 SemaObj->TUScope->AddDecl(D);
7920 }
7921}
7922
Guy Benyei11169dd2012-12-18 14:30:41 +00007923ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7924 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007925 bool AllowASTWithCompilerErrors,
7926 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007927 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007928 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7930 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7931 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7932 Consumer(0), ModuleMgr(PP.getFileManager()),
7933 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007934 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00007935 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00007936 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00007937 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7939 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00007940 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7941 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7942 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007943 NumMethodPoolLookups(0), NumMethodPoolHits(0),
7944 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7945 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7947 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7948 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7949 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00007950 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00007951{
7952 SourceMgr.setExternalSLocEntrySource(this);
7953}
7954
7955ASTReader::~ASTReader() {
7956 for (DeclContextVisibleUpdatesPending::iterator
7957 I = PendingVisibleUpdates.begin(),
7958 E = PendingVisibleUpdates.end();
7959 I != E; ++I) {
7960 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7961 F = I->second.end();
7962 J != F; ++J)
7963 delete J->first;
7964 }
7965}