blob: b6b0913811661ee8dacaada25395ca36da826fa7 [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"
Ben Langmuirb92de022014-04-29 16:25:26 +000032#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/HeaderSearchOptions.h"
35#include "clang/Lex/MacroInfo.h"
36#include "clang/Lex/PreprocessingRecord.h"
37#include "clang/Lex/Preprocessor.h"
38#include "clang/Lex/PreprocessorOptions.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/Sema.h"
41#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000042#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000043#include "clang/Serialization/ModuleManager.h"
44#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000045#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000046#include "llvm/ADT/StringExtras.h"
47#include "llvm/Bitcode/BitstreamReader.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000053#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000054#include "llvm/Support/system_error.h"
55#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
58
59using namespace clang;
60using namespace clang::serialization;
61using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000062using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000063
Ben Langmuircb69b572014-03-07 06:40:32 +000064
65//===----------------------------------------------------------------------===//
66// ChainedASTReaderListener implementation
67//===----------------------------------------------------------------------===//
68
69bool
70ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
71 return First->ReadFullVersionInformation(FullVersion) ||
72 Second->ReadFullVersionInformation(FullVersion);
73}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000074void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
75 First->ReadModuleName(ModuleName);
76 Second->ReadModuleName(ModuleName);
77}
78void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
79 First->ReadModuleMapFile(ModuleMapPath);
80 Second->ReadModuleMapFile(ModuleMapPath);
81}
Ben Langmuircb69b572014-03-07 06:40:32 +000082bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
83 bool Complain) {
84 return First->ReadLanguageOptions(LangOpts, Complain) ||
85 Second->ReadLanguageOptions(LangOpts, Complain);
86}
87bool
88ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
89 bool Complain) {
90 return First->ReadTargetOptions(TargetOpts, Complain) ||
91 Second->ReadTargetOptions(TargetOpts, Complain);
92}
93bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000094 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000095 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
96 Second->ReadDiagnosticOptions(DiagOpts, Complain);
97}
98bool
99ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
100 bool Complain) {
101 return First->ReadFileSystemOptions(FSOpts, Complain) ||
102 Second->ReadFileSystemOptions(FSOpts, Complain);
103}
104
105bool ChainedASTReaderListener::ReadHeaderSearchOptions(
106 const HeaderSearchOptions &HSOpts, bool Complain) {
107 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
108 Second->ReadHeaderSearchOptions(HSOpts, Complain);
109}
110bool ChainedASTReaderListener::ReadPreprocessorOptions(
111 const PreprocessorOptions &PPOpts, bool Complain,
112 std::string &SuggestedPredefines) {
113 return First->ReadPreprocessorOptions(PPOpts, Complain,
114 SuggestedPredefines) ||
115 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
116}
117void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
118 unsigned Value) {
119 First->ReadCounter(M, Value);
120 Second->ReadCounter(M, Value);
121}
122bool ChainedASTReaderListener::needsInputFileVisitation() {
123 return First->needsInputFileVisitation() ||
124 Second->needsInputFileVisitation();
125}
126bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
127 return First->needsSystemInputFileVisitation() ||
128 Second->needsSystemInputFileVisitation();
129}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000130void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
131 First->visitModuleFile(Filename);
132 Second->visitModuleFile(Filename);
133}
Ben Langmuircb69b572014-03-07 06:40:32 +0000134bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000135 bool isSystem,
136 bool isOverridden) {
137 return First->visitInputFile(Filename, isSystem, isOverridden) ||
138 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000139}
140
Guy Benyei11169dd2012-12-18 14:30:41 +0000141//===----------------------------------------------------------------------===//
142// PCH validator implementation
143//===----------------------------------------------------------------------===//
144
145ASTReaderListener::~ASTReaderListener() {}
146
147/// \brief Compare the given set of language options against an existing set of
148/// language options.
149///
150/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
151///
152/// \returns true if the languagae options mis-match, false otherwise.
153static bool checkLanguageOptions(const LangOptions &LangOpts,
154 const LangOptions &ExistingLangOpts,
155 DiagnosticsEngine *Diags) {
156#define LANGOPT(Name, Bits, Default, Description) \
157 if (ExistingLangOpts.Name != LangOpts.Name) { \
158 if (Diags) \
159 Diags->Report(diag::err_pch_langopt_mismatch) \
160 << Description << LangOpts.Name << ExistingLangOpts.Name; \
161 return true; \
162 }
163
164#define VALUE_LANGOPT(Name, Bits, Default, Description) \
165 if (ExistingLangOpts.Name != LangOpts.Name) { \
166 if (Diags) \
167 Diags->Report(diag::err_pch_langopt_value_mismatch) \
168 << Description; \
169 return true; \
170 }
171
172#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
173 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
174 if (Diags) \
175 Diags->Report(diag::err_pch_langopt_value_mismatch) \
176 << Description; \
177 return true; \
178 }
179
180#define BENIGN_LANGOPT(Name, Bits, Default, Description)
181#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
182#include "clang/Basic/LangOptions.def"
183
184 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
185 if (Diags)
186 Diags->Report(diag::err_pch_langopt_value_mismatch)
187 << "target Objective-C runtime";
188 return true;
189 }
190
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000191 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
192 LangOpts.CommentOpts.BlockCommandNames) {
193 if (Diags)
194 Diags->Report(diag::err_pch_langopt_value_mismatch)
195 << "block command names";
196 return true;
197 }
198
Guy Benyei11169dd2012-12-18 14:30:41 +0000199 return false;
200}
201
202/// \brief Compare the given set of target options against an existing set of
203/// target options.
204///
205/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
206///
207/// \returns true if the target options mis-match, false otherwise.
208static bool checkTargetOptions(const TargetOptions &TargetOpts,
209 const TargetOptions &ExistingTargetOpts,
210 DiagnosticsEngine *Diags) {
211#define CHECK_TARGET_OPT(Field, Name) \
212 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
213 if (Diags) \
214 Diags->Report(diag::err_pch_targetopt_mismatch) \
215 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
216 return true; \
217 }
218
219 CHECK_TARGET_OPT(Triple, "target");
220 CHECK_TARGET_OPT(CPU, "target CPU");
221 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000222#undef CHECK_TARGET_OPT
223
224 // Compare feature sets.
225 SmallVector<StringRef, 4> ExistingFeatures(
226 ExistingTargetOpts.FeaturesAsWritten.begin(),
227 ExistingTargetOpts.FeaturesAsWritten.end());
228 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
229 TargetOpts.FeaturesAsWritten.end());
230 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
231 std::sort(ReadFeatures.begin(), ReadFeatures.end());
232
233 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
234 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
235 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
236 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
237 ++ExistingIdx;
238 ++ReadIdx;
239 continue;
240 }
241
242 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
243 if (Diags)
244 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
245 << false << ReadFeatures[ReadIdx];
246 return true;
247 }
248
249 if (Diags)
250 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
251 << true << ExistingFeatures[ExistingIdx];
252 return true;
253 }
254
255 if (ExistingIdx < ExistingN) {
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ReadIdx < ReadN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << false << ReadFeatures[ReadIdx];
266 return true;
267 }
268
269 return false;
270}
271
272bool
273PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
274 bool Complain) {
275 const LangOptions &ExistingLangOpts = PP.getLangOpts();
276 return checkLanguageOptions(LangOpts, ExistingLangOpts,
277 Complain? &Reader.Diags : 0);
278}
279
280bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
281 bool Complain) {
282 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
283 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
284 Complain? &Reader.Diags : 0);
285}
286
287namespace {
288 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
289 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000290 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
291 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
Ben Langmuirb92de022014-04-29 16:25:26 +0000294static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
295 DiagnosticsEngine &Diags,
296 bool Complain) {
297 typedef DiagnosticsEngine::Level Level;
298
299 // Check current mappings for new -Werror mappings, and the stored mappings
300 // for cases that were explicitly mapped to *not* be errors that are now
301 // errors because of options like -Werror.
302 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
303
304 for (DiagnosticsEngine *MappingSource : MappingSources) {
305 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
306 diag::kind DiagID = DiagIDMappingPair.first;
307 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
308 if (CurLevel < DiagnosticsEngine::Error)
309 continue; // not significant
310 Level StoredLevel =
311 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
312 if (StoredLevel < DiagnosticsEngine::Error) {
313 if (Complain)
314 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
315 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
316 return true;
317 }
318 }
319 }
320
321 return false;
322}
323
324static DiagnosticsEngine::ExtensionHandling
325isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
326 DiagnosticsEngine::ExtensionHandling Ext =
327 Diags.getExtensionHandlingBehavior();
328 if (Ext == DiagnosticsEngine::Ext_Warn && Diags.getWarningsAsErrors())
329 Ext = DiagnosticsEngine::Ext_Error;
330 return Ext;
331}
332
333static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
334 DiagnosticsEngine &Diags,
335 bool IsSystem, bool Complain) {
336 // Top-level options
337 if (IsSystem) {
338 if (Diags.getSuppressSystemWarnings())
339 return false;
340 // If -Wsystem-headers was not enabled before, be conservative
341 if (StoredDiags.getSuppressSystemWarnings()) {
342 if (Complain)
343 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
344 return true;
345 }
346 }
347
348 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
349 if (Complain)
350 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
351 return true;
352 }
353
354 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
355 !StoredDiags.getEnableAllWarnings()) {
356 if (Complain)
357 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
358 return true;
359 }
360
361 if (isExtHandlingFromDiagsError(Diags) &&
362 !isExtHandlingFromDiagsError(StoredDiags)) {
363 if (Complain)
364 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
365 return true;
366 }
367
368 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
369}
370
371bool PCHValidator::ReadDiagnosticOptions(
372 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
373 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
374 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
375 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
376 new DiagnosticsEngine(DiagIDs, DiagOpts.getPtr()));
377 // This should never fail, because we would have processed these options
378 // before writing them to an ASTFile.
379 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
380
381 ModuleManager &ModuleMgr = Reader.getModuleManager();
382 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
383
384 // If the original import came from a file explicitly generated by the user,
385 // don't check the diagnostic mappings.
386 // FIXME: currently this is approximated by checking whether this is not a
387 // module import.
388 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
389 // the transitive closure of its imports, since unrelated modules cannot be
390 // imported until after this module finishes validation.
391 ModuleFile *TopImport = *ModuleMgr.rbegin();
392 while (!TopImport->ImportedBy.empty())
393 TopImport = TopImport->ImportedBy[0];
394 if (TopImport->Kind != MK_Module)
395 return false;
396
397 StringRef ModuleName = TopImport->ModuleName;
398 assert(!ModuleName.empty() && "diagnostic options read before module name");
399
400 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
401 assert(M && "missing module");
402
403 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
404 // contains the union of their flags.
405 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
406}
407
Guy Benyei11169dd2012-12-18 14:30:41 +0000408/// \brief Collect the macro definitions provided by the given preprocessor
409/// options.
410static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
411 MacroDefinitionsMap &Macros,
412 SmallVectorImpl<StringRef> *MacroNames = 0){
413 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
414 StringRef Macro = PPOpts.Macros[I].first;
415 bool IsUndef = PPOpts.Macros[I].second;
416
417 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
418 StringRef MacroName = MacroPair.first;
419 StringRef MacroBody = MacroPair.second;
420
421 // For an #undef'd macro, we only care about the name.
422 if (IsUndef) {
423 if (MacroNames && !Macros.count(MacroName))
424 MacroNames->push_back(MacroName);
425
426 Macros[MacroName] = std::make_pair("", true);
427 continue;
428 }
429
430 // For a #define'd macro, figure out the actual definition.
431 if (MacroName.size() == Macro.size())
432 MacroBody = "1";
433 else {
434 // Note: GCC drops anything following an end-of-line character.
435 StringRef::size_type End = MacroBody.find_first_of("\n\r");
436 MacroBody = MacroBody.substr(0, End);
437 }
438
439 if (MacroNames && !Macros.count(MacroName))
440 MacroNames->push_back(MacroName);
441 Macros[MacroName] = std::make_pair(MacroBody, false);
442 }
443}
444
445/// \brief Check the preprocessor options deserialized from the control block
446/// against the preprocessor options in an existing preprocessor.
447///
448/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
449static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
450 const PreprocessorOptions &ExistingPPOpts,
451 DiagnosticsEngine *Diags,
452 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000453 std::string &SuggestedPredefines,
454 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000455 // Check macro definitions.
456 MacroDefinitionsMap ASTFileMacros;
457 collectMacroDefinitions(PPOpts, ASTFileMacros);
458 MacroDefinitionsMap ExistingMacros;
459 SmallVector<StringRef, 4> ExistingMacroNames;
460 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
461
462 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
463 // Dig out the macro definition in the existing preprocessor options.
464 StringRef MacroName = ExistingMacroNames[I];
465 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
466
467 // Check whether we know anything about this macro name or not.
468 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
469 = ASTFileMacros.find(MacroName);
470 if (Known == ASTFileMacros.end()) {
471 // FIXME: Check whether this identifier was referenced anywhere in the
472 // AST file. If so, we should reject the AST file. Unfortunately, this
473 // information isn't in the control block. What shall we do about it?
474
475 if (Existing.second) {
476 SuggestedPredefines += "#undef ";
477 SuggestedPredefines += MacroName.str();
478 SuggestedPredefines += '\n';
479 } else {
480 SuggestedPredefines += "#define ";
481 SuggestedPredefines += MacroName.str();
482 SuggestedPredefines += ' ';
483 SuggestedPredefines += Existing.first.str();
484 SuggestedPredefines += '\n';
485 }
486 continue;
487 }
488
489 // If the macro was defined in one but undef'd in the other, we have a
490 // conflict.
491 if (Existing.second != Known->second.second) {
492 if (Diags) {
493 Diags->Report(diag::err_pch_macro_def_undef)
494 << MacroName << Known->second.second;
495 }
496 return true;
497 }
498
499 // If the macro was #undef'd in both, or if the macro bodies are identical,
500 // it's fine.
501 if (Existing.second || Existing.first == Known->second.first)
502 continue;
503
504 // The macro bodies differ; complain.
505 if (Diags) {
506 Diags->Report(diag::err_pch_macro_def_conflict)
507 << MacroName << Known->second.first << Existing.first;
508 }
509 return true;
510 }
511
512 // Check whether we're using predefines.
513 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
514 if (Diags) {
515 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
516 }
517 return true;
518 }
519
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000520 // Detailed record is important since it is used for the module cache hash.
521 if (LangOpts.Modules &&
522 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
523 if (Diags) {
524 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
525 }
526 return true;
527 }
528
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 // Compute the #include and #include_macros lines we need.
530 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
531 StringRef File = ExistingPPOpts.Includes[I];
532 if (File == ExistingPPOpts.ImplicitPCHInclude)
533 continue;
534
535 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
536 != PPOpts.Includes.end())
537 continue;
538
539 SuggestedPredefines += "#include \"";
540 SuggestedPredefines +=
541 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
542 SuggestedPredefines += "\"\n";
543 }
544
545 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
546 StringRef File = ExistingPPOpts.MacroIncludes[I];
547 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
548 File)
549 != PPOpts.MacroIncludes.end())
550 continue;
551
552 SuggestedPredefines += "#__include_macros \"";
553 SuggestedPredefines +=
554 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
555 SuggestedPredefines += "\"\n##\n";
556 }
557
558 return false;
559}
560
561bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
562 bool Complain,
563 std::string &SuggestedPredefines) {
564 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
565
566 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
567 Complain? &Reader.Diags : 0,
568 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000569 SuggestedPredefines,
570 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000571}
572
Guy Benyei11169dd2012-12-18 14:30:41 +0000573void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
574 PP.setCounterValue(Value);
575}
576
577//===----------------------------------------------------------------------===//
578// AST reader implementation
579//===----------------------------------------------------------------------===//
580
581void
582ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
583 DeserializationListener = Listener;
584}
585
586
587
588unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
589 return serialization::ComputeHash(Sel);
590}
591
592
593std::pair<unsigned, unsigned>
594ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000595 using namespace llvm::support;
596 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
597 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 return std::make_pair(KeyLen, DataLen);
599}
600
601ASTSelectorLookupTrait::internal_key_type
602ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000603 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000605 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
606 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
607 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 if (N == 0)
609 return SelTable.getNullarySelector(FirstII);
610 else if (N == 1)
611 return SelTable.getUnarySelector(FirstII);
612
613 SmallVector<IdentifierInfo *, 16> Args;
614 Args.push_back(FirstII);
615 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000616 Args.push_back(Reader.getLocalIdentifier(
617 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000618
619 return SelTable.getSelector(N, Args.data());
620}
621
622ASTSelectorLookupTrait::data_type
623ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
624 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000625 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000626
627 data_type Result;
628
Justin Bogner57ba0b22014-03-28 22:03:24 +0000629 Result.ID = Reader.getGlobalSelectorID(
630 F, endian::readNext<uint32_t, little, unaligned>(d));
631 unsigned NumInstanceMethodsAndBits =
632 endian::readNext<uint16_t, little, unaligned>(d);
633 unsigned NumFactoryMethodsAndBits =
634 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000635 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
636 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
637 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
638 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639
640 // Load instance methods
641 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000642 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
643 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 Result.Instance.push_back(Method);
645 }
646
647 // Load factory methods
648 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000649 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
650 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 Result.Factory.push_back(Method);
652 }
653
654 return Result;
655}
656
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000657unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
658 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000659}
660
661std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000662ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000663 using namespace llvm::support;
664 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
665 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 return std::make_pair(KeyLen, DataLen);
667}
668
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000669ASTIdentifierLookupTraitBase::internal_key_type
670ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000672 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000673}
674
Douglas Gregordcf25082013-02-11 18:16:18 +0000675/// \brief Whether the given identifier is "interesting".
676static bool isInterestingIdentifier(IdentifierInfo &II) {
677 return II.isPoisoned() ||
678 II.isExtensionToken() ||
679 II.getObjCOrBuiltinID() ||
680 II.hasRevertedTokenIDToIdentifier() ||
681 II.hadMacroDefinition() ||
682 II.getFETokenInfo<void>();
683}
684
Guy Benyei11169dd2012-12-18 14:30:41 +0000685IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
686 const unsigned char* d,
687 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000688 using namespace llvm::support;
689 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000690 bool IsInteresting = RawID & 0x01;
691
692 // Wipe out the "is interesting" bit.
693 RawID = RawID >> 1;
694
695 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
696 if (!IsInteresting) {
697 // For uninteresting identifiers, just build the IdentifierInfo
698 // and associate it with the persistent ID.
699 IdentifierInfo *II = KnownII;
700 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000701 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000702 KnownII = II;
703 }
704 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000705 if (!II->isFromAST()) {
706 bool WasInteresting = isInterestingIdentifier(*II);
707 II->setIsFromAST();
708 if (WasInteresting)
709 II->setChangedSinceDeserialization();
710 }
711 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000712 return II;
713 }
714
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
716 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 bool CPlusPlusOperatorKeyword = Bits & 0x01;
718 Bits >>= 1;
719 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
720 Bits >>= 1;
721 bool Poisoned = Bits & 0x01;
722 Bits >>= 1;
723 bool ExtensionToken = Bits & 0x01;
724 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000725 bool hasSubmoduleMacros = Bits & 0x01;
726 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 bool hadMacroDefinition = Bits & 0x01;
728 Bits >>= 1;
729
730 assert(Bits == 0 && "Extra bits in the identifier?");
731 DataLen -= 8;
732
733 // Build the IdentifierInfo itself and link the identifier ID with
734 // the new IdentifierInfo.
735 IdentifierInfo *II = KnownII;
736 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000737 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000738 KnownII = II;
739 }
740 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000741 if (!II->isFromAST()) {
742 bool WasInteresting = isInterestingIdentifier(*II);
743 II->setIsFromAST();
744 if (WasInteresting)
745 II->setChangedSinceDeserialization();
746 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000747
748 // Set or check the various bits in the IdentifierInfo structure.
749 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000750 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 II->RevertTokenIDToIdentifier();
752 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
753 assert(II->isExtensionToken() == ExtensionToken &&
754 "Incorrect extension token flag");
755 (void)ExtensionToken;
756 if (Poisoned)
757 II->setIsPoisoned(true);
758 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
759 "Incorrect C++ operator keyword flag");
760 (void)CPlusPlusOperatorKeyword;
761
762 // If this identifier is a macro, deserialize the macro
763 // definition.
764 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000765 uint32_t MacroDirectivesOffset =
766 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000767 DataLen -= 4;
768 SmallVector<uint32_t, 8> LocalMacroIDs;
769 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 while (uint32_t LocalMacroID =
771 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000772 DataLen -= 4;
773 LocalMacroIDs.push_back(LocalMacroID);
774 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000775 DataLen -= 4;
776 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000777
778 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000779 // Macro definitions are stored from newest to oldest, so reverse them
780 // before registering them.
781 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000782 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000783 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
784 unsigned Size = 1;
785
786 static const uint32_t HasOverridesFlag = 0x80000000U;
787 if (I + 1 != E && (I[1] & HasOverridesFlag))
788 Size += 1 + (I[1] & ~HasOverridesFlag);
789
790 MacroSizes.push_back(Size);
791 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000792 }
Richard Smith49f906a2014-03-01 00:08:04 +0000793
794 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
795 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
796 SE = MacroSizes.rend();
797 SI != SE; ++SI) {
798 I -= *SI;
799
800 uint32_t LocalMacroID = *I;
801 llvm::ArrayRef<uint32_t> Overrides;
802 if (*SI != 1)
803 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
804 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
805 }
806 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000807 } else {
808 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
809 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 }
811
812 Reader.SetIdentifierInfo(ID, II);
813
814 // Read all of the declarations visible at global scope with this
815 // name.
816 if (DataLen > 0) {
817 SmallVector<uint32_t, 4> DeclIDs;
818 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000819 DeclIDs.push_back(Reader.getGlobalDeclID(
820 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 Reader.SetGloballyVisibleDecls(II, DeclIDs);
822 }
823
824 return II;
825}
826
827unsigned
828ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
829 llvm::FoldingSetNodeID ID;
830 ID.AddInteger(Key.Kind);
831
832 switch (Key.Kind) {
833 case DeclarationName::Identifier:
834 case DeclarationName::CXXLiteralOperatorName:
835 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
836 break;
837 case DeclarationName::ObjCZeroArgSelector:
838 case DeclarationName::ObjCOneArgSelector:
839 case DeclarationName::ObjCMultiArgSelector:
840 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
841 break;
842 case DeclarationName::CXXOperatorName:
843 ID.AddInteger((OverloadedOperatorKind)Key.Data);
844 break;
845 case DeclarationName::CXXConstructorName:
846 case DeclarationName::CXXDestructorName:
847 case DeclarationName::CXXConversionFunctionName:
848 case DeclarationName::CXXUsingDirective:
849 break;
850 }
851
852 return ID.ComputeHash();
853}
854
855ASTDeclContextNameLookupTrait::internal_key_type
856ASTDeclContextNameLookupTrait::GetInternalKey(
857 const external_key_type& Name) const {
858 DeclNameKey Key;
859 Key.Kind = Name.getNameKind();
860 switch (Name.getNameKind()) {
861 case DeclarationName::Identifier:
862 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
863 break;
864 case DeclarationName::ObjCZeroArgSelector:
865 case DeclarationName::ObjCOneArgSelector:
866 case DeclarationName::ObjCMultiArgSelector:
867 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
868 break;
869 case DeclarationName::CXXOperatorName:
870 Key.Data = Name.getCXXOverloadedOperator();
871 break;
872 case DeclarationName::CXXLiteralOperatorName:
873 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
874 break;
875 case DeclarationName::CXXConstructorName:
876 case DeclarationName::CXXDestructorName:
877 case DeclarationName::CXXConversionFunctionName:
878 case DeclarationName::CXXUsingDirective:
879 Key.Data = 0;
880 break;
881 }
882
883 return Key;
884}
885
886std::pair<unsigned, unsigned>
887ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000888 using namespace llvm::support;
889 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
890 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000891 return std::make_pair(KeyLen, DataLen);
892}
893
894ASTDeclContextNameLookupTrait::internal_key_type
895ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000896 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000897
898 DeclNameKey Key;
899 Key.Kind = (DeclarationName::NameKind)*d++;
900 switch (Key.Kind) {
901 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 Key.Data = (uint64_t)Reader.getLocalIdentifier(
903 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 break;
905 case DeclarationName::ObjCZeroArgSelector:
906 case DeclarationName::ObjCOneArgSelector:
907 case DeclarationName::ObjCMultiArgSelector:
908 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 (uint64_t)Reader.getLocalSelector(
910 F, endian::readNext<uint32_t, little, unaligned>(
911 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 break;
913 case DeclarationName::CXXOperatorName:
914 Key.Data = *d++; // OverloadedOperatorKind
915 break;
916 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000917 Key.Data = (uint64_t)Reader.getLocalIdentifier(
918 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000919 break;
920 case DeclarationName::CXXConstructorName:
921 case DeclarationName::CXXDestructorName:
922 case DeclarationName::CXXConversionFunctionName:
923 case DeclarationName::CXXUsingDirective:
924 Key.Data = 0;
925 break;
926 }
927
928 return Key;
929}
930
931ASTDeclContextNameLookupTrait::data_type
932ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
933 const unsigned char* d,
934 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000935 using namespace llvm::support;
936 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000937 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
938 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 return std::make_pair(Start, Start + NumDecls);
940}
941
942bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000943 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 const std::pair<uint64_t, uint64_t> &Offsets,
945 DeclContextInfo &Info) {
946 SavedStreamPosition SavedPosition(Cursor);
947 // First the lexical decls.
948 if (Offsets.first != 0) {
949 Cursor.JumpToBit(Offsets.first);
950
951 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000952 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000954 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 if (RecCode != DECL_CONTEXT_LEXICAL) {
956 Error("Expected lexical block");
957 return true;
958 }
959
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
961 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 }
963
964 // Now the lookup table.
965 if (Offsets.second != 0) {
966 Cursor.JumpToBit(Offsets.second);
967
968 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000969 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000971 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 if (RecCode != DECL_CONTEXT_VISIBLE) {
973 Error("Expected visible lookup table block");
974 return true;
975 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000976 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
977 (const unsigned char *)Blob.data() + Record[0],
978 (const unsigned char *)Blob.data() + sizeof(uint32_t),
979 (const unsigned char *)Blob.data(),
980 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 }
982
983 return false;
984}
985
986void ASTReader::Error(StringRef Msg) {
987 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000988 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
989 Diag(diag::note_module_cache_path)
990 << PP.getHeaderSearchInfo().getModuleCachePath();
991 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000992}
993
994void ASTReader::Error(unsigned DiagID,
995 StringRef Arg1, StringRef Arg2) {
996 if (Diags.isDiagnosticInFlight())
997 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
998 else
999 Diag(DiagID) << Arg1 << Arg2;
1000}
1001
1002//===----------------------------------------------------------------------===//
1003// Source Manager Deserialization
1004//===----------------------------------------------------------------------===//
1005
1006/// \brief Read the line table in the source manager block.
1007/// \returns true if there was an error.
1008bool ASTReader::ParseLineTable(ModuleFile &F,
1009 SmallVectorImpl<uint64_t> &Record) {
1010 unsigned Idx = 0;
1011 LineTableInfo &LineTable = SourceMgr.getLineTable();
1012
1013 // Parse the file names
1014 std::map<int, int> FileIDs;
1015 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1016 // Extract the file name
1017 unsigned FilenameLen = Record[Idx++];
1018 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1019 Idx += FilenameLen;
1020 MaybeAddSystemRootToFilename(F, Filename);
1021 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1022 }
1023
1024 // Parse the line entries
1025 std::vector<LineEntry> Entries;
1026 while (Idx < Record.size()) {
1027 int FID = Record[Idx++];
1028 assert(FID >= 0 && "Serialized line entries for non-local file.");
1029 // Remap FileID from 1-based old view.
1030 FID += F.SLocEntryBaseID - 1;
1031
1032 // Extract the line entries
1033 unsigned NumEntries = Record[Idx++];
1034 assert(NumEntries && "Numentries is 00000");
1035 Entries.clear();
1036 Entries.reserve(NumEntries);
1037 for (unsigned I = 0; I != NumEntries; ++I) {
1038 unsigned FileOffset = Record[Idx++];
1039 unsigned LineNo = Record[Idx++];
1040 int FilenameID = FileIDs[Record[Idx++]];
1041 SrcMgr::CharacteristicKind FileKind
1042 = (SrcMgr::CharacteristicKind)Record[Idx++];
1043 unsigned IncludeOffset = Record[Idx++];
1044 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1045 FileKind, IncludeOffset));
1046 }
1047 LineTable.AddEntry(FileID::get(FID), Entries);
1048 }
1049
1050 return false;
1051}
1052
1053/// \brief Read a source manager block
1054bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1055 using namespace SrcMgr;
1056
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001057 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001058
1059 // Set the source-location entry cursor to the current position in
1060 // the stream. This cursor will be used to read the contents of the
1061 // source manager block initially, and then lazily read
1062 // source-location entries as needed.
1063 SLocEntryCursor = F.Stream;
1064
1065 // The stream itself is going to skip over the source manager block.
1066 if (F.Stream.SkipBlock()) {
1067 Error("malformed block record in AST file");
1068 return true;
1069 }
1070
1071 // Enter the source manager block.
1072 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1073 Error("malformed source manager block record in AST file");
1074 return true;
1075 }
1076
1077 RecordData Record;
1078 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001079 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1080
1081 switch (E.Kind) {
1082 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1083 case llvm::BitstreamEntry::Error:
1084 Error("malformed block record in AST file");
1085 return true;
1086 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001088 case llvm::BitstreamEntry::Record:
1089 // The interesting case.
1090 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001091 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001092
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001095 StringRef Blob;
1096 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 default: // Default behavior: ignore.
1098 break;
1099
1100 case SM_SLOC_FILE_ENTRY:
1101 case SM_SLOC_BUFFER_ENTRY:
1102 case SM_SLOC_EXPANSION_ENTRY:
1103 // Once we hit one of the source location entries, we're done.
1104 return false;
1105 }
1106 }
1107}
1108
1109/// \brief If a header file is not found at the path that we expect it to be
1110/// and the PCH file was moved from its original location, try to resolve the
1111/// file by assuming that header+PCH were moved together and the header is in
1112/// the same place relative to the PCH.
1113static std::string
1114resolveFileRelativeToOriginalDir(const std::string &Filename,
1115 const std::string &OriginalDir,
1116 const std::string &CurrDir) {
1117 assert(OriginalDir != CurrDir &&
1118 "No point trying to resolve the file if the PCH dir didn't change");
1119 using namespace llvm::sys;
1120 SmallString<128> filePath(Filename);
1121 fs::make_absolute(filePath);
1122 assert(path::is_absolute(OriginalDir));
1123 SmallString<128> currPCHPath(CurrDir);
1124
1125 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1126 fileDirE = path::end(path::parent_path(filePath));
1127 path::const_iterator origDirI = path::begin(OriginalDir),
1128 origDirE = path::end(OriginalDir);
1129 // Skip the common path components from filePath and OriginalDir.
1130 while (fileDirI != fileDirE && origDirI != origDirE &&
1131 *fileDirI == *origDirI) {
1132 ++fileDirI;
1133 ++origDirI;
1134 }
1135 for (; origDirI != origDirE; ++origDirI)
1136 path::append(currPCHPath, "..");
1137 path::append(currPCHPath, fileDirI, fileDirE);
1138 path::append(currPCHPath, path::filename(Filename));
1139 return currPCHPath.str();
1140}
1141
1142bool ASTReader::ReadSLocEntry(int ID) {
1143 if (ID == 0)
1144 return false;
1145
1146 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1147 Error("source location entry ID out-of-range for AST file");
1148 return true;
1149 }
1150
1151 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1152 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001153 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 unsigned BaseOffset = F->SLocEntryBaseOffset;
1155
1156 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001157 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1158 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001159 Error("incorrectly-formatted source location entry in AST file");
1160 return true;
1161 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001162
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001164 StringRef Blob;
1165 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 default:
1167 Error("incorrectly-formatted source location entry in AST file");
1168 return true;
1169
1170 case SM_SLOC_FILE_ENTRY: {
1171 // We will detect whether a file changed and return 'Failure' for it, but
1172 // we will also try to fail gracefully by setting up the SLocEntry.
1173 unsigned InputID = Record[4];
1174 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001175 const FileEntry *File = IF.getFile();
1176 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001177
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001178 // Note that we only check if a File was returned. If it was out-of-date
1179 // we have complained but we will continue creating a FileID to recover
1180 // gracefully.
1181 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 return true;
1183
1184 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1185 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1186 // This is the module's main file.
1187 IncludeLoc = getImportLocation(F);
1188 }
1189 SrcMgr::CharacteristicKind
1190 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1191 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1192 ID, BaseOffset + Record[0]);
1193 SrcMgr::FileInfo &FileInfo =
1194 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1195 FileInfo.NumCreatedFIDs = Record[5];
1196 if (Record[3])
1197 FileInfo.setHasLineDirectives();
1198
1199 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1200 unsigned NumFileDecls = Record[7];
1201 if (NumFileDecls) {
1202 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1203 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1204 NumFileDecls));
1205 }
1206
1207 const SrcMgr::ContentCache *ContentCache
1208 = SourceMgr.getOrCreateContentCache(File,
1209 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1210 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1211 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1212 unsigned Code = SLocEntryCursor.ReadCode();
1213 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001214 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001215
1216 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1217 Error("AST record has invalid code");
1218 return true;
1219 }
1220
1221 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001222 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001223 SourceMgr.overrideFileContents(File, Buffer);
1224 }
1225
1226 break;
1227 }
1228
1229 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001230 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 unsigned Offset = Record[0];
1232 SrcMgr::CharacteristicKind
1233 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1234 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1235 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1236 IncludeLoc = getImportLocation(F);
1237 }
1238 unsigned Code = SLocEntryCursor.ReadCode();
1239 Record.clear();
1240 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001241 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001242
1243 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1244 Error("AST record has invalid code");
1245 return true;
1246 }
1247
1248 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001249 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1251 BaseOffset + Offset, IncludeLoc);
1252 break;
1253 }
1254
1255 case SM_SLOC_EXPANSION_ENTRY: {
1256 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1257 SourceMgr.createExpansionLoc(SpellingLoc,
1258 ReadSourceLocation(*F, Record[2]),
1259 ReadSourceLocation(*F, Record[3]),
1260 Record[4],
1261 ID,
1262 BaseOffset + Record[0]);
1263 break;
1264 }
1265 }
1266
1267 return false;
1268}
1269
1270std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1271 if (ID == 0)
1272 return std::make_pair(SourceLocation(), "");
1273
1274 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1275 Error("source location entry ID out-of-range for AST file");
1276 return std::make_pair(SourceLocation(), "");
1277 }
1278
1279 // Find which module file this entry lands in.
1280 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1281 if (M->Kind != MK_Module)
1282 return std::make_pair(SourceLocation(), "");
1283
1284 // FIXME: Can we map this down to a particular submodule? That would be
1285 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001286 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001287}
1288
1289/// \brief Find the location where the module F is imported.
1290SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1291 if (F->ImportLoc.isValid())
1292 return F->ImportLoc;
1293
1294 // Otherwise we have a PCH. It's considered to be "imported" at the first
1295 // location of its includer.
1296 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001297 // Main file is the importer.
1298 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1299 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 return F->ImportedBy[0]->FirstLoc;
1302}
1303
1304/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1305/// specified cursor. Read the abbreviations that are at the top of the block
1306/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001307bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 if (Cursor.EnterSubBlock(BlockID)) {
1309 Error("malformed block record in AST file");
1310 return Failure;
1311 }
1312
1313 while (true) {
1314 uint64_t Offset = Cursor.GetCurrentBitNo();
1315 unsigned Code = Cursor.ReadCode();
1316
1317 // We expect all abbrevs to be at the start of the block.
1318 if (Code != llvm::bitc::DEFINE_ABBREV) {
1319 Cursor.JumpToBit(Offset);
1320 return false;
1321 }
1322 Cursor.ReadAbbrevRecord();
1323 }
1324}
1325
Richard Smithe40f2ba2013-08-07 21:41:30 +00001326Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001327 unsigned &Idx) {
1328 Token Tok;
1329 Tok.startToken();
1330 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1331 Tok.setLength(Record[Idx++]);
1332 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1333 Tok.setIdentifierInfo(II);
1334 Tok.setKind((tok::TokenKind)Record[Idx++]);
1335 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1336 return Tok;
1337}
1338
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001339MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001340 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001341
1342 // Keep track of where we are in the stream, then jump back there
1343 // after reading this macro.
1344 SavedStreamPosition SavedPosition(Stream);
1345
1346 Stream.JumpToBit(Offset);
1347 RecordData Record;
1348 SmallVector<IdentifierInfo*, 16> MacroArgs;
1349 MacroInfo *Macro = 0;
1350
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001352 // Advance to the next record, but if we get to the end of the block, don't
1353 // pop it (removing all the abbreviations from the cursor) since we want to
1354 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001355 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001356 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1357
1358 switch (Entry.Kind) {
1359 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1360 case llvm::BitstreamEntry::Error:
1361 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001362 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001364 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001365 case llvm::BitstreamEntry::Record:
1366 // The interesting case.
1367 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 }
1369
1370 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 Record.clear();
1372 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001373 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001375 case PP_MACRO_DIRECTIVE_HISTORY:
1376 return Macro;
1377
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 case PP_MACRO_OBJECT_LIKE:
1379 case PP_MACRO_FUNCTION_LIKE: {
1380 // If we already have a macro, that means that we've hit the end
1381 // of the definition of the macro we were looking for. We're
1382 // done.
1383 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001384 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001385
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001386 unsigned NextIndex = 1; // Skip identifier ID.
1387 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001389 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001390 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001392 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1395 // Decode function-like macro info.
1396 bool isC99VarArgs = Record[NextIndex++];
1397 bool isGNUVarArgs = Record[NextIndex++];
1398 bool hasCommaPasting = Record[NextIndex++];
1399 MacroArgs.clear();
1400 unsigned NumArgs = Record[NextIndex++];
1401 for (unsigned i = 0; i != NumArgs; ++i)
1402 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1403
1404 // Install function-like macro info.
1405 MI->setIsFunctionLike();
1406 if (isC99VarArgs) MI->setIsC99Varargs();
1407 if (isGNUVarArgs) MI->setIsGNUVarargs();
1408 if (hasCommaPasting) MI->setHasCommaPasting();
1409 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1410 PP.getPreprocessorAllocator());
1411 }
1412
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 // Remember that we saw this macro last so that we add the tokens that
1414 // form its body to it.
1415 Macro = MI;
1416
1417 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1418 Record[NextIndex]) {
1419 // We have a macro definition. Register the association
1420 PreprocessedEntityID
1421 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1422 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001423 PreprocessingRecord::PPEntityID
1424 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1425 MacroDefinition *PPDef =
1426 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1427 if (PPDef)
1428 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 }
1430
1431 ++NumMacrosRead;
1432 break;
1433 }
1434
1435 case PP_TOKEN: {
1436 // If we see a TOKEN before a PP_MACRO_*, then the file is
1437 // erroneous, just pretend we didn't see this.
1438 if (Macro == 0) break;
1439
John McCallf413f5e2013-05-03 00:10:13 +00001440 unsigned Idx = 0;
1441 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 Macro->AddTokenToBody(Tok);
1443 break;
1444 }
1445 }
1446 }
1447}
1448
1449PreprocessedEntityID
1450ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1451 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1452 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1453 assert(I != M.PreprocessedEntityRemap.end()
1454 && "Invalid index into preprocessed entity index remap");
1455
1456 return LocalID + I->second;
1457}
1458
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001459unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1460 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001461}
1462
1463HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001464HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1465 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1466 FE->getName() };
1467 return ikey;
1468}
Guy Benyei11169dd2012-12-18 14:30:41 +00001469
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001470bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1471 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 return false;
1473
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001474 if (strcmp(a.Filename, b.Filename) == 0)
1475 return true;
1476
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001478 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1480 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001481 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001482}
1483
1484std::pair<unsigned, unsigned>
1485HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001486 using namespace llvm::support;
1487 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001489 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001490}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001491
1492HeaderFileInfoTrait::internal_key_type
1493HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001494 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001495 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001496 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1497 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498 ikey.Filename = (const char *)d;
1499 return ikey;
1500}
1501
Guy Benyei11169dd2012-12-18 14:30:41 +00001502HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001503HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 unsigned DataLen) {
1505 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001506 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001507 HeaderFileInfo HFI;
1508 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001509 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1510 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 HFI.isImport = (Flags >> 5) & 0x01;
1512 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1513 HFI.DirInfo = (Flags >> 2) & 0x03;
1514 HFI.Resolved = (Flags >> 1) & 0x01;
1515 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001516 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1517 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1518 M, endian::readNext<uint32_t, little, unaligned>(d));
1519 if (unsigned FrameworkOffset =
1520 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // The framework offset is 1 greater than the actual offset,
1522 // since 0 is used as an indicator for "no framework name".
1523 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1524 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1525 }
1526
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001527 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001528 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001529 if (LocalSMID) {
1530 // This header is part of a module. Associate it with the module to enable
1531 // implicit module import.
1532 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1533 Module *Mod = Reader.getSubmodule(GlobalSMID);
1534 HFI.isModuleHeader = true;
1535 FileManager &FileMgr = Reader.getFileManager();
1536 ModuleMap &ModMap =
1537 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001538 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001539 }
1540 }
1541
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1543 (void)End;
1544
1545 // This HeaderFileInfo was externally loaded.
1546 HFI.External = true;
1547 return HFI;
1548}
1549
Richard Smith49f906a2014-03-01 00:08:04 +00001550void
1551ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1552 GlobalMacroID GMacID,
1553 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001555 SubmoduleID *OverrideData = 0;
1556 if (!Overrides.empty()) {
1557 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1558 OverrideData[0] = Overrides.size();
1559 for (unsigned I = 0; I != Overrides.size(); ++I)
1560 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1561 }
1562 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001563}
1564
1565void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1566 ModuleFile *M,
1567 uint64_t MacroDirectivesOffset) {
1568 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1569 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001570}
1571
1572void ASTReader::ReadDefinedMacros() {
1573 // Note that we are loading defined macros.
1574 Deserializing Macros(this);
1575
1576 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1577 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001578 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001579
1580 // If there was no preprocessor block, skip this file.
1581 if (!MacroCursor.getBitStreamReader())
1582 continue;
1583
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001584 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 Cursor.JumpToBit((*I)->MacroStartOffset);
1586
1587 RecordData Record;
1588 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001589 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1590
1591 switch (E.Kind) {
1592 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1593 case llvm::BitstreamEntry::Error:
1594 Error("malformed block record in AST file");
1595 return;
1596 case llvm::BitstreamEntry::EndBlock:
1597 goto NextCursor;
1598
1599 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001600 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001601 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001602 default: // Default behavior: ignore.
1603 break;
1604
1605 case PP_MACRO_OBJECT_LIKE:
1606 case PP_MACRO_FUNCTION_LIKE:
1607 getLocalIdentifier(**I, Record[0]);
1608 break;
1609
1610 case PP_TOKEN:
1611 // Ignore tokens.
1612 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 break;
1615 }
1616 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 }
1619}
1620
1621namespace {
1622 /// \brief Visitor class used to look up identifirs in an AST file.
1623 class IdentifierLookupVisitor {
1624 StringRef Name;
1625 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001626 unsigned &NumIdentifierLookups;
1627 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001629
Guy Benyei11169dd2012-12-18 14:30:41 +00001630 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001631 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1632 unsigned &NumIdentifierLookups,
1633 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001634 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001635 NumIdentifierLookups(NumIdentifierLookups),
1636 NumIdentifierLookupHits(NumIdentifierLookupHits),
1637 Found()
1638 {
1639 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001640
1641 static bool visit(ModuleFile &M, void *UserData) {
1642 IdentifierLookupVisitor *This
1643 = static_cast<IdentifierLookupVisitor *>(UserData);
1644
1645 // If we've already searched this module file, skip it now.
1646 if (M.Generation <= This->PriorGeneration)
1647 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001648
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 ASTIdentifierLookupTable *IdTable
1650 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1651 if (!IdTable)
1652 return false;
1653
1654 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1655 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001656 ++This->NumIdentifierLookups;
1657 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 if (Pos == IdTable->end())
1659 return false;
1660
1661 // Dereferencing the iterator has the effect of building the
1662 // IdentifierInfo node and populating it with the various
1663 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001664 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 This->Found = *Pos;
1666 return true;
1667 }
1668
1669 // \brief Retrieve the identifier info found within the module
1670 // files.
1671 IdentifierInfo *getIdentifierInfo() const { return Found; }
1672 };
1673}
1674
1675void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1676 // Note that we are loading an identifier.
1677 Deserializing AnIdentifier(this);
1678
1679 unsigned PriorGeneration = 0;
1680 if (getContext().getLangOpts().Modules)
1681 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001682
1683 // If there is a global index, look there first to determine which modules
1684 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001685 GlobalModuleIndex::HitSet Hits;
1686 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001687 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001688 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1689 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001690 }
1691 }
1692
Douglas Gregor7211ac12013-01-25 23:32:03 +00001693 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001694 NumIdentifierLookups,
1695 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001696 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 markIdentifierUpToDate(&II);
1698}
1699
1700void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1701 if (!II)
1702 return;
1703
1704 II->setOutOfDate(false);
1705
1706 // Update the generation for this identifier.
1707 if (getContext().getLangOpts().Modules)
1708 IdentifierGeneration[II] = CurrentGeneration;
1709}
1710
Richard Smith49f906a2014-03-01 00:08:04 +00001711struct ASTReader::ModuleMacroInfo {
1712 SubmoduleID SubModID;
1713 MacroInfo *MI;
1714 SubmoduleID *Overrides;
1715 // FIXME: Remove this.
1716 ModuleFile *F;
1717
1718 bool isDefine() const { return MI; }
1719
1720 SubmoduleID getSubmoduleID() const { return SubModID; }
1721
1722 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1723 if (!Overrides)
1724 return llvm::ArrayRef<SubmoduleID>();
1725 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1726 }
1727
1728 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1729 if (!MI)
1730 return 0;
1731 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1732 }
1733};
1734
1735ASTReader::ModuleMacroInfo *
1736ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1737 ModuleMacroInfo Info;
1738
1739 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1740 if (ID & 1) {
1741 // Macro undefinition.
1742 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1743 Info.MI = 0;
1744 } else {
1745 // Macro definition.
1746 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1747 assert(GMacID);
1748
1749 // If this macro has already been loaded, don't do so again.
1750 // FIXME: This is highly dubious. Multiple macro definitions can have the
1751 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1752 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1753 return 0;
1754
1755 Info.MI = getMacro(GMacID);
1756 Info.SubModID = Info.MI->getOwningModuleID();
1757 }
1758 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1759 Info.F = PMInfo.M;
1760
1761 return new (Context) ModuleMacroInfo(Info);
1762}
1763
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1765 const PendingMacroInfo &PMInfo) {
1766 assert(II);
1767
1768 if (PMInfo.M->Kind != MK_Module) {
1769 installPCHMacroDirectives(II, *PMInfo.M,
1770 PMInfo.PCHMacroData.MacroDirectivesOffset);
1771 return;
1772 }
Richard Smith49f906a2014-03-01 00:08:04 +00001773
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001774 // Module Macro.
1775
Richard Smith49f906a2014-03-01 00:08:04 +00001776 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1777 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001778 return;
1779
Richard Smith49f906a2014-03-01 00:08:04 +00001780 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1781 if (Owner && Owner->NameVisibility == Module::Hidden) {
1782 // Macros in the owning module are hidden. Just remember this macro to
1783 // install if we make this module visible.
1784 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1785 } else {
1786 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001787 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788}
1789
1790void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1791 ModuleFile &M, uint64_t Offset) {
1792 assert(M.Kind != MK_Module);
1793
1794 BitstreamCursor &Cursor = M.MacroCursor;
1795 SavedStreamPosition SavedPosition(Cursor);
1796 Cursor.JumpToBit(Offset);
1797
1798 llvm::BitstreamEntry Entry =
1799 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1800 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1801 Error("malformed block record in AST file");
1802 return;
1803 }
1804
1805 RecordData Record;
1806 PreprocessorRecordTypes RecType =
1807 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1808 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1809 Error("malformed block record in AST file");
1810 return;
1811 }
1812
1813 // Deserialize the macro directives history in reverse source-order.
1814 MacroDirective *Latest = 0, *Earliest = 0;
1815 unsigned Idx = 0, N = Record.size();
1816 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001817 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001818 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001819 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1820 switch (K) {
1821 case MacroDirective::MD_Define: {
1822 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1823 MacroInfo *MI = getMacro(GMacID);
1824 bool isImported = Record[Idx++];
1825 bool isAmbiguous = Record[Idx++];
1826 DefMacroDirective *DefMD =
1827 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1828 DefMD->setAmbiguous(isAmbiguous);
1829 MD = DefMD;
1830 break;
1831 }
1832 case MacroDirective::MD_Undefine:
1833 MD = PP.AllocateUndefMacroDirective(Loc);
1834 break;
1835 case MacroDirective::MD_Visibility: {
1836 bool isPublic = Record[Idx++];
1837 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1838 break;
1839 }
1840 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001841
1842 if (!Latest)
1843 Latest = MD;
1844 if (Earliest)
1845 Earliest->setPrevious(MD);
1846 Earliest = MD;
1847 }
1848
1849 PP.setLoadedMacroDirective(II, Latest);
1850}
1851
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001852/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001853/// modules.
1854static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001855 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001856 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001857 Module *PrevOwner = 0;
1858 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1859 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001860 SourceManager &SrcMgr = Reader.getSourceManager();
1861 bool PrevInSystem
1862 = PrevOwner? PrevOwner->IsSystem
1863 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1864 bool NewInSystem
1865 = NewOwner? NewOwner->IsSystem
1866 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1867 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001868 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001869 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001870}
1871
Richard Smith49f906a2014-03-01 00:08:04 +00001872void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1873 AmbiguousMacros &Ambig,
1874 llvm::ArrayRef<SubmoduleID> Overrides) {
1875 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1876 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
Richard Smith49f906a2014-03-01 00:08:04 +00001878 // If this macro is not yet visible, remove it from the hidden names list.
1879 Module *Owner = getSubmodule(OwnerID);
1880 HiddenNames &Hidden = HiddenNamesMap[Owner];
1881 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1882 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001883 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001884 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001885 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001886 }
1887
1888 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001889 Ambig.erase(
1890 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1891 return MD->getInfo()->getOwningModuleID() == OwnerID;
1892 }),
1893 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001894 }
1895}
1896
1897ASTReader::AmbiguousMacros *
1898ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1899 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001900 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001901 if (!Prev && Overrides.empty())
1902 return 0;
1903
1904 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1905 if (PrevDef && PrevDef->isAmbiguous()) {
1906 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1907 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1908 Ambig.push_back(PrevDef);
1909
1910 removeOverriddenMacros(II, Ambig, Overrides);
1911
1912 if (!Ambig.empty())
1913 return &Ambig;
1914
1915 AmbiguousMacroDefs.erase(II);
1916 } else {
1917 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001918 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001919 if (PrevDef)
1920 Ambig.push_back(PrevDef);
1921
1922 removeOverriddenMacros(II, Ambig, Overrides);
1923
1924 if (!Ambig.empty()) {
1925 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001926 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001927 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001928 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001929 }
Richard Smith49f906a2014-03-01 00:08:04 +00001930
1931 // We ended up with no ambiguity.
1932 return 0;
1933}
1934
1935void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1936 Module *Owner) {
1937 assert(II && Owner);
1938
1939 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1940 if (ImportLoc.isInvalid()) {
1941 // FIXME: If we made macros from this module visible but didn't provide a
1942 // source location for the import, we don't have a location for the macro.
1943 // Use the location at which the containing module file was first imported
1944 // for now.
1945 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001946 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001947 }
1948
Benjamin Kramer834652a2014-05-03 18:44:26 +00001949 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001950 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1951
Richard Smith49f906a2014-03-01 00:08:04 +00001952 // Create a synthetic macro definition corresponding to the import (or null
1953 // if this was an undefinition of the macro).
1954 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1955
1956 // If there's no ambiguity, just install the macro.
1957 if (!Prev) {
1958 if (MD)
1959 PP.appendMacroDirective(II, MD);
1960 else
1961 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1962 return;
1963 }
1964 assert(!Prev->empty());
1965
1966 if (!MD) {
1967 // We imported a #undef that didn't remove all prior definitions. The most
1968 // recent prior definition remains, and we install it in the place of the
1969 // imported directive.
1970 MacroInfo *NewMI = Prev->back()->getInfo();
1971 Prev->pop_back();
1972 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1973 }
1974
1975 // We're introducing a macro definition that creates or adds to an ambiguity.
1976 // We can resolve that ambiguity if this macro is token-for-token identical to
1977 // all of the existing definitions.
1978 MacroInfo *NewMI = MD->getInfo();
1979 assert(NewMI && "macro definition with no MacroInfo?");
1980 while (!Prev->empty()) {
1981 MacroInfo *PrevMI = Prev->back()->getInfo();
1982 assert(PrevMI && "macro definition with no MacroInfo?");
1983
1984 // Before marking the macros as ambiguous, check if this is a case where
1985 // both macros are in system headers. If so, we trust that the system
1986 // did not get it wrong. This also handles cases where Clang's own
1987 // headers have a different spelling of certain system macros:
1988 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1989 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1990 //
1991 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1992 // overrides the system limits.h's macros, so there's no conflict here.
1993 if (NewMI != PrevMI &&
1994 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1995 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1996 break;
1997
1998 // The previous definition is the same as this one (or both are defined in
1999 // system modules so we can assume they're equivalent); we don't need to
2000 // track it any more.
2001 Prev->pop_back();
2002 }
2003
2004 if (!Prev->empty())
2005 MD->setAmbiguous(true);
2006
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002007 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002008}
2009
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002010ASTReader::InputFileInfo
2011ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // Go find this input file.
2013 BitstreamCursor &Cursor = F.InputFilesCursor;
2014 SavedStreamPosition SavedPosition(Cursor);
2015 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2016
2017 unsigned Code = Cursor.ReadCode();
2018 RecordData Record;
2019 StringRef Blob;
2020
2021 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2022 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2023 "invalid record type for input file");
2024 (void)Result;
2025
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002026 std::string Filename;
2027 off_t StoredSize;
2028 time_t StoredTime;
2029 bool Overridden;
2030
Ben Langmuir198c1682014-03-07 07:27:49 +00002031 assert(Record[0] == ID && "Bogus stored ID or offset");
2032 StoredSize = static_cast<off_t>(Record[1]);
2033 StoredTime = static_cast<time_t>(Record[2]);
2034 Overridden = static_cast<bool>(Record[3]);
2035 Filename = Blob;
2036 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002037
Hans Wennborg73945142014-03-14 17:45:06 +00002038 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2039 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002040}
2041
2042std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002043 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002044}
2045
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002046InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 // If this ID is bogus, just return an empty input file.
2048 if (ID == 0 || ID > F.InputFilesLoaded.size())
2049 return InputFile();
2050
2051 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002052 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002053 return F.InputFilesLoaded[ID-1];
2054
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002055 if (F.InputFilesLoaded[ID-1].isNotFound())
2056 return InputFile();
2057
Guy Benyei11169dd2012-12-18 14:30:41 +00002058 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002059 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002060 SavedStreamPosition SavedPosition(Cursor);
2061 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2062
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002063 InputFileInfo FI = readInputFileInfo(F, ID);
2064 off_t StoredSize = FI.StoredSize;
2065 time_t StoredTime = FI.StoredTime;
2066 bool Overridden = FI.Overridden;
2067 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002068
Ben Langmuir198c1682014-03-07 07:27:49 +00002069 const FileEntry *File
2070 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2071 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2072
2073 // If we didn't find the file, resolve it relative to the
2074 // original directory from which this AST file was created.
2075 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2076 F.OriginalDir != CurrentDir) {
2077 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2078 F.OriginalDir,
2079 CurrentDir);
2080 if (!Resolved.empty())
2081 File = FileMgr.getFile(Resolved);
2082 }
2083
2084 // For an overridden file, create a virtual file with the stored
2085 // size/timestamp.
2086 if (Overridden && File == 0) {
2087 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2088 }
2089
2090 if (File == 0) {
2091 if (Complain) {
2092 std::string ErrorStr = "could not find file '";
2093 ErrorStr += Filename;
2094 ErrorStr += "' referenced by AST file";
2095 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 // Record that we didn't find the file.
2098 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2099 return InputFile();
2100 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002101
Ben Langmuir198c1682014-03-07 07:27:49 +00002102 // Check if there was a request to override the contents of the file
2103 // that was part of the precompiled header. Overridding such a file
2104 // can lead to problems when lexing using the source locations from the
2105 // PCH.
2106 SourceManager &SM = getSourceManager();
2107 if (!Overridden && SM.isFileOverridden(File)) {
2108 if (Complain)
2109 Error(diag::err_fe_pch_file_overridden, Filename);
2110 // After emitting the diagnostic, recover by disabling the override so
2111 // that the original file will be used.
2112 SM.disableFileContentsOverride(File);
2113 // The FileEntry is a virtual file entry with the size of the contents
2114 // that would override the original contents. Set it to the original's
2115 // size/time.
2116 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2117 StoredSize, StoredTime);
2118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002119
Ben Langmuir198c1682014-03-07 07:27:49 +00002120 bool IsOutOfDate = false;
2121
2122 // For an overridden file, there is nothing to validate.
2123 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002124#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002125 // In our regression testing, the Windows file system seems to
2126 // have inconsistent modification times that sometimes
2127 // erroneously trigger this error-handling path.
2128 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002129#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002130 )) {
2131 if (Complain) {
2132 // Build a list of the PCH imports that got us here (in reverse).
2133 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2134 while (ImportStack.back()->ImportedBy.size() > 0)
2135 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002136
Ben Langmuir198c1682014-03-07 07:27:49 +00002137 // The top-level PCH is stale.
2138 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2139 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002140
Ben Langmuir198c1682014-03-07 07:27:49 +00002141 // Print the import stack.
2142 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2143 Diag(diag::note_pch_required_by)
2144 << Filename << ImportStack[0]->FileName;
2145 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002146 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002147 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002148 }
2149
Ben Langmuir198c1682014-03-07 07:27:49 +00002150 if (!Diags.isDiagnosticInFlight())
2151 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 }
2153
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 }
2156
Ben Langmuir198c1682014-03-07 07:27:49 +00002157 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2158
2159 // Note that we've loaded this input file.
2160 F.InputFilesLoaded[ID-1] = IF;
2161 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002162}
2163
2164const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2165 ModuleFile &M = ModuleMgr.getPrimaryModule();
2166 std::string Filename = filenameStrRef;
2167 MaybeAddSystemRootToFilename(M, Filename);
2168 const FileEntry *File = FileMgr.getFile(Filename);
2169 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2170 M.OriginalDir != CurrentDir) {
2171 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2172 M.OriginalDir,
2173 CurrentDir);
2174 if (!resolved.empty())
2175 File = FileMgr.getFile(resolved);
2176 }
2177
2178 return File;
2179}
2180
2181/// \brief If we are loading a relocatable PCH file, and the filename is
2182/// not an absolute path, add the system root to the beginning of the file
2183/// name.
2184void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2185 std::string &Filename) {
2186 // If this is not a relocatable PCH file, there's nothing to do.
2187 if (!M.RelocatablePCH)
2188 return;
2189
2190 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2191 return;
2192
2193 if (isysroot.empty()) {
2194 // If no system root was given, default to '/'
2195 Filename.insert(Filename.begin(), '/');
2196 return;
2197 }
2198
2199 unsigned Length = isysroot.size();
2200 if (isysroot[Length - 1] != '/')
2201 Filename.insert(Filename.begin(), '/');
2202
2203 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2204}
2205
2206ASTReader::ASTReadResult
2207ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002208 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002209 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002211 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002212
2213 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2214 Error("malformed block record in AST file");
2215 return Failure;
2216 }
2217
2218 // Read all of the records and blocks in the control block.
2219 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002220 while (1) {
2221 llvm::BitstreamEntry Entry = Stream.advance();
2222
2223 switch (Entry.Kind) {
2224 case llvm::BitstreamEntry::Error:
2225 Error("malformed block record in AST file");
2226 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002227 case llvm::BitstreamEntry::EndBlock: {
2228 // Validate input files.
2229 const HeaderSearchOptions &HSOpts =
2230 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002231
2232 // All user input files reside at the index range [0, Record[1]), and
2233 // system input files reside at [Record[1], Record[0]).
2234 // Record is the one from INPUT_FILE_OFFSETS.
2235 unsigned NumInputs = Record[0];
2236 unsigned NumUserInputs = Record[1];
2237
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002238 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002239 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002240 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002242
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002243 // If we are reading a module, we will create a verification timestamp,
2244 // so we verify all input files. Otherwise, verify only user input
2245 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002246
2247 unsigned N = NumUserInputs;
2248 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002249 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2250 N = NumInputs;
2251
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002252 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002253 InputFile IF = getInputFile(F, I+1, Complain);
2254 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002256 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002258
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002259 if (Listener)
2260 Listener->visitModuleFile(F.FileName);
2261
Ben Langmuircb69b572014-03-07 06:40:32 +00002262 if (Listener && Listener->needsInputFileVisitation()) {
2263 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2264 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002265 for (unsigned I = 0; I < N; ++I) {
2266 bool IsSystem = I >= NumUserInputs;
2267 InputFileInfo FI = readInputFileInfo(F, I+1);
2268 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2269 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002270 }
2271
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002273 }
2274
Chris Lattnere7b154b2013-01-19 21:39:22 +00002275 case llvm::BitstreamEntry::SubBlock:
2276 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 case INPUT_FILES_BLOCK_ID:
2278 F.InputFilesCursor = Stream;
2279 if (Stream.SkipBlock() || // Skip with the main cursor
2280 // Read the abbreviations
2281 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2282 Error("malformed block record in AST file");
2283 return Failure;
2284 }
2285 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002286
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002288 if (Stream.SkipBlock()) {
2289 Error("malformed block record in AST file");
2290 return Failure;
2291 }
2292 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002294
2295 case llvm::BitstreamEntry::Record:
2296 // The interesting case.
2297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 }
2299
2300 // Read and process a record.
2301 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002302 StringRef Blob;
2303 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 case METADATA: {
2305 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2306 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002307 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2308 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 return VersionMismatch;
2310 }
2311
2312 bool hasErrors = Record[5];
2313 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2314 Diag(diag::err_pch_with_compiler_errors);
2315 return HadErrors;
2316 }
2317
2318 F.RelocatablePCH = Record[4];
2319
2320 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002321 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2323 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002324 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 return VersionMismatch;
2326 }
2327 break;
2328 }
2329
2330 case IMPORTS: {
2331 // Load each of the imported PCH files.
2332 unsigned Idx = 0, N = Record.size();
2333 while (Idx < N) {
2334 // Read information about the AST file.
2335 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2336 // The import location will be the local one for now; we will adjust
2337 // all import locations of module imports after the global source
2338 // location info are setup.
2339 SourceLocation ImportLoc =
2340 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002341 off_t StoredSize = (off_t)Record[Idx++];
2342 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002343 unsigned Length = Record[Idx++];
2344 SmallString<128> ImportedFile(Record.begin() + Idx,
2345 Record.begin() + Idx + Length);
2346 Idx += Length;
2347
2348 // Load the AST file.
2349 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002350 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 ClientLoadCapabilities)) {
2352 case Failure: return Failure;
2353 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002354 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 case OutOfDate: return OutOfDate;
2356 case VersionMismatch: return VersionMismatch;
2357 case ConfigurationMismatch: return ConfigurationMismatch;
2358 case HadErrors: return HadErrors;
2359 case Success: break;
2360 }
2361 }
2362 break;
2363 }
2364
2365 case LANGUAGE_OPTIONS: {
2366 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2367 if (Listener && &F == *ModuleMgr.begin() &&
2368 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002369 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 return ConfigurationMismatch;
2371 break;
2372 }
2373
2374 case TARGET_OPTIONS: {
2375 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2376 if (Listener && &F == *ModuleMgr.begin() &&
2377 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002378 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 return ConfigurationMismatch;
2380 break;
2381 }
2382
2383 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002384 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 if (Listener && &F == *ModuleMgr.begin() &&
2386 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002387 !DisableValidation)
2388 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 break;
2390 }
2391
2392 case FILE_SYSTEM_OPTIONS: {
2393 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2394 if (Listener && &F == *ModuleMgr.begin() &&
2395 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002396 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 return ConfigurationMismatch;
2398 break;
2399 }
2400
2401 case HEADER_SEARCH_OPTIONS: {
2402 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2403 if (Listener && &F == *ModuleMgr.begin() &&
2404 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002405 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 return ConfigurationMismatch;
2407 break;
2408 }
2409
2410 case PREPROCESSOR_OPTIONS: {
2411 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2412 if (Listener && &F == *ModuleMgr.begin() &&
2413 ParsePreprocessorOptions(Record, Complain, *Listener,
2414 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002415 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 return ConfigurationMismatch;
2417 break;
2418 }
2419
2420 case ORIGINAL_FILE:
2421 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002422 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2424 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2425 break;
2426
2427 case ORIGINAL_FILE_ID:
2428 F.OriginalSourceFileID = FileID::get(Record[0]);
2429 break;
2430
2431 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 break;
2434
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002435 case MODULE_NAME:
2436 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002437 if (Listener)
2438 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002439 break;
2440
2441 case MODULE_MAP_FILE:
2442 F.ModuleMapPath = Blob;
2443
2444 // Try to resolve ModuleName in the current header search context and
2445 // verify that it is found in the same module map file as we saved. If the
2446 // top-level AST file is a main file, skip this check because there is no
2447 // usable header search context.
2448 assert(!F.ModuleName.empty() &&
2449 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2450 if (F.Kind == MK_Module &&
2451 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2452 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2453 if (!M) {
2454 assert(ImportedBy && "top-level import should be verified");
2455 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2456 Diag(diag::err_imported_module_not_found)
2457 << F.ModuleName << ImportedBy->FileName;
2458 return Missing;
2459 }
2460
2461 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2462 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2463 assert(M->ModuleMap && "found module is missing module map file");
2464 assert(M->Name == F.ModuleName && "found module with different name");
2465 assert(ImportedBy && "top-level import should be verified");
2466 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2467 Diag(diag::err_imported_module_modmap_changed)
2468 << F.ModuleName << ImportedBy->FileName
2469 << M->ModuleMap->getName() << F.ModuleMapPath;
2470 return OutOfDate;
2471 }
2472 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002473
2474 if (Listener)
2475 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002476 break;
2477
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002479 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 F.InputFilesLoaded.resize(Record[0]);
2481 break;
2482 }
2483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002484}
2485
Ben Langmuir2c9af442014-04-10 17:57:43 +00002486ASTReader::ASTReadResult
2487ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002488 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002489
2490 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2491 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 }
2494
2495 // Read all of the records and blocks for the AST file.
2496 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002497 while (1) {
2498 llvm::BitstreamEntry Entry = Stream.advance();
2499
2500 switch (Entry.Kind) {
2501 case llvm::BitstreamEntry::Error:
2502 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002503 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002504 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002505 // Outside of C++, we do not store a lookup map for the translation unit.
2506 // Instead, mark it as needing a lookup map to be built if this module
2507 // contains any declarations lexically within it (which it always does!).
2508 // This usually has no cost, since we very rarely need the lookup map for
2509 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002511 if (DC->hasExternalLexicalStorage() &&
2512 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514
Ben Langmuir2c9af442014-04-10 17:57:43 +00002515 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002517 case llvm::BitstreamEntry::SubBlock:
2518 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 case DECLTYPES_BLOCK_ID:
2520 // We lazily load the decls block, but we want to set up the
2521 // DeclsCursor cursor to point into it. Clone our current bitcode
2522 // cursor to it, enter the block and read the abbrevs in that block.
2523 // With the main cursor, we just skip over it.
2524 F.DeclsCursor = Stream;
2525 if (Stream.SkipBlock() || // Skip with the main cursor.
2526 // Read the abbrevs.
2527 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2528 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002529 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 }
2531 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002532
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 case PREPROCESSOR_BLOCK_ID:
2534 F.MacroCursor = Stream;
2535 if (!PP.getExternalSource())
2536 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002537
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 if (Stream.SkipBlock() ||
2539 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2540 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002541 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 }
2543 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2544 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 case PREPROCESSOR_DETAIL_BLOCK_ID:
2547 F.PreprocessorDetailCursor = Stream;
2548 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002551 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002552 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2556
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 if (!PP.getPreprocessingRecord())
2558 PP.createPreprocessingRecord();
2559 if (!PP.getPreprocessingRecord()->getExternalSource())
2560 PP.getPreprocessingRecord()->SetExternalSource(*this);
2561 break;
2562
2563 case SOURCE_MANAGER_BLOCK_ID:
2564 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002565 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002567
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002569 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2570 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002572
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002574 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 if (Stream.SkipBlock() ||
2576 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2577 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 }
2580 CommentsCursors.push_back(std::make_pair(C, &F));
2581 break;
2582 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002583
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 if (Stream.SkipBlock()) {
2586 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002588 }
2589 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 }
2591 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592
2593 case llvm::BitstreamEntry::Record:
2594 // The interesting case.
2595 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 }
2597
2598 // Read and process a record.
2599 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002600 StringRef Blob;
2601 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 default: // Default behavior: ignore.
2603 break;
2604
2605 case TYPE_OFFSET: {
2606 if (F.LocalNumTypes != 0) {
2607 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002610 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 F.LocalNumTypes = Record[0];
2612 unsigned LocalBaseTypeIndex = Record[1];
2613 F.BaseTypeIndex = getTotalNumTypes();
2614
2615 if (F.LocalNumTypes > 0) {
2616 // Introduce the global -> local mapping for types within this module.
2617 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2618
2619 // Introduce the local -> global mapping for types within this module.
2620 F.TypeRemap.insertOrReplace(
2621 std::make_pair(LocalBaseTypeIndex,
2622 F.BaseTypeIndex - LocalBaseTypeIndex));
2623
2624 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2625 }
2626 break;
2627 }
2628
2629 case DECL_OFFSET: {
2630 if (F.LocalNumDecls != 0) {
2631 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002632 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002634 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 F.LocalNumDecls = Record[0];
2636 unsigned LocalBaseDeclID = Record[1];
2637 F.BaseDeclID = getTotalNumDecls();
2638
2639 if (F.LocalNumDecls > 0) {
2640 // Introduce the global -> local mapping for declarations within this
2641 // module.
2642 GlobalDeclMap.insert(
2643 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2644
2645 // Introduce the local -> global mapping for declarations within this
2646 // module.
2647 F.DeclRemap.insertOrReplace(
2648 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2649
2650 // Introduce the global -> local mapping for declarations within this
2651 // module.
2652 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2653
2654 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2655 }
2656 break;
2657 }
2658
2659 case TU_UPDATE_LEXICAL: {
2660 DeclContext *TU = Context.getTranslationUnitDecl();
2661 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002662 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002664 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 TU->setHasExternalLexicalStorage(true);
2666 break;
2667 }
2668
2669 case UPDATE_VISIBLE: {
2670 unsigned Idx = 0;
2671 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2672 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002673 ASTDeclContextNameLookupTable::Create(
2674 (const unsigned char *)Blob.data() + Record[Idx++],
2675 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2676 (const unsigned char *)Blob.data(),
2677 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002678 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002679 auto *DC = cast<DeclContext>(D);
2680 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002681 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002682 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002683 delete LookupTable;
2684 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 } else
2686 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2687 break;
2688 }
2689
2690 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002691 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002693 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2694 (const unsigned char *)F.IdentifierTableData + Record[0],
2695 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2696 (const unsigned char *)F.IdentifierTableData,
2697 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002698
2699 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2700 }
2701 break;
2702
2703 case IDENTIFIER_OFFSET: {
2704 if (F.LocalNumIdentifiers != 0) {
2705 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002706 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002708 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 F.LocalNumIdentifiers = Record[0];
2710 unsigned LocalBaseIdentifierID = Record[1];
2711 F.BaseIdentifierID = getTotalNumIdentifiers();
2712
2713 if (F.LocalNumIdentifiers > 0) {
2714 // Introduce the global -> local mapping for identifiers within this
2715 // module.
2716 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2717 &F));
2718
2719 // Introduce the local -> global mapping for identifiers within this
2720 // module.
2721 F.IdentifierRemap.insertOrReplace(
2722 std::make_pair(LocalBaseIdentifierID,
2723 F.BaseIdentifierID - LocalBaseIdentifierID));
2724
2725 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2726 + F.LocalNumIdentifiers);
2727 }
2728 break;
2729 }
2730
Ben Langmuir332aafe2014-01-31 01:06:56 +00002731 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002733 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 break;
2735
2736 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002737 if (SpecialTypes.empty()) {
2738 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2739 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2740 break;
2741 }
2742
2743 if (SpecialTypes.size() != Record.size()) {
2744 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002745 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002746 }
2747
2748 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2749 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2750 if (!SpecialTypes[I])
2751 SpecialTypes[I] = ID;
2752 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2753 // merge step?
2754 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 break;
2756
2757 case STATISTICS:
2758 TotalNumStatements += Record[0];
2759 TotalNumMacros += Record[1];
2760 TotalLexicalDeclContexts += Record[2];
2761 TotalVisibleDeclContexts += Record[3];
2762 break;
2763
2764 case UNUSED_FILESCOPED_DECLS:
2765 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2766 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2767 break;
2768
2769 case DELEGATING_CTORS:
2770 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2771 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2772 break;
2773
2774 case WEAK_UNDECLARED_IDENTIFIERS:
2775 if (Record.size() % 4 != 0) {
2776 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002777 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 }
2779
2780 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2781 // files. This isn't the way to do it :)
2782 WeakUndeclaredIdentifiers.clear();
2783
2784 // Translate the weak, undeclared identifiers into global IDs.
2785 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2786 WeakUndeclaredIdentifiers.push_back(
2787 getGlobalIdentifierID(F, Record[I++]));
2788 WeakUndeclaredIdentifiers.push_back(
2789 getGlobalIdentifierID(F, Record[I++]));
2790 WeakUndeclaredIdentifiers.push_back(
2791 ReadSourceLocation(F, Record, I).getRawEncoding());
2792 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2793 }
2794 break;
2795
Richard Smith78165b52013-01-10 23:43:47 +00002796 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002798 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
2801 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002802 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 F.LocalNumSelectors = Record[0];
2804 unsigned LocalBaseSelectorID = Record[1];
2805 F.BaseSelectorID = getTotalNumSelectors();
2806
2807 if (F.LocalNumSelectors > 0) {
2808 // Introduce the global -> local mapping for selectors within this
2809 // module.
2810 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2811
2812 // Introduce the local -> global mapping for selectors within this
2813 // module.
2814 F.SelectorRemap.insertOrReplace(
2815 std::make_pair(LocalBaseSelectorID,
2816 F.BaseSelectorID - LocalBaseSelectorID));
2817
2818 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2819 }
2820 break;
2821 }
2822
2823 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002824 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 if (Record[0])
2826 F.SelectorLookupTable
2827 = ASTSelectorLookupTable::Create(
2828 F.SelectorLookupTableData + Record[0],
2829 F.SelectorLookupTableData,
2830 ASTSelectorLookupTrait(*this, F));
2831 TotalNumMethodPoolEntries += Record[1];
2832 break;
2833
2834 case REFERENCED_SELECTOR_POOL:
2835 if (!Record.empty()) {
2836 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2837 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2838 Record[Idx++]));
2839 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2840 getRawEncoding());
2841 }
2842 }
2843 break;
2844
2845 case PP_COUNTER_VALUE:
2846 if (!Record.empty() && Listener)
2847 Listener->ReadCounter(F, Record[0]);
2848 break;
2849
2850 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002851 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 F.NumFileSortedDecls = Record[0];
2853 break;
2854
2855 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 F.LocalNumSLocEntries = Record[0];
2858 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002859 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2861 SLocSpaceSize);
2862 // Make our entry in the range map. BaseID is negative and growing, so
2863 // we invert it. Because we invert it, though, we need the other end of
2864 // the range.
2865 unsigned RangeStart =
2866 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2867 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2868 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2869
2870 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2871 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2872 GlobalSLocOffsetMap.insert(
2873 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2874 - SLocSpaceSize,&F));
2875
2876 // Initialize the remapping table.
2877 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002878 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002880 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2882
2883 TotalNumSLocEntries += F.LocalNumSLocEntries;
2884 break;
2885 }
2886
2887 case MODULE_OFFSET_MAP: {
2888 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002889 const unsigned char *Data = (const unsigned char*)Blob.data();
2890 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002891
2892 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2893 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2894 F.SLocRemap.insert(std::make_pair(0U, 0));
2895 F.SLocRemap.insert(std::make_pair(2U, 1));
2896 }
2897
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 // Continuous range maps we may be updating in our module.
2899 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2900 ContinuousRangeMap<uint32_t, int, 2>::Builder
2901 IdentifierRemap(F.IdentifierRemap);
2902 ContinuousRangeMap<uint32_t, int, 2>::Builder
2903 MacroRemap(F.MacroRemap);
2904 ContinuousRangeMap<uint32_t, int, 2>::Builder
2905 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2906 ContinuousRangeMap<uint32_t, int, 2>::Builder
2907 SubmoduleRemap(F.SubmoduleRemap);
2908 ContinuousRangeMap<uint32_t, int, 2>::Builder
2909 SelectorRemap(F.SelectorRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2911 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2912
2913 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002914 using namespace llvm::support;
2915 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002916 StringRef Name = StringRef((const char*)Data, Len);
2917 Data += Len;
2918 ModuleFile *OM = ModuleMgr.lookup(Name);
2919 if (!OM) {
2920 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002921 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 }
2923
Justin Bogner57ba0b22014-03-28 22:03:24 +00002924 uint32_t SLocOffset =
2925 endian::readNext<uint32_t, little, unaligned>(Data);
2926 uint32_t IdentifierIDOffset =
2927 endian::readNext<uint32_t, little, unaligned>(Data);
2928 uint32_t MacroIDOffset =
2929 endian::readNext<uint32_t, little, unaligned>(Data);
2930 uint32_t PreprocessedEntityIDOffset =
2931 endian::readNext<uint32_t, little, unaligned>(Data);
2932 uint32_t SubmoduleIDOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t SelectorIDOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t DeclIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t TypeIndexOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2942 SLocRemap.insert(std::make_pair(SLocOffset,
2943 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2944 IdentifierRemap.insert(
2945 std::make_pair(IdentifierIDOffset,
2946 OM->BaseIdentifierID - IdentifierIDOffset));
2947 MacroRemap.insert(std::make_pair(MacroIDOffset,
2948 OM->BaseMacroID - MacroIDOffset));
2949 PreprocessedEntityRemap.insert(
2950 std::make_pair(PreprocessedEntityIDOffset,
2951 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2952 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2953 OM->BaseSubmoduleID - SubmoduleIDOffset));
2954 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2955 OM->BaseSelectorID - SelectorIDOffset));
2956 DeclRemap.insert(std::make_pair(DeclIDOffset,
2957 OM->BaseDeclID - DeclIDOffset));
2958
2959 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2960 OM->BaseTypeIndex - TypeIndexOffset));
2961
2962 // Global -> local mappings.
2963 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2964 }
2965 break;
2966 }
2967
2968 case SOURCE_MANAGER_LINE_TABLE:
2969 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002970 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 break;
2972
2973 case SOURCE_LOCATION_PRELOADS: {
2974 // Need to transform from the local view (1-based IDs) to the global view,
2975 // which is based off F.SLocEntryBaseID.
2976 if (!F.PreloadSLocEntries.empty()) {
2977 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002978 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 }
2980
2981 F.PreloadSLocEntries.swap(Record);
2982 break;
2983 }
2984
2985 case EXT_VECTOR_DECLS:
2986 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2987 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2988 break;
2989
2990 case VTABLE_USES:
2991 if (Record.size() % 3 != 0) {
2992 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002993 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 }
2995
2996 // Later tables overwrite earlier ones.
2997 // FIXME: Modules will have some trouble with this. This is clearly not
2998 // the right way to do this.
2999 VTableUses.clear();
3000
3001 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3002 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3003 VTableUses.push_back(
3004 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3005 VTableUses.push_back(Record[Idx++]);
3006 }
3007 break;
3008
3009 case DYNAMIC_CLASSES:
3010 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3011 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3012 break;
3013
3014 case PENDING_IMPLICIT_INSTANTIATIONS:
3015 if (PendingInstantiations.size() % 2 != 0) {
3016 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003017 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 }
3019
3020 if (Record.size() % 2 != 0) {
3021 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 }
3024
3025 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3026 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3027 PendingInstantiations.push_back(
3028 ReadSourceLocation(F, Record, I).getRawEncoding());
3029 }
3030 break;
3031
3032 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003033 if (Record.size() != 2) {
3034 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003035 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3038 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3039 break;
3040
3041 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003042 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3043 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3044 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003045
3046 unsigned LocalBasePreprocessedEntityID = Record[0];
3047
3048 unsigned StartingID;
3049 if (!PP.getPreprocessingRecord())
3050 PP.createPreprocessingRecord();
3051 if (!PP.getPreprocessingRecord()->getExternalSource())
3052 PP.getPreprocessingRecord()->SetExternalSource(*this);
3053 StartingID
3054 = PP.getPreprocessingRecord()
3055 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3056 F.BasePreprocessedEntityID = StartingID;
3057
3058 if (F.NumPreprocessedEntities > 0) {
3059 // Introduce the global -> local mapping for preprocessed entities in
3060 // this module.
3061 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3062
3063 // Introduce the local -> global mapping for preprocessed entities in
3064 // this module.
3065 F.PreprocessedEntityRemap.insertOrReplace(
3066 std::make_pair(LocalBasePreprocessedEntityID,
3067 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3068 }
3069
3070 break;
3071 }
3072
3073 case DECL_UPDATE_OFFSETS: {
3074 if (Record.size() % 2 != 0) {
3075 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003076 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003078 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3079 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3080 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3081
3082 // If we've already loaded the decl, perform the updates when we finish
3083 // loading this block.
3084 if (Decl *D = GetExistingDecl(ID))
3085 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 break;
3088 }
3089
3090 case DECL_REPLACEMENTS: {
3091 if (Record.size() % 3 != 0) {
3092 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003093 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 }
3095 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3096 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3097 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3098 break;
3099 }
3100
3101 case OBJC_CATEGORIES_MAP: {
3102 if (F.LocalNumObjCCategoriesInMap != 0) {
3103 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003104 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 }
3106
3107 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003108 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 break;
3110 }
3111
3112 case OBJC_CATEGORIES:
3113 F.ObjCCategories.swap(Record);
3114 break;
3115
3116 case CXX_BASE_SPECIFIER_OFFSETS: {
3117 if (F.LocalNumCXXBaseSpecifiers != 0) {
3118 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003119 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 }
3121
3122 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003123 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3125 break;
3126 }
3127
3128 case DIAG_PRAGMA_MAPPINGS:
3129 if (F.PragmaDiagMappings.empty())
3130 F.PragmaDiagMappings.swap(Record);
3131 else
3132 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3133 Record.begin(), Record.end());
3134 break;
3135
3136 case CUDA_SPECIAL_DECL_REFS:
3137 // Later tables overwrite earlier ones.
3138 // FIXME: Modules will have trouble with this.
3139 CUDASpecialDeclRefs.clear();
3140 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3141 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3142 break;
3143
3144 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003145 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 if (Record[0]) {
3148 F.HeaderFileInfoTable
3149 = HeaderFileInfoLookupTable::Create(
3150 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3151 (const unsigned char *)F.HeaderFileInfoTableData,
3152 HeaderFileInfoTrait(*this, F,
3153 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003154 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003155
3156 PP.getHeaderSearchInfo().SetExternalSource(this);
3157 if (!PP.getHeaderSearchInfo().getExternalLookup())
3158 PP.getHeaderSearchInfo().SetExternalLookup(this);
3159 }
3160 break;
3161 }
3162
3163 case FP_PRAGMA_OPTIONS:
3164 // Later tables overwrite earlier ones.
3165 FPPragmaOptions.swap(Record);
3166 break;
3167
3168 case OPENCL_EXTENSIONS:
3169 // Later tables overwrite earlier ones.
3170 OpenCLExtensions.swap(Record);
3171 break;
3172
3173 case TENTATIVE_DEFINITIONS:
3174 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3175 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3176 break;
3177
3178 case KNOWN_NAMESPACES:
3179 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3180 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3181 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003182
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003183 case UNDEFINED_BUT_USED:
3184 if (UndefinedButUsed.size() % 2 != 0) {
3185 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003186 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003187 }
3188
3189 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003190 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003191 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003192 }
3193 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003194 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3195 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003196 ReadSourceLocation(F, Record, I).getRawEncoding());
3197 }
3198 break;
3199
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 case IMPORTED_MODULES: {
3201 if (F.Kind != MK_Module) {
3202 // If we aren't loading a module (which has its own exports), make
3203 // all of the imported modules visible.
3204 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003205 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3206 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3207 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3208 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003209 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 }
3211 }
3212 break;
3213 }
3214
3215 case LOCAL_REDECLARATIONS: {
3216 F.RedeclarationChains.swap(Record);
3217 break;
3218 }
3219
3220 case LOCAL_REDECLARATIONS_MAP: {
3221 if (F.LocalNumRedeclarationsInMap != 0) {
3222 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003223 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 }
3225
3226 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003227 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 break;
3229 }
3230
3231 case MERGED_DECLARATIONS: {
3232 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3233 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3234 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3235 for (unsigned N = Record[Idx++]; N > 0; --N)
3236 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3237 }
3238 break;
3239 }
3240
3241 case MACRO_OFFSET: {
3242 if (F.LocalNumMacros != 0) {
3243 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003244 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003246 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 F.LocalNumMacros = Record[0];
3248 unsigned LocalBaseMacroID = Record[1];
3249 F.BaseMacroID = getTotalNumMacros();
3250
3251 if (F.LocalNumMacros > 0) {
3252 // Introduce the global -> local mapping for macros within this module.
3253 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3254
3255 // Introduce the local -> global mapping for macros within this module.
3256 F.MacroRemap.insertOrReplace(
3257 std::make_pair(LocalBaseMacroID,
3258 F.BaseMacroID - LocalBaseMacroID));
3259
3260 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3261 }
3262 break;
3263 }
3264
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003265 case MACRO_TABLE: {
3266 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 break;
3268 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003269
3270 case LATE_PARSED_TEMPLATE: {
3271 LateParsedTemplates.append(Record.begin(), Record.end());
3272 break;
3273 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 }
3275 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003276}
3277
Douglas Gregorc1489562013-02-12 23:36:21 +00003278/// \brief Move the given method to the back of the global list of methods.
3279static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3280 // Find the entry for this selector in the method pool.
3281 Sema::GlobalMethodPool::iterator Known
3282 = S.MethodPool.find(Method->getSelector());
3283 if (Known == S.MethodPool.end())
3284 return;
3285
3286 // Retrieve the appropriate method list.
3287 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3288 : Known->second.second;
3289 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003290 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003291 if (!Found) {
3292 if (List->Method == Method) {
3293 Found = true;
3294 } else {
3295 // Keep searching.
3296 continue;
3297 }
3298 }
3299
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003300 if (List->getNext())
3301 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003302 else
3303 List->Method = Method;
3304 }
3305}
3306
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003307void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003308 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3309 Decl *D = Names.HiddenDecls[I];
3310 bool wasHidden = D->Hidden;
3311 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003312
Richard Smith49f906a2014-03-01 00:08:04 +00003313 if (wasHidden && SemaObj) {
3314 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3315 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 }
3318 }
Richard Smith49f906a2014-03-01 00:08:04 +00003319
3320 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3321 E = Names.HiddenMacros.end();
3322 I != E; ++I)
3323 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003324}
3325
Richard Smith49f906a2014-03-01 00:08:04 +00003326void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003327 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003328 SourceLocation ImportLoc,
3329 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003331 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003332 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003334 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003335
3336 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003337 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 // there is nothing more to do.
3339 continue;
3340 }
Richard Smith49f906a2014-03-01 00:08:04 +00003341
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 if (!Mod->isAvailable()) {
3343 // Modules that aren't available cannot be made visible.
3344 continue;
3345 }
3346
3347 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003348 if (NameVisibility >= Module::MacrosVisible &&
3349 Mod->NameVisibility < Module::MacrosVisible)
3350 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 // If we've already deserialized any names from this module,
3354 // mark them as visible.
3355 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3356 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003357 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 HiddenNamesMap.erase(Hidden);
3359 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003360
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003362 SmallVector<Module *, 16> Exports;
3363 Mod->getExportedModules(Exports);
3364 for (SmallVectorImpl<Module *>::iterator
3365 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3366 Module *Exported = *I;
3367 if (Visited.insert(Exported))
3368 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003370
3371 // Detect any conflicts.
3372 if (Complain) {
3373 assert(ImportLoc.isValid() && "Missing import location");
3374 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3375 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3376 Diag(ImportLoc, diag::warn_module_conflict)
3377 << Mod->getFullModuleName()
3378 << Mod->Conflicts[I].Other->getFullModuleName()
3379 << Mod->Conflicts[I].Message;
3380 // FIXME: Need note where the other module was imported.
3381 }
3382 }
3383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 }
3385}
3386
Douglas Gregore060e572013-01-25 01:03:03 +00003387bool ASTReader::loadGlobalIndex() {
3388 if (GlobalIndex)
3389 return false;
3390
3391 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3392 !Context.getLangOpts().Modules)
3393 return true;
3394
3395 // Try to load the global index.
3396 TriedLoadingGlobalIndex = true;
3397 StringRef ModuleCachePath
3398 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3399 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003400 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003401 if (!Result.first)
3402 return true;
3403
3404 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003405 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003406 return false;
3407}
3408
3409bool ASTReader::isGlobalIndexUnavailable() const {
3410 return Context.getLangOpts().Modules && UseGlobalIndex &&
3411 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3412}
3413
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003414static void updateModuleTimestamp(ModuleFile &MF) {
3415 // Overwrite the timestamp file contents so that file's mtime changes.
3416 std::string TimestampFilename = MF.getTimestampFilename();
3417 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003418 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003419 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003420 if (!ErrorInfo.empty())
3421 return;
3422 OS << "Timestamp file\n";
3423}
3424
Guy Benyei11169dd2012-12-18 14:30:41 +00003425ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3426 ModuleKind Type,
3427 SourceLocation ImportLoc,
3428 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003429 llvm::SaveAndRestore<SourceLocation>
3430 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3431
Richard Smithd1c46742014-04-30 02:24:17 +00003432 // Defer any pending actions until we get to the end of reading the AST file.
3433 Deserializing AnASTFile(this);
3434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435 // Bump the generation number.
3436 unsigned PreviousGeneration = CurrentGeneration++;
3437
3438 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003439 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3441 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003442 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 ClientLoadCapabilities)) {
3444 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003445 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 case OutOfDate:
3447 case VersionMismatch:
3448 case ConfigurationMismatch:
3449 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003450 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3451 Context.getLangOpts().Modules
3452 ? &PP.getHeaderSearchInfo().getModuleMap()
3453 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003454
3455 // If we find that any modules are unusable, the global index is going
3456 // to be out-of-date. Just remove it.
3457 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003458 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 return ReadResult;
3460
3461 case Success:
3462 break;
3463 }
3464
3465 // Here comes stuff that we only do once the entire chain is loaded.
3466
3467 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003468 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3469 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003470 M != MEnd; ++M) {
3471 ModuleFile &F = *M->Mod;
3472
3473 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003474 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3475 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003476
3477 // Once read, set the ModuleFile bit base offset and update the size in
3478 // bits of all files we've seen.
3479 F.GlobalBitOffset = TotalModulesSizeInBits;
3480 TotalModulesSizeInBits += F.SizeInBits;
3481 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3482
3483 // Preload SLocEntries.
3484 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3485 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3486 // Load it through the SourceManager and don't call ReadSLocEntry()
3487 // directly because the entry may have already been loaded in which case
3488 // calling ReadSLocEntry() directly would trigger an assertion in
3489 // SourceManager.
3490 SourceMgr.getLoadedSLocEntryByID(Index);
3491 }
3492 }
3493
Douglas Gregor603cd862013-03-22 18:50:14 +00003494 // Setup the import locations and notify the module manager that we've
3495 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003496 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3497 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 M != MEnd; ++M) {
3499 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003500
3501 ModuleMgr.moduleFileAccepted(&F);
3502
3503 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003504 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 if (!M->ImportedBy)
3506 F.ImportLoc = M->ImportLoc;
3507 else
3508 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3509 M->ImportLoc.getRawEncoding());
3510 }
3511
3512 // Mark all of the identifiers in the identifier table as being out of date,
3513 // so that various accessors know to check the loaded modules when the
3514 // identifier is used.
3515 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3516 IdEnd = PP.getIdentifierTable().end();
3517 Id != IdEnd; ++Id)
3518 Id->second->setOutOfDate(true);
3519
3520 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003521 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3522 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3524 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003525
3526 switch (Unresolved.Kind) {
3527 case UnresolvedModuleRef::Conflict:
3528 if (ResolvedMod) {
3529 Module::Conflict Conflict;
3530 Conflict.Other = ResolvedMod;
3531 Conflict.Message = Unresolved.String.str();
3532 Unresolved.Mod->Conflicts.push_back(Conflict);
3533 }
3534 continue;
3535
3536 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 if (ResolvedMod)
3538 Unresolved.Mod->Imports.push_back(ResolvedMod);
3539 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003540
Douglas Gregorfb912652013-03-20 21:10:35 +00003541 case UnresolvedModuleRef::Export:
3542 if (ResolvedMod || Unresolved.IsWildcard)
3543 Unresolved.Mod->Exports.push_back(
3544 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3545 continue;
3546 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003548 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003549
3550 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3551 // Might be unnecessary as use declarations are only used to build the
3552 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003553
3554 InitializeContext();
3555
Richard Smith3d8e97e2013-10-18 06:54:39 +00003556 if (SemaObj)
3557 UpdateSema();
3558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 if (DeserializationListener)
3560 DeserializationListener->ReaderInitialized(this);
3561
3562 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3563 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3564 PrimaryModule.OriginalSourceFileID
3565 = FileID::get(PrimaryModule.SLocEntryBaseID
3566 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3567
3568 // If this AST file is a precompiled preamble, then set the
3569 // preamble file ID of the source manager to the file source file
3570 // from which the preamble was built.
3571 if (Type == MK_Preamble) {
3572 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3573 } else if (Type == MK_MainFile) {
3574 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3575 }
3576 }
3577
3578 // For any Objective-C class definitions we have already loaded, make sure
3579 // that we load any additional categories.
3580 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3581 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3582 ObjCClassesLoaded[I],
3583 PreviousGeneration);
3584 }
Douglas Gregore060e572013-01-25 01:03:03 +00003585
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003586 if (PP.getHeaderSearchInfo()
3587 .getHeaderSearchOpts()
3588 .ModulesValidateOncePerBuildSession) {
3589 // Now we are certain that the module and all modules it depends on are
3590 // up to date. Create or update timestamp files for modules that are
3591 // located in the module cache (not for PCH files that could be anywhere
3592 // in the filesystem).
3593 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3594 ImportedModule &M = Loaded[I];
3595 if (M.Mod->Kind == MK_Module) {
3596 updateModuleTimestamp(*M.Mod);
3597 }
3598 }
3599 }
3600
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 return Success;
3602}
3603
3604ASTReader::ASTReadResult
3605ASTReader::ReadASTCore(StringRef FileName,
3606 ModuleKind Type,
3607 SourceLocation ImportLoc,
3608 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003609 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003610 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 unsigned ClientLoadCapabilities) {
3612 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003614 ModuleManager::AddModuleResult AddResult
3615 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3616 CurrentGeneration, ExpectedSize, ExpectedModTime,
3617 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003618
Douglas Gregor7029ce12013-03-19 00:28:20 +00003619 switch (AddResult) {
3620 case ModuleManager::AlreadyLoaded:
3621 return Success;
3622
3623 case ModuleManager::NewlyLoaded:
3624 // Load module file below.
3625 break;
3626
3627 case ModuleManager::Missing:
3628 // The module file was missing; if the client handle handle, that, return
3629 // it.
3630 if (ClientLoadCapabilities & ARR_Missing)
3631 return Missing;
3632
3633 // Otherwise, return an error.
3634 {
3635 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3636 + ErrorStr;
3637 Error(Msg);
3638 }
3639 return Failure;
3640
3641 case ModuleManager::OutOfDate:
3642 // We couldn't load the module file because it is out-of-date. If the
3643 // client can handle out-of-date, return it.
3644 if (ClientLoadCapabilities & ARR_OutOfDate)
3645 return OutOfDate;
3646
3647 // Otherwise, return an error.
3648 {
3649 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3650 + ErrorStr;
3651 Error(Msg);
3652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003653 return Failure;
3654 }
3655
Douglas Gregor7029ce12013-03-19 00:28:20 +00003656 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003657
3658 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3659 // module?
3660 if (FileName != "-") {
3661 CurrentDir = llvm::sys::path::parent_path(FileName);
3662 if (CurrentDir.empty()) CurrentDir = ".";
3663 }
3664
3665 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003666 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 Stream.init(F.StreamFile);
3668 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3669
3670 // Sniff for the signature.
3671 if (Stream.Read(8) != 'C' ||
3672 Stream.Read(8) != 'P' ||
3673 Stream.Read(8) != 'C' ||
3674 Stream.Read(8) != 'H') {
3675 Diag(diag::err_not_a_pch_file) << FileName;
3676 return Failure;
3677 }
3678
3679 // This is used for compatibility with older PCH formats.
3680 bool HaveReadControlBlock = false;
3681
Chris Lattnerefa77172013-01-20 00:00:22 +00003682 while (1) {
3683 llvm::BitstreamEntry Entry = Stream.advance();
3684
3685 switch (Entry.Kind) {
3686 case llvm::BitstreamEntry::Error:
3687 case llvm::BitstreamEntry::EndBlock:
3688 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 Error("invalid record at top-level of AST file");
3690 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003691
3692 case llvm::BitstreamEntry::SubBlock:
3693 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 }
3695
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003697 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3699 if (Stream.ReadBlockInfoBlock()) {
3700 Error("malformed BlockInfoBlock in AST file");
3701 return Failure;
3702 }
3703 break;
3704 case CONTROL_BLOCK_ID:
3705 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003706 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 case Success:
3708 break;
3709
3710 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003711 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 case OutOfDate: return OutOfDate;
3713 case VersionMismatch: return VersionMismatch;
3714 case ConfigurationMismatch: return ConfigurationMismatch;
3715 case HadErrors: return HadErrors;
3716 }
3717 break;
3718 case AST_BLOCK_ID:
3719 if (!HaveReadControlBlock) {
3720 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003721 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 return VersionMismatch;
3723 }
3724
3725 // Record that we've loaded this module.
3726 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3727 return Success;
3728
3729 default:
3730 if (Stream.SkipBlock()) {
3731 Error("malformed block record in AST file");
3732 return Failure;
3733 }
3734 break;
3735 }
3736 }
3737
3738 return Success;
3739}
3740
3741void ASTReader::InitializeContext() {
3742 // If there's a listener, notify them that we "read" the translation unit.
3743 if (DeserializationListener)
3744 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3745 Context.getTranslationUnitDecl());
3746
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 // FIXME: Find a better way to deal with collisions between these
3748 // built-in types. Right now, we just ignore the problem.
3749
3750 // Load the special types.
3751 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3752 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3753 if (!Context.CFConstantStringTypeDecl)
3754 Context.setCFConstantStringType(GetType(String));
3755 }
3756
3757 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3758 QualType FileType = GetType(File);
3759 if (FileType.isNull()) {
3760 Error("FILE type is NULL");
3761 return;
3762 }
3763
3764 if (!Context.FILEDecl) {
3765 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3766 Context.setFILEDecl(Typedef->getDecl());
3767 else {
3768 const TagType *Tag = FileType->getAs<TagType>();
3769 if (!Tag) {
3770 Error("Invalid FILE type in AST file");
3771 return;
3772 }
3773 Context.setFILEDecl(Tag->getDecl());
3774 }
3775 }
3776 }
3777
3778 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3779 QualType Jmp_bufType = GetType(Jmp_buf);
3780 if (Jmp_bufType.isNull()) {
3781 Error("jmp_buf type is NULL");
3782 return;
3783 }
3784
3785 if (!Context.jmp_bufDecl) {
3786 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3787 Context.setjmp_bufDecl(Typedef->getDecl());
3788 else {
3789 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3790 if (!Tag) {
3791 Error("Invalid jmp_buf type in AST file");
3792 return;
3793 }
3794 Context.setjmp_bufDecl(Tag->getDecl());
3795 }
3796 }
3797 }
3798
3799 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3800 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3801 if (Sigjmp_bufType.isNull()) {
3802 Error("sigjmp_buf type is NULL");
3803 return;
3804 }
3805
3806 if (!Context.sigjmp_bufDecl) {
3807 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3808 Context.setsigjmp_bufDecl(Typedef->getDecl());
3809 else {
3810 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3811 assert(Tag && "Invalid sigjmp_buf type in AST file");
3812 Context.setsigjmp_bufDecl(Tag->getDecl());
3813 }
3814 }
3815 }
3816
3817 if (unsigned ObjCIdRedef
3818 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3819 if (Context.ObjCIdRedefinitionType.isNull())
3820 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3821 }
3822
3823 if (unsigned ObjCClassRedef
3824 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3825 if (Context.ObjCClassRedefinitionType.isNull())
3826 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3827 }
3828
3829 if (unsigned ObjCSelRedef
3830 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3831 if (Context.ObjCSelRedefinitionType.isNull())
3832 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3833 }
3834
3835 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3836 QualType Ucontext_tType = GetType(Ucontext_t);
3837 if (Ucontext_tType.isNull()) {
3838 Error("ucontext_t type is NULL");
3839 return;
3840 }
3841
3842 if (!Context.ucontext_tDecl) {
3843 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3844 Context.setucontext_tDecl(Typedef->getDecl());
3845 else {
3846 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3847 assert(Tag && "Invalid ucontext_t type in AST file");
3848 Context.setucontext_tDecl(Tag->getDecl());
3849 }
3850 }
3851 }
3852 }
3853
3854 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3855
3856 // If there were any CUDA special declarations, deserialize them.
3857 if (!CUDASpecialDeclRefs.empty()) {
3858 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3859 Context.setcudaConfigureCallDecl(
3860 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3861 }
Richard Smith56be7542014-03-21 00:33:59 +00003862
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003864 // FIXME: This does not make macro-only imports visible again. It also doesn't
3865 // make #includes mapped to module imports visible.
3866 for (auto &Import : ImportedModules) {
3867 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003868 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003869 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003870 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003871 }
3872 ImportedModules.clear();
3873}
3874
3875void ASTReader::finalizeForWriting() {
3876 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3877 HiddenEnd = HiddenNamesMap.end();
3878 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003879 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 }
3881 HiddenNamesMap.clear();
3882}
3883
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003884/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3885/// cursor into the start of the given block ID, returning false on success and
3886/// true on failure.
3887static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003888 while (1) {
3889 llvm::BitstreamEntry Entry = Cursor.advance();
3890 switch (Entry.Kind) {
3891 case llvm::BitstreamEntry::Error:
3892 case llvm::BitstreamEntry::EndBlock:
3893 return true;
3894
3895 case llvm::BitstreamEntry::Record:
3896 // Ignore top-level records.
3897 Cursor.skipRecord(Entry.ID);
3898 break;
3899
3900 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003901 if (Entry.ID == BlockID) {
3902 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003903 return true;
3904 // Found it!
3905 return false;
3906 }
3907
3908 if (Cursor.SkipBlock())
3909 return true;
3910 }
3911 }
3912}
3913
Guy Benyei11169dd2012-12-18 14:30:41 +00003914/// \brief Retrieve the name of the original source file name
3915/// directly from the AST file, without actually loading the AST
3916/// file.
3917std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3918 FileManager &FileMgr,
3919 DiagnosticsEngine &Diags) {
3920 // Open the AST file.
3921 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003922 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3924 if (!Buffer) {
3925 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3926 return std::string();
3927 }
3928
3929 // Initialize the stream
3930 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003931 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3933 (const unsigned char *)Buffer->getBufferEnd());
3934 Stream.init(StreamFile);
3935
3936 // Sniff for the signature.
3937 if (Stream.Read(8) != 'C' ||
3938 Stream.Read(8) != 'P' ||
3939 Stream.Read(8) != 'C' ||
3940 Stream.Read(8) != 'H') {
3941 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3942 return std::string();
3943 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003944
Chris Lattnere7b154b2013-01-19 21:39:22 +00003945 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003946 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003947 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3948 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003949 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003950
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003951 // Scan for ORIGINAL_FILE inside the control block.
3952 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003953 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003954 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003955 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3956 return std::string();
3957
3958 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3959 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3960 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003962
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003964 StringRef Blob;
3965 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3966 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003968}
3969
3970namespace {
3971 class SimplePCHValidator : public ASTReaderListener {
3972 const LangOptions &ExistingLangOpts;
3973 const TargetOptions &ExistingTargetOpts;
3974 const PreprocessorOptions &ExistingPPOpts;
3975 FileManager &FileMgr;
3976
3977 public:
3978 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3979 const TargetOptions &ExistingTargetOpts,
3980 const PreprocessorOptions &ExistingPPOpts,
3981 FileManager &FileMgr)
3982 : ExistingLangOpts(ExistingLangOpts),
3983 ExistingTargetOpts(ExistingTargetOpts),
3984 ExistingPPOpts(ExistingPPOpts),
3985 FileMgr(FileMgr)
3986 {
3987 }
3988
Craig Topper3e89dfe2014-03-13 02:13:41 +00003989 bool ReadLanguageOptions(const LangOptions &LangOpts,
3990 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3992 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003993 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3994 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3996 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003997 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3998 bool Complain,
3999 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004001 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 }
4003 };
4004}
4005
4006bool ASTReader::readASTFileControlBlock(StringRef Filename,
4007 FileManager &FileMgr,
4008 ASTReaderListener &Listener) {
4009 // Open the AST file.
4010 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004011 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4013 if (!Buffer) {
4014 return true;
4015 }
4016
4017 // Initialize the stream
4018 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004019 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4021 (const unsigned char *)Buffer->getBufferEnd());
4022 Stream.init(StreamFile);
4023
4024 // Sniff for the signature.
4025 if (Stream.Read(8) != 'C' ||
4026 Stream.Read(8) != 'P' ||
4027 Stream.Read(8) != 'C' ||
4028 Stream.Read(8) != 'H') {
4029 return true;
4030 }
4031
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004032 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004033 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004034 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004035
4036 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004037 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004038 BitstreamCursor InputFilesCursor;
4039 if (NeedsInputFiles) {
4040 InputFilesCursor = Stream;
4041 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4042 return true;
4043
4044 // Read the abbreviations
4045 while (true) {
4046 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4047 unsigned Code = InputFilesCursor.ReadCode();
4048
4049 // We expect all abbrevs to be at the start of the block.
4050 if (Code != llvm::bitc::DEFINE_ABBREV) {
4051 InputFilesCursor.JumpToBit(Offset);
4052 break;
4053 }
4054 InputFilesCursor.ReadAbbrevRecord();
4055 }
4056 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057
4058 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004060 while (1) {
4061 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4062 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4063 return false;
4064
4065 if (Entry.Kind != llvm::BitstreamEntry::Record)
4066 return true;
4067
Guy Benyei11169dd2012-12-18 14:30:41 +00004068 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004069 StringRef Blob;
4070 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004071 switch ((ControlRecordTypes)RecCode) {
4072 case METADATA: {
4073 if (Record[0] != VERSION_MAJOR)
4074 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004076 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004078
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 break;
4080 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004081 case MODULE_NAME:
4082 Listener.ReadModuleName(Blob);
4083 break;
4084 case MODULE_MAP_FILE:
4085 Listener.ReadModuleMapFile(Blob);
4086 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 case LANGUAGE_OPTIONS:
4088 if (ParseLanguageOptions(Record, false, Listener))
4089 return true;
4090 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004091
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004092 case TARGET_OPTIONS:
4093 if (ParseTargetOptions(Record, false, Listener))
4094 return true;
4095 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004096
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097 case DIAGNOSTIC_OPTIONS:
4098 if (ParseDiagnosticOptions(Record, false, Listener))
4099 return true;
4100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004102 case FILE_SYSTEM_OPTIONS:
4103 if (ParseFileSystemOptions(Record, false, Listener))
4104 return true;
4105 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004106
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107 case HEADER_SEARCH_OPTIONS:
4108 if (ParseHeaderSearchOptions(Record, false, Listener))
4109 return true;
4110 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004112 case PREPROCESSOR_OPTIONS: {
4113 std::string IgnoredSuggestedPredefines;
4114 if (ParsePreprocessorOptions(Record, false, Listener,
4115 IgnoredSuggestedPredefines))
4116 return true;
4117 break;
4118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004119
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004120 case INPUT_FILE_OFFSETS: {
4121 if (!NeedsInputFiles)
4122 break;
4123
4124 unsigned NumInputFiles = Record[0];
4125 unsigned NumUserFiles = Record[1];
4126 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4127 for (unsigned I = 0; I != NumInputFiles; ++I) {
4128 // Go find this input file.
4129 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004130
4131 if (isSystemFile && !NeedsSystemInputFiles)
4132 break; // the rest are system input files
4133
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004134 BitstreamCursor &Cursor = InputFilesCursor;
4135 SavedStreamPosition SavedPosition(Cursor);
4136 Cursor.JumpToBit(InputFileOffs[I]);
4137
4138 unsigned Code = Cursor.ReadCode();
4139 RecordData Record;
4140 StringRef Blob;
4141 bool shouldContinue = false;
4142 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4143 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004144 bool Overridden = static_cast<bool>(Record[3]);
4145 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004146 break;
4147 }
4148 if (!shouldContinue)
4149 break;
4150 }
4151 break;
4152 }
4153
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004154 default:
4155 // No other validation to perform.
4156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
4158 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004159}
4160
4161
4162bool ASTReader::isAcceptableASTFile(StringRef Filename,
4163 FileManager &FileMgr,
4164 const LangOptions &LangOpts,
4165 const TargetOptions &TargetOpts,
4166 const PreprocessorOptions &PPOpts) {
4167 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4168 return !readASTFileControlBlock(Filename, FileMgr, validator);
4169}
4170
Ben Langmuir2c9af442014-04-10 17:57:43 +00004171ASTReader::ASTReadResult
4172ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 // Enter the submodule block.
4174 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4175 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004176 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 }
4178
4179 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4180 bool First = true;
4181 Module *CurrentModule = 0;
4182 RecordData Record;
4183 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004184 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4185
4186 switch (Entry.Kind) {
4187 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4188 case llvm::BitstreamEntry::Error:
4189 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004190 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004191 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004192 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004193 case llvm::BitstreamEntry::Record:
4194 // The interesting case.
4195 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004197
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004199 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004201 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 default: // Default behavior: ignore.
4203 break;
4204
4205 case SUBMODULE_DEFINITION: {
4206 if (First) {
4207 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004208 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 }
4210
Douglas Gregor8d932422013-03-20 03:59:18 +00004211 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004213 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 }
4215
Chris Lattner0e6c9402013-01-20 02:38:54 +00004216 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004217 unsigned Idx = 0;
4218 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4219 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4220 bool IsFramework = Record[Idx++];
4221 bool IsExplicit = Record[Idx++];
4222 bool IsSystem = Record[Idx++];
4223 bool IsExternC = Record[Idx++];
4224 bool InferSubmodules = Record[Idx++];
4225 bool InferExplicitSubmodules = Record[Idx++];
4226 bool InferExportWildcard = Record[Idx++];
4227 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004228
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004229 Module *ParentModule = nullptr;
4230 const FileEntry *ModuleMap = nullptr;
4231 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004233 ModuleMap = ParentModule->ModuleMap;
4234 }
4235
4236 if (!F.ModuleMapPath.empty())
4237 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4238
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 // Retrieve this (sub)module from the module map, creating it if
4240 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004241 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 IsFramework,
4243 IsExplicit).first;
4244 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4245 if (GlobalIndex >= SubmodulesLoaded.size() ||
4246 SubmodulesLoaded[GlobalIndex]) {
4247 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004248 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004250
Douglas Gregor7029ce12013-03-19 00:28:20 +00004251 if (!ParentModule) {
4252 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4253 if (CurFile != F.File) {
4254 if (!Diags.isDiagnosticInFlight()) {
4255 Diag(diag::err_module_file_conflict)
4256 << CurrentModule->getTopLevelModuleName()
4257 << CurFile->getName()
4258 << F.File->getName();
4259 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004260 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004261 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004262 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004263
4264 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004265 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 CurrentModule->IsFromModuleFile = true;
4268 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004269 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 CurrentModule->InferSubmodules = InferSubmodules;
4271 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4272 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004273 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 if (DeserializationListener)
4275 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4276
4277 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004278
Douglas Gregorfb912652013-03-20 21:10:35 +00004279 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004280 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004281 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004282 CurrentModule->UnresolvedConflicts.clear();
4283 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 break;
4285 }
4286
4287 case SUBMODULE_UMBRELLA_HEADER: {
4288 if (First) {
4289 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004290 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 }
4292
4293 if (!CurrentModule)
4294 break;
4295
Chris Lattner0e6c9402013-01-20 02:38:54 +00004296 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 if (!CurrentModule->getUmbrellaHeader())
4298 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4299 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004300 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4301 Error("mismatched umbrella headers in submodule");
4302 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 }
4304 }
4305 break;
4306 }
4307
4308 case SUBMODULE_HEADER: {
4309 if (First) {
4310 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004311 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 }
4313
4314 if (!CurrentModule)
4315 break;
4316
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004317 // We lazily associate headers with their modules via the HeaderInfoTable.
4318 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4319 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 break;
4321 }
4322
4323 case SUBMODULE_EXCLUDED_HEADER: {
4324 if (First) {
4325 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004326 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004327 }
4328
4329 if (!CurrentModule)
4330 break;
4331
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004332 // We lazily associate headers with their modules via the HeaderInfoTable.
4333 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4334 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 break;
4336 }
4337
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004338 case SUBMODULE_PRIVATE_HEADER: {
4339 if (First) {
4340 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004341 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004342 }
4343
4344 if (!CurrentModule)
4345 break;
4346
4347 // We lazily associate headers with their modules via the HeaderInfoTable.
4348 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4349 // of complete filenames or remove it entirely.
4350 break;
4351 }
4352
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 case SUBMODULE_TOPHEADER: {
4354 if (First) {
4355 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004356 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 }
4358
4359 if (!CurrentModule)
4360 break;
4361
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004362 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 break;
4364 }
4365
4366 case SUBMODULE_UMBRELLA_DIR: {
4367 if (First) {
4368 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004369 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 }
4371
4372 if (!CurrentModule)
4373 break;
4374
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004376 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (!CurrentModule->getUmbrellaDir())
4378 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4379 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004380 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4381 Error("mismatched umbrella directories in submodule");
4382 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 }
4384 }
4385 break;
4386 }
4387
4388 case SUBMODULE_METADATA: {
4389 if (!First) {
4390 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004391 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 }
4393 First = false;
4394
4395 F.BaseSubmoduleID = getTotalNumSubmodules();
4396 F.LocalNumSubmodules = Record[0];
4397 unsigned LocalBaseSubmoduleID = Record[1];
4398 if (F.LocalNumSubmodules > 0) {
4399 // Introduce the global -> local mapping for submodules within this
4400 // module.
4401 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4402
4403 // Introduce the local -> global mapping for submodules within this
4404 // module.
4405 F.SubmoduleRemap.insertOrReplace(
4406 std::make_pair(LocalBaseSubmoduleID,
4407 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4408
4409 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4410 }
4411 break;
4412 }
4413
4414 case SUBMODULE_IMPORTS: {
4415 if (First) {
4416 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004417 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 }
4419
4420 if (!CurrentModule)
4421 break;
4422
4423 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004424 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004425 Unresolved.File = &F;
4426 Unresolved.Mod = CurrentModule;
4427 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004428 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004430 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 }
4432 break;
4433 }
4434
4435 case SUBMODULE_EXPORTS: {
4436 if (First) {
4437 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004438 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
4440
4441 if (!CurrentModule)
4442 break;
4443
4444 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004445 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 Unresolved.File = &F;
4447 Unresolved.Mod = CurrentModule;
4448 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004449 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004451 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 }
4453
4454 // Once we've loaded the set of exports, there's no reason to keep
4455 // the parsed, unresolved exports around.
4456 CurrentModule->UnresolvedExports.clear();
4457 break;
4458 }
4459 case SUBMODULE_REQUIRES: {
4460 if (First) {
4461 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004462 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
4464
4465 if (!CurrentModule)
4466 break;
4467
Richard Smitha3feee22013-10-28 22:18:19 +00004468 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 Context.getTargetInfo());
4470 break;
4471 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004472
4473 case SUBMODULE_LINK_LIBRARY:
4474 if (First) {
4475 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004476 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004477 }
4478
4479 if (!CurrentModule)
4480 break;
4481
4482 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004483 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004484 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004485
4486 case SUBMODULE_CONFIG_MACRO:
4487 if (First) {
4488 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004489 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004490 }
4491
4492 if (!CurrentModule)
4493 break;
4494
4495 CurrentModule->ConfigMacros.push_back(Blob.str());
4496 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004497
4498 case SUBMODULE_CONFLICT: {
4499 if (First) {
4500 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004501 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004502 }
4503
4504 if (!CurrentModule)
4505 break;
4506
4507 UnresolvedModuleRef Unresolved;
4508 Unresolved.File = &F;
4509 Unresolved.Mod = CurrentModule;
4510 Unresolved.ID = Record[0];
4511 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4512 Unresolved.IsWildcard = false;
4513 Unresolved.String = Blob;
4514 UnresolvedModuleRefs.push_back(Unresolved);
4515 break;
4516 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518 }
4519}
4520
4521/// \brief Parse the record that corresponds to a LangOptions data
4522/// structure.
4523///
4524/// This routine parses the language options from the AST file and then gives
4525/// them to the AST listener if one is set.
4526///
4527/// \returns true if the listener deems the file unacceptable, false otherwise.
4528bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4529 bool Complain,
4530 ASTReaderListener &Listener) {
4531 LangOptions LangOpts;
4532 unsigned Idx = 0;
4533#define LANGOPT(Name, Bits, Default, Description) \
4534 LangOpts.Name = Record[Idx++];
4535#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4536 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4537#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004538#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4539#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004540
4541 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4542 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4543 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4544
4545 unsigned Length = Record[Idx++];
4546 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4547 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004548
4549 Idx += Length;
4550
4551 // Comment options.
4552 for (unsigned N = Record[Idx++]; N; --N) {
4553 LangOpts.CommentOpts.BlockCommandNames.push_back(
4554 ReadString(Record, Idx));
4555 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004556 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004557
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 return Listener.ReadLanguageOptions(LangOpts, Complain);
4559}
4560
4561bool ASTReader::ParseTargetOptions(const RecordData &Record,
4562 bool Complain,
4563 ASTReaderListener &Listener) {
4564 unsigned Idx = 0;
4565 TargetOptions TargetOpts;
4566 TargetOpts.Triple = ReadString(Record, Idx);
4567 TargetOpts.CPU = ReadString(Record, Idx);
4568 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 for (unsigned N = Record[Idx++]; N; --N) {
4570 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4571 }
4572 for (unsigned N = Record[Idx++]; N; --N) {
4573 TargetOpts.Features.push_back(ReadString(Record, Idx));
4574 }
4575
4576 return Listener.ReadTargetOptions(TargetOpts, Complain);
4577}
4578
4579bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4580 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004581 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004583#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004584#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004585 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004586#include "clang/Basic/DiagnosticOptions.def"
4587
4588 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004589 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004590 }
4591
4592 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4593}
4594
4595bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4596 ASTReaderListener &Listener) {
4597 FileSystemOptions FSOpts;
4598 unsigned Idx = 0;
4599 FSOpts.WorkingDir = ReadString(Record, Idx);
4600 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4601}
4602
4603bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4604 bool Complain,
4605 ASTReaderListener &Listener) {
4606 HeaderSearchOptions HSOpts;
4607 unsigned Idx = 0;
4608 HSOpts.Sysroot = ReadString(Record, Idx);
4609
4610 // Include entries.
4611 for (unsigned N = Record[Idx++]; N; --N) {
4612 std::string Path = ReadString(Record, Idx);
4613 frontend::IncludeDirGroup Group
4614 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 bool IsFramework = Record[Idx++];
4616 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004618 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
4620
4621 // System header prefixes.
4622 for (unsigned N = Record[Idx++]; N; --N) {
4623 std::string Prefix = ReadString(Record, Idx);
4624 bool IsSystemHeader = Record[Idx++];
4625 HSOpts.SystemHeaderPrefixes.push_back(
4626 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4627 }
4628
4629 HSOpts.ResourceDir = ReadString(Record, Idx);
4630 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004631 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 HSOpts.DisableModuleHash = Record[Idx++];
4633 HSOpts.UseBuiltinIncludes = Record[Idx++];
4634 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4635 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4636 HSOpts.UseLibcxx = Record[Idx++];
4637
4638 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4639}
4640
4641bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4642 bool Complain,
4643 ASTReaderListener &Listener,
4644 std::string &SuggestedPredefines) {
4645 PreprocessorOptions PPOpts;
4646 unsigned Idx = 0;
4647
4648 // Macro definitions/undefs
4649 for (unsigned N = Record[Idx++]; N; --N) {
4650 std::string Macro = ReadString(Record, Idx);
4651 bool IsUndef = Record[Idx++];
4652 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4653 }
4654
4655 // Includes
4656 for (unsigned N = Record[Idx++]; N; --N) {
4657 PPOpts.Includes.push_back(ReadString(Record, Idx));
4658 }
4659
4660 // Macro Includes
4661 for (unsigned N = Record[Idx++]; N; --N) {
4662 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4663 }
4664
4665 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004666 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4668 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4669 PPOpts.ObjCXXARCStandardLibrary =
4670 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4671 SuggestedPredefines.clear();
4672 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4673 SuggestedPredefines);
4674}
4675
4676std::pair<ModuleFile *, unsigned>
4677ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4678 GlobalPreprocessedEntityMapType::iterator
4679 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4680 assert(I != GlobalPreprocessedEntityMap.end() &&
4681 "Corrupted global preprocessed entity map");
4682 ModuleFile *M = I->second;
4683 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4684 return std::make_pair(M, LocalIndex);
4685}
4686
4687std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4688ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4689 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4690 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4691 Mod.NumPreprocessedEntities);
4692
4693 return std::make_pair(PreprocessingRecord::iterator(),
4694 PreprocessingRecord::iterator());
4695}
4696
4697std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4698ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4699 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4700 ModuleDeclIterator(this, &Mod,
4701 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4702}
4703
4704PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4705 PreprocessedEntityID PPID = Index+1;
4706 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4707 ModuleFile &M = *PPInfo.first;
4708 unsigned LocalIndex = PPInfo.second;
4709 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4710
Guy Benyei11169dd2012-12-18 14:30:41 +00004711 if (!PP.getPreprocessingRecord()) {
4712 Error("no preprocessing record");
4713 return 0;
4714 }
4715
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004716 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4717 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4718
4719 llvm::BitstreamEntry Entry =
4720 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4721 if (Entry.Kind != llvm::BitstreamEntry::Record)
4722 return 0;
4723
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 // Read the record.
4725 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4726 ReadSourceLocation(M, PPOffs.End));
4727 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004728 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 RecordData Record;
4730 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004731 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4732 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004733 switch (RecType) {
4734 case PPD_MACRO_EXPANSION: {
4735 bool isBuiltin = Record[0];
4736 IdentifierInfo *Name = 0;
4737 MacroDefinition *Def = 0;
4738 if (isBuiltin)
4739 Name = getLocalIdentifier(M, Record[1]);
4740 else {
4741 PreprocessedEntityID
4742 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4743 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4744 }
4745
4746 MacroExpansion *ME;
4747 if (isBuiltin)
4748 ME = new (PPRec) MacroExpansion(Name, Range);
4749 else
4750 ME = new (PPRec) MacroExpansion(Def, Range);
4751
4752 return ME;
4753 }
4754
4755 case PPD_MACRO_DEFINITION: {
4756 // Decode the identifier info and then check again; if the macro is
4757 // still defined and associated with the identifier,
4758 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4759 MacroDefinition *MD
4760 = new (PPRec) MacroDefinition(II, Range);
4761
4762 if (DeserializationListener)
4763 DeserializationListener->MacroDefinitionRead(PPID, MD);
4764
4765 return MD;
4766 }
4767
4768 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004769 const char *FullFileNameStart = Blob.data() + Record[0];
4770 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 const FileEntry *File = 0;
4772 if (!FullFileName.empty())
4773 File = PP.getFileManager().getFile(FullFileName);
4774
4775 // FIXME: Stable encoding
4776 InclusionDirective::InclusionKind Kind
4777 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4778 InclusionDirective *ID
4779 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004780 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004781 Record[1], Record[3],
4782 File,
4783 Range);
4784 return ID;
4785 }
4786 }
4787
4788 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4789}
4790
4791/// \brief \arg SLocMapI points at a chunk of a module that contains no
4792/// preprocessed entities or the entities it contains are not the ones we are
4793/// looking for. Find the next module that contains entities and return the ID
4794/// of the first entry.
4795PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4796 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4797 ++SLocMapI;
4798 for (GlobalSLocOffsetMapType::const_iterator
4799 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4800 ModuleFile &M = *SLocMapI->second;
4801 if (M.NumPreprocessedEntities)
4802 return M.BasePreprocessedEntityID;
4803 }
4804
4805 return getTotalNumPreprocessedEntities();
4806}
4807
4808namespace {
4809
4810template <unsigned PPEntityOffset::*PPLoc>
4811struct PPEntityComp {
4812 const ASTReader &Reader;
4813 ModuleFile &M;
4814
4815 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4816
4817 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4818 SourceLocation LHS = getLoc(L);
4819 SourceLocation RHS = getLoc(R);
4820 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4821 }
4822
4823 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4824 SourceLocation LHS = getLoc(L);
4825 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4826 }
4827
4828 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4829 SourceLocation RHS = getLoc(R);
4830 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4831 }
4832
4833 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4834 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4835 }
4836};
4837
4838}
4839
4840/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4841PreprocessedEntityID
4842ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4843 if (SourceMgr.isLocalSourceLocation(BLoc))
4844 return getTotalNumPreprocessedEntities();
4845
4846 GlobalSLocOffsetMapType::const_iterator
4847 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004848 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4850 "Corrupted global sloc offset map");
4851
4852 if (SLocMapI->second->NumPreprocessedEntities == 0)
4853 return findNextPreprocessedEntity(SLocMapI);
4854
4855 ModuleFile &M = *SLocMapI->second;
4856 typedef const PPEntityOffset *pp_iterator;
4857 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4858 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4859
4860 size_t Count = M.NumPreprocessedEntities;
4861 size_t Half;
4862 pp_iterator First = pp_begin;
4863 pp_iterator PPI;
4864
4865 // Do a binary search manually instead of using std::lower_bound because
4866 // The end locations of entities may be unordered (when a macro expansion
4867 // is inside another macro argument), but for this case it is not important
4868 // whether we get the first macro expansion or its containing macro.
4869 while (Count > 0) {
4870 Half = Count/2;
4871 PPI = First;
4872 std::advance(PPI, Half);
4873 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4874 BLoc)){
4875 First = PPI;
4876 ++First;
4877 Count = Count - Half - 1;
4878 } else
4879 Count = Half;
4880 }
4881
4882 if (PPI == pp_end)
4883 return findNextPreprocessedEntity(SLocMapI);
4884
4885 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4886}
4887
4888/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4889PreprocessedEntityID
4890ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4891 if (SourceMgr.isLocalSourceLocation(ELoc))
4892 return getTotalNumPreprocessedEntities();
4893
4894 GlobalSLocOffsetMapType::const_iterator
4895 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004896 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4898 "Corrupted global sloc offset map");
4899
4900 if (SLocMapI->second->NumPreprocessedEntities == 0)
4901 return findNextPreprocessedEntity(SLocMapI);
4902
4903 ModuleFile &M = *SLocMapI->second;
4904 typedef const PPEntityOffset *pp_iterator;
4905 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4906 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4907 pp_iterator PPI =
4908 std::upper_bound(pp_begin, pp_end, ELoc,
4909 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4910
4911 if (PPI == pp_end)
4912 return findNextPreprocessedEntity(SLocMapI);
4913
4914 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4915}
4916
4917/// \brief Returns a pair of [Begin, End) indices of preallocated
4918/// preprocessed entities that \arg Range encompasses.
4919std::pair<unsigned, unsigned>
4920 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4921 if (Range.isInvalid())
4922 return std::make_pair(0,0);
4923 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4924
4925 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4926 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4927 return std::make_pair(BeginID, EndID);
4928}
4929
4930/// \brief Optionally returns true or false if the preallocated preprocessed
4931/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004932Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 FileID FID) {
4934 if (FID.isInvalid())
4935 return false;
4936
4937 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4938 ModuleFile &M = *PPInfo.first;
4939 unsigned LocalIndex = PPInfo.second;
4940 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4941
4942 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4943 if (Loc.isInvalid())
4944 return false;
4945
4946 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4947 return true;
4948 else
4949 return false;
4950}
4951
4952namespace {
4953 /// \brief Visitor used to search for information about a header file.
4954 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 const FileEntry *FE;
4956
David Blaikie05785d12013-02-20 22:23:23 +00004957 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958
4959 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004960 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4961 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004962
4963 static bool visit(ModuleFile &M, void *UserData) {
4964 HeaderFileInfoVisitor *This
4965 = static_cast<HeaderFileInfoVisitor *>(UserData);
4966
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 HeaderFileInfoLookupTable *Table
4968 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4969 if (!Table)
4970 return false;
4971
4972 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004973 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 if (Pos == Table->end())
4975 return false;
4976
4977 This->HFI = *Pos;
4978 return true;
4979 }
4980
David Blaikie05785d12013-02-20 22:23:23 +00004981 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 };
4983}
4984
4985HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004986 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004988 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004990
4991 return HeaderFileInfo();
4992}
4993
4994void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4995 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004996 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4998 ModuleFile &F = *(*I);
4999 unsigned Idx = 0;
5000 DiagStates.clear();
5001 assert(!Diag.DiagStates.empty());
5002 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5003 while (Idx < F.PragmaDiagMappings.size()) {
5004 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5005 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5006 if (DiagStateID != 0) {
5007 Diag.DiagStatePoints.push_back(
5008 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5009 FullSourceLoc(Loc, SourceMgr)));
5010 continue;
5011 }
5012
5013 assert(DiagStateID == 0);
5014 // A new DiagState was created here.
5015 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5016 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5017 DiagStates.push_back(NewState);
5018 Diag.DiagStatePoints.push_back(
5019 DiagnosticsEngine::DiagStatePoint(NewState,
5020 FullSourceLoc(Loc, SourceMgr)));
5021 while (1) {
5022 assert(Idx < F.PragmaDiagMappings.size() &&
5023 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5024 if (Idx >= F.PragmaDiagMappings.size()) {
5025 break; // Something is messed up but at least avoid infinite loop in
5026 // release build.
5027 }
5028 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5029 if (DiagID == (unsigned)-1) {
5030 break; // no more diag/map pairs for this location.
5031 }
5032 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5033 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5034 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5035 }
5036 }
5037 }
5038}
5039
5040/// \brief Get the correct cursor and offset for loading a type.
5041ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5042 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5043 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5044 ModuleFile *M = I->second;
5045 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5046}
5047
5048/// \brief Read and return the type with the given index..
5049///
5050/// The index is the type ID, shifted and minus the number of predefs. This
5051/// routine actually reads the record corresponding to the type at the given
5052/// location. It is a helper routine for GetType, which deals with reading type
5053/// IDs.
5054QualType ASTReader::readTypeRecord(unsigned Index) {
5055 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005056 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005057
5058 // Keep track of where we are in the stream, then jump back there
5059 // after reading this type.
5060 SavedStreamPosition SavedPosition(DeclsCursor);
5061
5062 ReadingKindTracker ReadingKind(Read_Type, *this);
5063
5064 // Note that we are loading a type record.
5065 Deserializing AType(this);
5066
5067 unsigned Idx = 0;
5068 DeclsCursor.JumpToBit(Loc.Offset);
5069 RecordData Record;
5070 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005071 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 case TYPE_EXT_QUAL: {
5073 if (Record.size() != 2) {
5074 Error("Incorrect encoding of extended qualifier type");
5075 return QualType();
5076 }
5077 QualType Base = readType(*Loc.F, Record, Idx);
5078 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5079 return Context.getQualifiedType(Base, Quals);
5080 }
5081
5082 case TYPE_COMPLEX: {
5083 if (Record.size() != 1) {
5084 Error("Incorrect encoding of complex type");
5085 return QualType();
5086 }
5087 QualType ElemType = readType(*Loc.F, Record, Idx);
5088 return Context.getComplexType(ElemType);
5089 }
5090
5091 case TYPE_POINTER: {
5092 if (Record.size() != 1) {
5093 Error("Incorrect encoding of pointer type");
5094 return QualType();
5095 }
5096 QualType PointeeType = readType(*Loc.F, Record, Idx);
5097 return Context.getPointerType(PointeeType);
5098 }
5099
Reid Kleckner8a365022013-06-24 17:51:48 +00005100 case TYPE_DECAYED: {
5101 if (Record.size() != 1) {
5102 Error("Incorrect encoding of decayed type");
5103 return QualType();
5104 }
5105 QualType OriginalType = readType(*Loc.F, Record, Idx);
5106 QualType DT = Context.getAdjustedParameterType(OriginalType);
5107 if (!isa<DecayedType>(DT))
5108 Error("Decayed type does not decay");
5109 return DT;
5110 }
5111
Reid Kleckner0503a872013-12-05 01:23:43 +00005112 case TYPE_ADJUSTED: {
5113 if (Record.size() != 2) {
5114 Error("Incorrect encoding of adjusted type");
5115 return QualType();
5116 }
5117 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5118 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5119 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5120 }
5121
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 case TYPE_BLOCK_POINTER: {
5123 if (Record.size() != 1) {
5124 Error("Incorrect encoding of block pointer type");
5125 return QualType();
5126 }
5127 QualType PointeeType = readType(*Loc.F, Record, Idx);
5128 return Context.getBlockPointerType(PointeeType);
5129 }
5130
5131 case TYPE_LVALUE_REFERENCE: {
5132 if (Record.size() != 2) {
5133 Error("Incorrect encoding of lvalue reference type");
5134 return QualType();
5135 }
5136 QualType PointeeType = readType(*Loc.F, Record, Idx);
5137 return Context.getLValueReferenceType(PointeeType, Record[1]);
5138 }
5139
5140 case TYPE_RVALUE_REFERENCE: {
5141 if (Record.size() != 1) {
5142 Error("Incorrect encoding of rvalue reference type");
5143 return QualType();
5144 }
5145 QualType PointeeType = readType(*Loc.F, Record, Idx);
5146 return Context.getRValueReferenceType(PointeeType);
5147 }
5148
5149 case TYPE_MEMBER_POINTER: {
5150 if (Record.size() != 2) {
5151 Error("Incorrect encoding of member pointer type");
5152 return QualType();
5153 }
5154 QualType PointeeType = readType(*Loc.F, Record, Idx);
5155 QualType ClassType = readType(*Loc.F, Record, Idx);
5156 if (PointeeType.isNull() || ClassType.isNull())
5157 return QualType();
5158
5159 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5160 }
5161
5162 case TYPE_CONSTANT_ARRAY: {
5163 QualType ElementType = readType(*Loc.F, Record, Idx);
5164 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5165 unsigned IndexTypeQuals = Record[2];
5166 unsigned Idx = 3;
5167 llvm::APInt Size = ReadAPInt(Record, Idx);
5168 return Context.getConstantArrayType(ElementType, Size,
5169 ASM, IndexTypeQuals);
5170 }
5171
5172 case TYPE_INCOMPLETE_ARRAY: {
5173 QualType ElementType = readType(*Loc.F, Record, Idx);
5174 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5175 unsigned IndexTypeQuals = Record[2];
5176 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5177 }
5178
5179 case TYPE_VARIABLE_ARRAY: {
5180 QualType ElementType = readType(*Loc.F, Record, Idx);
5181 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5182 unsigned IndexTypeQuals = Record[2];
5183 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5184 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5185 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5186 ASM, IndexTypeQuals,
5187 SourceRange(LBLoc, RBLoc));
5188 }
5189
5190 case TYPE_VECTOR: {
5191 if (Record.size() != 3) {
5192 Error("incorrect encoding of vector type in AST file");
5193 return QualType();
5194 }
5195
5196 QualType ElementType = readType(*Loc.F, Record, Idx);
5197 unsigned NumElements = Record[1];
5198 unsigned VecKind = Record[2];
5199 return Context.getVectorType(ElementType, NumElements,
5200 (VectorType::VectorKind)VecKind);
5201 }
5202
5203 case TYPE_EXT_VECTOR: {
5204 if (Record.size() != 3) {
5205 Error("incorrect encoding of extended vector type in AST file");
5206 return QualType();
5207 }
5208
5209 QualType ElementType = readType(*Loc.F, Record, Idx);
5210 unsigned NumElements = Record[1];
5211 return Context.getExtVectorType(ElementType, NumElements);
5212 }
5213
5214 case TYPE_FUNCTION_NO_PROTO: {
5215 if (Record.size() != 6) {
5216 Error("incorrect encoding of no-proto function type");
5217 return QualType();
5218 }
5219 QualType ResultType = readType(*Loc.F, Record, Idx);
5220 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5221 (CallingConv)Record[4], Record[5]);
5222 return Context.getFunctionNoProtoType(ResultType, Info);
5223 }
5224
5225 case TYPE_FUNCTION_PROTO: {
5226 QualType ResultType = readType(*Loc.F, Record, Idx);
5227
5228 FunctionProtoType::ExtProtoInfo EPI;
5229 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5230 /*hasregparm*/ Record[2],
5231 /*regparm*/ Record[3],
5232 static_cast<CallingConv>(Record[4]),
5233 /*produces*/ Record[5]);
5234
5235 unsigned Idx = 6;
5236 unsigned NumParams = Record[Idx++];
5237 SmallVector<QualType, 16> ParamTypes;
5238 for (unsigned I = 0; I != NumParams; ++I)
5239 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5240
5241 EPI.Variadic = Record[Idx++];
5242 EPI.HasTrailingReturn = Record[Idx++];
5243 EPI.TypeQuals = Record[Idx++];
5244 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005245 SmallVector<QualType, 8> ExceptionStorage;
5246 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005247 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 }
5249
5250 case TYPE_UNRESOLVED_USING: {
5251 unsigned Idx = 0;
5252 return Context.getTypeDeclType(
5253 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5254 }
5255
5256 case TYPE_TYPEDEF: {
5257 if (Record.size() != 2) {
5258 Error("incorrect encoding of typedef type");
5259 return QualType();
5260 }
5261 unsigned Idx = 0;
5262 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5263 QualType Canonical = readType(*Loc.F, Record, Idx);
5264 if (!Canonical.isNull())
5265 Canonical = Context.getCanonicalType(Canonical);
5266 return Context.getTypedefType(Decl, Canonical);
5267 }
5268
5269 case TYPE_TYPEOF_EXPR:
5270 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5271
5272 case TYPE_TYPEOF: {
5273 if (Record.size() != 1) {
5274 Error("incorrect encoding of typeof(type) in AST file");
5275 return QualType();
5276 }
5277 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5278 return Context.getTypeOfType(UnderlyingType);
5279 }
5280
5281 case TYPE_DECLTYPE: {
5282 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5283 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5284 }
5285
5286 case TYPE_UNARY_TRANSFORM: {
5287 QualType BaseType = readType(*Loc.F, Record, Idx);
5288 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5289 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5290 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5291 }
5292
Richard Smith74aeef52013-04-26 16:15:35 +00005293 case TYPE_AUTO: {
5294 QualType Deduced = readType(*Loc.F, Record, Idx);
5295 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005296 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005297 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005298 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005299
5300 case TYPE_RECORD: {
5301 if (Record.size() != 2) {
5302 Error("incorrect encoding of record type");
5303 return QualType();
5304 }
5305 unsigned Idx = 0;
5306 bool IsDependent = Record[Idx++];
5307 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5308 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5309 QualType T = Context.getRecordType(RD);
5310 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5311 return T;
5312 }
5313
5314 case TYPE_ENUM: {
5315 if (Record.size() != 2) {
5316 Error("incorrect encoding of enum type");
5317 return QualType();
5318 }
5319 unsigned Idx = 0;
5320 bool IsDependent = Record[Idx++];
5321 QualType T
5322 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5323 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5324 return T;
5325 }
5326
5327 case TYPE_ATTRIBUTED: {
5328 if (Record.size() != 3) {
5329 Error("incorrect encoding of attributed type");
5330 return QualType();
5331 }
5332 QualType modifiedType = readType(*Loc.F, Record, Idx);
5333 QualType equivalentType = readType(*Loc.F, Record, Idx);
5334 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5335 return Context.getAttributedType(kind, modifiedType, equivalentType);
5336 }
5337
5338 case TYPE_PAREN: {
5339 if (Record.size() != 1) {
5340 Error("incorrect encoding of paren type");
5341 return QualType();
5342 }
5343 QualType InnerType = readType(*Loc.F, Record, Idx);
5344 return Context.getParenType(InnerType);
5345 }
5346
5347 case TYPE_PACK_EXPANSION: {
5348 if (Record.size() != 2) {
5349 Error("incorrect encoding of pack expansion type");
5350 return QualType();
5351 }
5352 QualType Pattern = readType(*Loc.F, Record, Idx);
5353 if (Pattern.isNull())
5354 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005355 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 if (Record[1])
5357 NumExpansions = Record[1] - 1;
5358 return Context.getPackExpansionType(Pattern, NumExpansions);
5359 }
5360
5361 case TYPE_ELABORATED: {
5362 unsigned Idx = 0;
5363 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5364 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5365 QualType NamedType = readType(*Loc.F, Record, Idx);
5366 return Context.getElaboratedType(Keyword, NNS, NamedType);
5367 }
5368
5369 case TYPE_OBJC_INTERFACE: {
5370 unsigned Idx = 0;
5371 ObjCInterfaceDecl *ItfD
5372 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5373 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5374 }
5375
5376 case TYPE_OBJC_OBJECT: {
5377 unsigned Idx = 0;
5378 QualType Base = readType(*Loc.F, Record, Idx);
5379 unsigned NumProtos = Record[Idx++];
5380 SmallVector<ObjCProtocolDecl*, 4> Protos;
5381 for (unsigned I = 0; I != NumProtos; ++I)
5382 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5383 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5384 }
5385
5386 case TYPE_OBJC_OBJECT_POINTER: {
5387 unsigned Idx = 0;
5388 QualType Pointee = readType(*Loc.F, Record, Idx);
5389 return Context.getObjCObjectPointerType(Pointee);
5390 }
5391
5392 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5393 unsigned Idx = 0;
5394 QualType Parm = readType(*Loc.F, Record, Idx);
5395 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005396 return Context.getSubstTemplateTypeParmType(
5397 cast<TemplateTypeParmType>(Parm),
5398 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 }
5400
5401 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5402 unsigned Idx = 0;
5403 QualType Parm = readType(*Loc.F, Record, Idx);
5404 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5405 return Context.getSubstTemplateTypeParmPackType(
5406 cast<TemplateTypeParmType>(Parm),
5407 ArgPack);
5408 }
5409
5410 case TYPE_INJECTED_CLASS_NAME: {
5411 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5412 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5413 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5414 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005415 const Type *T;
5416 if (const Type *Existing = D->getTypeForDecl())
5417 T = Existing;
5418 else if (auto *Prev = D->getPreviousDecl())
5419 T = Prev->getTypeForDecl();
5420 else
5421 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5422 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 }
5424
5425 case TYPE_TEMPLATE_TYPE_PARM: {
5426 unsigned Idx = 0;
5427 unsigned Depth = Record[Idx++];
5428 unsigned Index = Record[Idx++];
5429 bool Pack = Record[Idx++];
5430 TemplateTypeParmDecl *D
5431 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5432 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5433 }
5434
5435 case TYPE_DEPENDENT_NAME: {
5436 unsigned Idx = 0;
5437 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5438 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5439 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5440 QualType Canon = readType(*Loc.F, Record, Idx);
5441 if (!Canon.isNull())
5442 Canon = Context.getCanonicalType(Canon);
5443 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5444 }
5445
5446 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5447 unsigned Idx = 0;
5448 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5449 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5450 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5451 unsigned NumArgs = Record[Idx++];
5452 SmallVector<TemplateArgument, 8> Args;
5453 Args.reserve(NumArgs);
5454 while (NumArgs--)
5455 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5456 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5457 Args.size(), Args.data());
5458 }
5459
5460 case TYPE_DEPENDENT_SIZED_ARRAY: {
5461 unsigned Idx = 0;
5462
5463 // ArrayType
5464 QualType ElementType = readType(*Loc.F, Record, Idx);
5465 ArrayType::ArraySizeModifier ASM
5466 = (ArrayType::ArraySizeModifier)Record[Idx++];
5467 unsigned IndexTypeQuals = Record[Idx++];
5468
5469 // DependentSizedArrayType
5470 Expr *NumElts = ReadExpr(*Loc.F);
5471 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5472
5473 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5474 IndexTypeQuals, Brackets);
5475 }
5476
5477 case TYPE_TEMPLATE_SPECIALIZATION: {
5478 unsigned Idx = 0;
5479 bool IsDependent = Record[Idx++];
5480 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5481 SmallVector<TemplateArgument, 8> Args;
5482 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5483 QualType Underlying = readType(*Loc.F, Record, Idx);
5484 QualType T;
5485 if (Underlying.isNull())
5486 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5487 Args.size());
5488 else
5489 T = Context.getTemplateSpecializationType(Name, Args.data(),
5490 Args.size(), Underlying);
5491 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5492 return T;
5493 }
5494
5495 case TYPE_ATOMIC: {
5496 if (Record.size() != 1) {
5497 Error("Incorrect encoding of atomic type");
5498 return QualType();
5499 }
5500 QualType ValueType = readType(*Loc.F, Record, Idx);
5501 return Context.getAtomicType(ValueType);
5502 }
5503 }
5504 llvm_unreachable("Invalid TypeCode!");
5505}
5506
Richard Smith564417a2014-03-20 21:47:22 +00005507void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5508 SmallVectorImpl<QualType> &Exceptions,
5509 FunctionProtoType::ExtProtoInfo &EPI,
5510 const RecordData &Record, unsigned &Idx) {
5511 ExceptionSpecificationType EST =
5512 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5513 EPI.ExceptionSpecType = EST;
5514 if (EST == EST_Dynamic) {
5515 EPI.NumExceptions = Record[Idx++];
5516 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5517 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5518 EPI.Exceptions = Exceptions.data();
5519 } else if (EST == EST_ComputedNoexcept) {
5520 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5521 } else if (EST == EST_Uninstantiated) {
5522 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5523 EPI.ExceptionSpecTemplate =
5524 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5525 } else if (EST == EST_Unevaluated) {
5526 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5527 }
5528}
5529
Guy Benyei11169dd2012-12-18 14:30:41 +00005530class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5531 ASTReader &Reader;
5532 ModuleFile &F;
5533 const ASTReader::RecordData &Record;
5534 unsigned &Idx;
5535
5536 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5537 unsigned &I) {
5538 return Reader.ReadSourceLocation(F, R, I);
5539 }
5540
5541 template<typename T>
5542 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5543 return Reader.ReadDeclAs<T>(F, Record, Idx);
5544 }
5545
5546public:
5547 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5548 const ASTReader::RecordData &Record, unsigned &Idx)
5549 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5550 { }
5551
5552 // We want compile-time assurance that we've enumerated all of
5553 // these, so unfortunately we have to declare them first, then
5554 // define them out-of-line.
5555#define ABSTRACT_TYPELOC(CLASS, PARENT)
5556#define TYPELOC(CLASS, PARENT) \
5557 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5558#include "clang/AST/TypeLocNodes.def"
5559
5560 void VisitFunctionTypeLoc(FunctionTypeLoc);
5561 void VisitArrayTypeLoc(ArrayTypeLoc);
5562};
5563
5564void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5565 // nothing to do
5566}
5567void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5568 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5569 if (TL.needsExtraLocalData()) {
5570 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5571 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5572 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5573 TL.setModeAttr(Record[Idx++]);
5574 }
5575}
5576void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5577 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5578}
5579void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5580 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5581}
Reid Kleckner8a365022013-06-24 17:51:48 +00005582void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5583 // nothing to do
5584}
Reid Kleckner0503a872013-12-05 01:23:43 +00005585void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5586 // nothing to do
5587}
Guy Benyei11169dd2012-12-18 14:30:41 +00005588void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5589 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5590}
5591void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5592 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5593}
5594void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5595 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5596}
5597void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5598 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5599 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5600}
5601void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5602 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5603 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5604 if (Record[Idx++])
5605 TL.setSizeExpr(Reader.ReadExpr(F));
5606 else
5607 TL.setSizeExpr(0);
5608}
5609void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5610 VisitArrayTypeLoc(TL);
5611}
5612void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5613 VisitArrayTypeLoc(TL);
5614}
5615void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5616 VisitArrayTypeLoc(TL);
5617}
5618void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5619 DependentSizedArrayTypeLoc TL) {
5620 VisitArrayTypeLoc(TL);
5621}
5622void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5623 DependentSizedExtVectorTypeLoc TL) {
5624 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5625}
5626void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5627 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628}
5629void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5630 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5631}
5632void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5633 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5634 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5635 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5636 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005637 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5638 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 }
5640}
5641void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5642 VisitFunctionTypeLoc(TL);
5643}
5644void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5645 VisitFunctionTypeLoc(TL);
5646}
5647void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5648 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5649}
5650void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5651 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5652}
5653void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5654 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5655 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5656 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5657}
5658void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5659 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5660 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5661 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5662 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5663}
5664void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5668 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5669 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5670 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5671 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5672}
5673void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5674 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5677 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5680 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5681}
5682void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5683 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5684 if (TL.hasAttrOperand()) {
5685 SourceRange range;
5686 range.setBegin(ReadSourceLocation(Record, Idx));
5687 range.setEnd(ReadSourceLocation(Record, Idx));
5688 TL.setAttrOperandParensRange(range);
5689 }
5690 if (TL.hasAttrExprOperand()) {
5691 if (Record[Idx++])
5692 TL.setAttrExprOperand(Reader.ReadExpr(F));
5693 else
5694 TL.setAttrExprOperand(0);
5695 } else if (TL.hasAttrEnumOperand())
5696 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5697}
5698void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5699 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5700}
5701void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5702 SubstTemplateTypeParmTypeLoc TL) {
5703 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5704}
5705void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5706 SubstTemplateTypeParmPackTypeLoc TL) {
5707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5708}
5709void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5710 TemplateSpecializationTypeLoc TL) {
5711 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5712 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5713 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5714 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5715 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5716 TL.setArgLocInfo(i,
5717 Reader.GetTemplateArgumentLocInfo(F,
5718 TL.getTypePtr()->getArg(i).getKind(),
5719 Record, Idx));
5720}
5721void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5722 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5723 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5724}
5725void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5726 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5727 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5728}
5729void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5730 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5731}
5732void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5733 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5734 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5735 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5736}
5737void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5738 DependentTemplateSpecializationTypeLoc TL) {
5739 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5740 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5741 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5742 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5743 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5744 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5745 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5746 TL.setArgLocInfo(I,
5747 Reader.GetTemplateArgumentLocInfo(F,
5748 TL.getTypePtr()->getArg(I).getKind(),
5749 Record, Idx));
5750}
5751void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5752 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5753}
5754void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5755 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5756}
5757void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5758 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5759 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5760 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5761 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5762 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5763}
5764void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5765 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5766}
5767void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5768 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5769 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5770 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5771}
5772
5773TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5774 const RecordData &Record,
5775 unsigned &Idx) {
5776 QualType InfoTy = readType(F, Record, Idx);
5777 if (InfoTy.isNull())
5778 return 0;
5779
5780 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5781 TypeLocReader TLR(*this, F, Record, Idx);
5782 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5783 TLR.Visit(TL);
5784 return TInfo;
5785}
5786
5787QualType ASTReader::GetType(TypeID ID) {
5788 unsigned FastQuals = ID & Qualifiers::FastMask;
5789 unsigned Index = ID >> Qualifiers::FastWidth;
5790
5791 if (Index < NUM_PREDEF_TYPE_IDS) {
5792 QualType T;
5793 switch ((PredefinedTypeIDs)Index) {
5794 case PREDEF_TYPE_NULL_ID: return QualType();
5795 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5796 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5797
5798 case PREDEF_TYPE_CHAR_U_ID:
5799 case PREDEF_TYPE_CHAR_S_ID:
5800 // FIXME: Check that the signedness of CharTy is correct!
5801 T = Context.CharTy;
5802 break;
5803
5804 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5805 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5806 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5807 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5808 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5809 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5810 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5811 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5812 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5813 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5814 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5815 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5816 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5817 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5818 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5819 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5820 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5821 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5822 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5823 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5824 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5825 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5826 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5827 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5828 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5829 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5830 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5831 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005832 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5833 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5834 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5835 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5836 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5837 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005838 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005839 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5841
5842 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5843 T = Context.getAutoRRefDeductType();
5844 break;
5845
5846 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5847 T = Context.ARCUnbridgedCastTy;
5848 break;
5849
5850 case PREDEF_TYPE_VA_LIST_TAG:
5851 T = Context.getVaListTagType();
5852 break;
5853
5854 case PREDEF_TYPE_BUILTIN_FN:
5855 T = Context.BuiltinFnTy;
5856 break;
5857 }
5858
5859 assert(!T.isNull() && "Unknown predefined type");
5860 return T.withFastQualifiers(FastQuals);
5861 }
5862
5863 Index -= NUM_PREDEF_TYPE_IDS;
5864 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5865 if (TypesLoaded[Index].isNull()) {
5866 TypesLoaded[Index] = readTypeRecord(Index);
5867 if (TypesLoaded[Index].isNull())
5868 return QualType();
5869
5870 TypesLoaded[Index]->setFromAST();
5871 if (DeserializationListener)
5872 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5873 TypesLoaded[Index]);
5874 }
5875
5876 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5877}
5878
5879QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5880 return GetType(getGlobalTypeID(F, LocalID));
5881}
5882
5883serialization::TypeID
5884ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5885 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5886 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5887
5888 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5889 return LocalID;
5890
5891 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5892 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5893 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5894
5895 unsigned GlobalIndex = LocalIndex + I->second;
5896 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5897}
5898
5899TemplateArgumentLocInfo
5900ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5901 TemplateArgument::ArgKind Kind,
5902 const RecordData &Record,
5903 unsigned &Index) {
5904 switch (Kind) {
5905 case TemplateArgument::Expression:
5906 return ReadExpr(F);
5907 case TemplateArgument::Type:
5908 return GetTypeSourceInfo(F, Record, Index);
5909 case TemplateArgument::Template: {
5910 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5911 Index);
5912 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5913 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5914 SourceLocation());
5915 }
5916 case TemplateArgument::TemplateExpansion: {
5917 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5918 Index);
5919 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5920 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5921 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5922 EllipsisLoc);
5923 }
5924 case TemplateArgument::Null:
5925 case TemplateArgument::Integral:
5926 case TemplateArgument::Declaration:
5927 case TemplateArgument::NullPtr:
5928 case TemplateArgument::Pack:
5929 // FIXME: Is this right?
5930 return TemplateArgumentLocInfo();
5931 }
5932 llvm_unreachable("unexpected template argument loc");
5933}
5934
5935TemplateArgumentLoc
5936ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5937 const RecordData &Record, unsigned &Index) {
5938 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5939
5940 if (Arg.getKind() == TemplateArgument::Expression) {
5941 if (Record[Index++]) // bool InfoHasSameExpr.
5942 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5943 }
5944 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5945 Record, Index));
5946}
5947
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005948const ASTTemplateArgumentListInfo*
5949ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5950 const RecordData &Record,
5951 unsigned &Index) {
5952 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5953 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5954 unsigned NumArgsAsWritten = Record[Index++];
5955 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5956 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5957 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5958 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5959}
5960
Guy Benyei11169dd2012-12-18 14:30:41 +00005961Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5962 return GetDecl(ID);
5963}
5964
Richard Smithcd45dbc2014-04-19 03:48:30 +00005965uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5966 const RecordData &Record,
5967 unsigned &Idx) {
5968 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5969 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005971 }
5972
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 unsigned LocalID = Record[Idx++];
5974 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5975}
5976
5977CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5978 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005979 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005980 SavedStreamPosition SavedPosition(Cursor);
5981 Cursor.JumpToBit(Loc.Offset);
5982 ReadingKindTracker ReadingKind(Read_Decl, *this);
5983 RecordData Record;
5984 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005985 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005986 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005987 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 return 0;
5989 }
5990
5991 unsigned Idx = 0;
5992 unsigned NumBases = Record[Idx++];
5993 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5994 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5995 for (unsigned I = 0; I != NumBases; ++I)
5996 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5997 return Bases;
5998}
5999
6000serialization::DeclID
6001ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6002 if (LocalID < NUM_PREDEF_DECL_IDS)
6003 return LocalID;
6004
6005 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6006 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6007 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6008
6009 return LocalID + I->second;
6010}
6011
6012bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6013 ModuleFile &M) const {
6014 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6015 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6016 return &M == I->second;
6017}
6018
Douglas Gregor9f782892013-01-21 15:25:38 +00006019ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006020 if (!D->isFromASTFile())
6021 return 0;
6022 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6023 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6024 return I->second;
6025}
6026
6027SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6028 if (ID < NUM_PREDEF_DECL_IDS)
6029 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006030
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6032
6033 if (Index > DeclsLoaded.size()) {
6034 Error("declaration ID out-of-range for AST file");
6035 return SourceLocation();
6036 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006037
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (Decl *D = DeclsLoaded[Index])
6039 return D->getLocation();
6040
6041 unsigned RawLocation = 0;
6042 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6043 return ReadSourceLocation(*Rec.F, RawLocation);
6044}
6045
Richard Smithcd45dbc2014-04-19 03:48:30 +00006046Decl *ASTReader::GetExistingDecl(DeclID ID) {
6047 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 switch ((PredefinedDeclIDs)ID) {
6049 case PREDEF_DECL_NULL_ID:
6050 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006051
Guy Benyei11169dd2012-12-18 14:30:41 +00006052 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6053 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006054
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 case PREDEF_DECL_OBJC_ID_ID:
6056 return Context.getObjCIdDecl();
6057
6058 case PREDEF_DECL_OBJC_SEL_ID:
6059 return Context.getObjCSelDecl();
6060
6061 case PREDEF_DECL_OBJC_CLASS_ID:
6062 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006063
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6065 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006066
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 case PREDEF_DECL_INT_128_ID:
6068 return Context.getInt128Decl();
6069
6070 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6071 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006072
Guy Benyei11169dd2012-12-18 14:30:41 +00006073 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6074 return Context.getObjCInstanceTypeDecl();
6075
6076 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6077 return Context.getBuiltinVaListDecl();
6078 }
6079 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006080
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6082
6083 if (Index >= DeclsLoaded.size()) {
6084 assert(0 && "declaration ID out-of-range for AST file");
6085 Error("declaration ID out-of-range for AST file");
6086 return 0;
6087 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088
6089 return DeclsLoaded[Index];
6090}
6091
6092Decl *ASTReader::GetDecl(DeclID ID) {
6093 if (ID < NUM_PREDEF_DECL_IDS)
6094 return GetExistingDecl(ID);
6095
6096 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6097
6098 if (Index >= DeclsLoaded.size()) {
6099 assert(0 && "declaration ID out-of-range for AST file");
6100 Error("declaration ID out-of-range for AST file");
6101 return 0;
6102 }
6103
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 if (!DeclsLoaded[Index]) {
6105 ReadDeclRecord(ID);
6106 if (DeserializationListener)
6107 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6108 }
6109
6110 return DeclsLoaded[Index];
6111}
6112
6113DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6114 DeclID GlobalID) {
6115 if (GlobalID < NUM_PREDEF_DECL_IDS)
6116 return GlobalID;
6117
6118 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6119 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6120 ModuleFile *Owner = I->second;
6121
6122 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6123 = M.GlobalToLocalDeclIDs.find(Owner);
6124 if (Pos == M.GlobalToLocalDeclIDs.end())
6125 return 0;
6126
6127 return GlobalID - Owner->BaseDeclID + Pos->second;
6128}
6129
6130serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6131 const RecordData &Record,
6132 unsigned &Idx) {
6133 if (Idx >= Record.size()) {
6134 Error("Corrupted AST file");
6135 return 0;
6136 }
6137
6138 return getGlobalDeclID(F, Record[Idx++]);
6139}
6140
6141/// \brief Resolve the offset of a statement into a statement.
6142///
6143/// This operation will read a new statement from the external
6144/// source each time it is called, and is meant to be used via a
6145/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6146Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6147 // Switch case IDs are per Decl.
6148 ClearSwitchCaseIDs();
6149
6150 // Offset here is a global offset across the entire chain.
6151 RecordLocation Loc = getLocalBitOffset(Offset);
6152 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6153 return ReadStmtFromStream(*Loc.F);
6154}
6155
6156namespace {
6157 class FindExternalLexicalDeclsVisitor {
6158 ASTReader &Reader;
6159 const DeclContext *DC;
6160 bool (*isKindWeWant)(Decl::Kind);
6161
6162 SmallVectorImpl<Decl*> &Decls;
6163 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6164
6165 public:
6166 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6167 bool (*isKindWeWant)(Decl::Kind),
6168 SmallVectorImpl<Decl*> &Decls)
6169 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6170 {
6171 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6172 PredefsVisited[I] = false;
6173 }
6174
6175 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6176 if (Preorder)
6177 return false;
6178
6179 FindExternalLexicalDeclsVisitor *This
6180 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6181
6182 ModuleFile::DeclContextInfosMap::iterator Info
6183 = M.DeclContextInfos.find(This->DC);
6184 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6185 return false;
6186
6187 // Load all of the declaration IDs
6188 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6189 *IDE = ID + Info->second.NumLexicalDecls;
6190 ID != IDE; ++ID) {
6191 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6192 continue;
6193
6194 // Don't add predefined declarations to the lexical context more
6195 // than once.
6196 if (ID->second < NUM_PREDEF_DECL_IDS) {
6197 if (This->PredefsVisited[ID->second])
6198 continue;
6199
6200 This->PredefsVisited[ID->second] = true;
6201 }
6202
6203 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6204 if (!This->DC->isDeclInLexicalTraversal(D))
6205 This->Decls.push_back(D);
6206 }
6207 }
6208
6209 return false;
6210 }
6211 };
6212}
6213
6214ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6215 bool (*isKindWeWant)(Decl::Kind),
6216 SmallVectorImpl<Decl*> &Decls) {
6217 // There might be lexical decls in multiple modules, for the TU at
6218 // least. Walk all of the modules in the order they were loaded.
6219 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6220 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6221 ++NumLexicalDeclContextsRead;
6222 return ELR_Success;
6223}
6224
6225namespace {
6226
6227class DeclIDComp {
6228 ASTReader &Reader;
6229 ModuleFile &Mod;
6230
6231public:
6232 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6233
6234 bool operator()(LocalDeclID L, LocalDeclID R) const {
6235 SourceLocation LHS = getLocation(L);
6236 SourceLocation RHS = getLocation(R);
6237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6238 }
6239
6240 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6241 SourceLocation RHS = getLocation(R);
6242 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6243 }
6244
6245 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6246 SourceLocation LHS = getLocation(L);
6247 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6248 }
6249
6250 SourceLocation getLocation(LocalDeclID ID) const {
6251 return Reader.getSourceManager().getFileLoc(
6252 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6253 }
6254};
6255
6256}
6257
6258void ASTReader::FindFileRegionDecls(FileID File,
6259 unsigned Offset, unsigned Length,
6260 SmallVectorImpl<Decl *> &Decls) {
6261 SourceManager &SM = getSourceManager();
6262
6263 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6264 if (I == FileDeclIDs.end())
6265 return;
6266
6267 FileDeclsInfo &DInfo = I->second;
6268 if (DInfo.Decls.empty())
6269 return;
6270
6271 SourceLocation
6272 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6273 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6274
6275 DeclIDComp DIDComp(*this, *DInfo.Mod);
6276 ArrayRef<serialization::LocalDeclID>::iterator
6277 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6278 BeginLoc, DIDComp);
6279 if (BeginIt != DInfo.Decls.begin())
6280 --BeginIt;
6281
6282 // If we are pointing at a top-level decl inside an objc container, we need
6283 // to backtrack until we find it otherwise we will fail to report that the
6284 // region overlaps with an objc container.
6285 while (BeginIt != DInfo.Decls.begin() &&
6286 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6287 ->isTopLevelDeclInObjCContainer())
6288 --BeginIt;
6289
6290 ArrayRef<serialization::LocalDeclID>::iterator
6291 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292 EndLoc, DIDComp);
6293 if (EndIt != DInfo.Decls.end())
6294 ++EndIt;
6295
6296 for (ArrayRef<serialization::LocalDeclID>::iterator
6297 DIt = BeginIt; DIt != EndIt; ++DIt)
6298 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6299}
6300
6301namespace {
6302 /// \brief ModuleFile visitor used to perform name lookup into a
6303 /// declaration context.
6304 class DeclContextNameLookupVisitor {
6305 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006306 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 DeclarationName Name;
6308 SmallVectorImpl<NamedDecl *> &Decls;
6309
6310 public:
6311 DeclContextNameLookupVisitor(ASTReader &Reader,
6312 SmallVectorImpl<const DeclContext *> &Contexts,
6313 DeclarationName Name,
6314 SmallVectorImpl<NamedDecl *> &Decls)
6315 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6316
6317 static bool visit(ModuleFile &M, void *UserData) {
6318 DeclContextNameLookupVisitor *This
6319 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6320
6321 // Check whether we have any visible declaration information for
6322 // this context in this module.
6323 ModuleFile::DeclContextInfosMap::iterator Info;
6324 bool FoundInfo = false;
6325 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6326 Info = M.DeclContextInfos.find(This->Contexts[I]);
6327 if (Info != M.DeclContextInfos.end() &&
6328 Info->second.NameLookupTableData) {
6329 FoundInfo = true;
6330 break;
6331 }
6332 }
6333
6334 if (!FoundInfo)
6335 return false;
6336
6337 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006338 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 Info->second.NameLookupTableData;
6340 ASTDeclContextNameLookupTable::iterator Pos
6341 = LookupTable->find(This->Name);
6342 if (Pos == LookupTable->end())
6343 return false;
6344
6345 bool FoundAnything = false;
6346 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6347 for (; Data.first != Data.second; ++Data.first) {
6348 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6349 if (!ND)
6350 continue;
6351
6352 if (ND->getDeclName() != This->Name) {
6353 // A name might be null because the decl's redeclarable part is
6354 // currently read before reading its name. The lookup is triggered by
6355 // building that decl (likely indirectly), and so it is later in the
6356 // sense of "already existing" and can be ignored here.
6357 continue;
6358 }
6359
6360 // Record this declaration.
6361 FoundAnything = true;
6362 This->Decls.push_back(ND);
6363 }
6364
6365 return FoundAnything;
6366 }
6367 };
6368}
6369
Douglas Gregor9f782892013-01-21 15:25:38 +00006370/// \brief Retrieve the "definitive" module file for the definition of the
6371/// given declaration context, if there is one.
6372///
6373/// The "definitive" module file is the only place where we need to look to
6374/// find information about the declarations within the given declaration
6375/// context. For example, C++ and Objective-C classes, C structs/unions, and
6376/// Objective-C protocols, categories, and extensions are all defined in a
6377/// single place in the source code, so they have definitive module files
6378/// associated with them. C++ namespaces, on the other hand, can have
6379/// definitions in multiple different module files.
6380///
6381/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6382/// NDEBUG checking.
6383static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6384 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006385 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6386 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006387
6388 return 0;
6389}
6390
Richard Smith9ce12e32013-02-07 03:30:24 +00006391bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006392ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6393 DeclarationName Name) {
6394 assert(DC->hasExternalVisibleStorage() &&
6395 "DeclContext has no visible decls in storage");
6396 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006397 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006398
6399 SmallVector<NamedDecl *, 64> Decls;
6400
6401 // Compute the declaration contexts we need to look into. Multiple such
6402 // declaration contexts occur when two declaration contexts from disjoint
6403 // modules get merged, e.g., when two namespaces with the same name are
6404 // independently defined in separate modules.
6405 SmallVector<const DeclContext *, 2> Contexts;
6406 Contexts.push_back(DC);
6407
6408 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006409 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 if (Merged != MergedDecls.end()) {
6411 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6412 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6413 }
6414 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006415 if (isa<CXXRecordDecl>(DC)) {
6416 auto Merged = MergedLookups.find(DC);
6417 if (Merged != MergedLookups.end())
6418 Contexts.insert(Contexts.end(), Merged->second.begin(),
6419 Merged->second.end());
6420 }
6421
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006423
6424 // If we can definitively determine which module file to look into,
6425 // only look there. Otherwise, look in all module files.
6426 ModuleFile *Definitive;
6427 if (Contexts.size() == 1 &&
6428 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6429 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6430 } else {
6431 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 ++NumVisibleDeclContextsRead;
6434 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006435 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006436}
6437
6438namespace {
6439 /// \brief ModuleFile visitor used to retrieve all visible names in a
6440 /// declaration context.
6441 class DeclContextAllNamesVisitor {
6442 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006443 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006444 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006445 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006446
6447 public:
6448 DeclContextAllNamesVisitor(ASTReader &Reader,
6449 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006450 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006451 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006452
6453 static bool visit(ModuleFile &M, void *UserData) {
6454 DeclContextAllNamesVisitor *This
6455 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6456
6457 // Check whether we have any visible declaration information for
6458 // this context in this module.
6459 ModuleFile::DeclContextInfosMap::iterator Info;
6460 bool FoundInfo = false;
6461 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6462 Info = M.DeclContextInfos.find(This->Contexts[I]);
6463 if (Info != M.DeclContextInfos.end() &&
6464 Info->second.NameLookupTableData) {
6465 FoundInfo = true;
6466 break;
6467 }
6468 }
6469
6470 if (!FoundInfo)
6471 return false;
6472
Richard Smith52e3fba2014-03-11 07:17:35 +00006473 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 Info->second.NameLookupTableData;
6475 bool FoundAnything = false;
6476 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006477 I = LookupTable->data_begin(), E = LookupTable->data_end();
6478 I != E;
6479 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 ASTDeclContextNameLookupTrait::data_type Data = *I;
6481 for (; Data.first != Data.second; ++Data.first) {
6482 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6483 *Data.first);
6484 if (!ND)
6485 continue;
6486
6487 // Record this declaration.
6488 FoundAnything = true;
6489 This->Decls[ND->getDeclName()].push_back(ND);
6490 }
6491 }
6492
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006493 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 }
6495 };
6496}
6497
6498void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6499 if (!DC->hasExternalVisibleStorage())
6500 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006501 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006502
6503 // Compute the declaration contexts we need to look into. Multiple such
6504 // declaration contexts occur when two declaration contexts from disjoint
6505 // modules get merged, e.g., when two namespaces with the same name are
6506 // independently defined in separate modules.
6507 SmallVector<const DeclContext *, 2> Contexts;
6508 Contexts.push_back(DC);
6509
6510 if (DC->isNamespace()) {
6511 MergedDeclsMap::iterator Merged
6512 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6513 if (Merged != MergedDecls.end()) {
6514 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6515 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6516 }
6517 }
6518
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006519 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6520 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6522 ++NumVisibleDeclContextsRead;
6523
Craig Topper79be4cd2013-07-05 04:33:53 +00006524 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006525 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6526 }
6527 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6528}
6529
6530/// \brief Under non-PCH compilation the consumer receives the objc methods
6531/// before receiving the implementation, and codegen depends on this.
6532/// We simulate this by deserializing and passing to consumer the methods of the
6533/// implementation before passing the deserialized implementation decl.
6534static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6535 ASTConsumer *Consumer) {
6536 assert(ImplD && Consumer);
6537
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006538 for (auto *I : ImplD->methods())
6539 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006540
6541 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6542}
6543
6544void ASTReader::PassInterestingDeclsToConsumer() {
6545 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006546
6547 if (PassingDeclsToConsumer)
6548 return;
6549
6550 // Guard variable to avoid recursively redoing the process of passing
6551 // decls to consumer.
6552 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6553 true);
6554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 while (!InterestingDecls.empty()) {
6556 Decl *D = InterestingDecls.front();
6557 InterestingDecls.pop_front();
6558
6559 PassInterestingDeclToConsumer(D);
6560 }
6561}
6562
6563void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6564 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6565 PassObjCImplDeclToConsumer(ImplD, Consumer);
6566 else
6567 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6568}
6569
6570void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6571 this->Consumer = Consumer;
6572
6573 if (!Consumer)
6574 return;
6575
Ben Langmuir332aafe2014-01-31 01:06:56 +00006576 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006577 // Force deserialization of this decl, which will cause it to be queued for
6578 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006579 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006581 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006582
6583 PassInterestingDeclsToConsumer();
6584}
6585
6586void ASTReader::PrintStats() {
6587 std::fprintf(stderr, "*** AST File Statistics:\n");
6588
6589 unsigned NumTypesLoaded
6590 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6591 QualType());
6592 unsigned NumDeclsLoaded
6593 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6594 (Decl *)0);
6595 unsigned NumIdentifiersLoaded
6596 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6597 IdentifiersLoaded.end(),
6598 (IdentifierInfo *)0);
6599 unsigned NumMacrosLoaded
6600 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6601 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006602 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006603 unsigned NumSelectorsLoaded
6604 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6605 SelectorsLoaded.end(),
6606 Selector());
6607
6608 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6609 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6610 NumSLocEntriesRead, TotalNumSLocEntries,
6611 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6612 if (!TypesLoaded.empty())
6613 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6614 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6615 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6616 if (!DeclsLoaded.empty())
6617 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6618 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6619 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6620 if (!IdentifiersLoaded.empty())
6621 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6622 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6623 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6624 if (!MacrosLoaded.empty())
6625 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6626 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6627 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6628 if (!SelectorsLoaded.empty())
6629 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6630 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6631 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6632 if (TotalNumStatements)
6633 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6634 NumStatementsRead, TotalNumStatements,
6635 ((float)NumStatementsRead/TotalNumStatements * 100));
6636 if (TotalNumMacros)
6637 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6638 NumMacrosRead, TotalNumMacros,
6639 ((float)NumMacrosRead/TotalNumMacros * 100));
6640 if (TotalLexicalDeclContexts)
6641 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6642 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6643 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6644 * 100));
6645 if (TotalVisibleDeclContexts)
6646 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6647 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6648 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6649 * 100));
6650 if (TotalNumMethodPoolEntries) {
6651 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6652 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6653 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6654 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006656 if (NumMethodPoolLookups) {
6657 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6658 NumMethodPoolHits, NumMethodPoolLookups,
6659 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6660 }
6661 if (NumMethodPoolTableLookups) {
6662 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6663 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6664 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6665 * 100.0));
6666 }
6667
Douglas Gregor00a50f72013-01-25 00:38:33 +00006668 if (NumIdentifierLookupHits) {
6669 std::fprintf(stderr,
6670 " %u / %u identifier table lookups succeeded (%f%%)\n",
6671 NumIdentifierLookupHits, NumIdentifierLookups,
6672 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6673 }
6674
Douglas Gregore060e572013-01-25 01:03:03 +00006675 if (GlobalIndex) {
6676 std::fprintf(stderr, "\n");
6677 GlobalIndex->printStats();
6678 }
6679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 std::fprintf(stderr, "\n");
6681 dump();
6682 std::fprintf(stderr, "\n");
6683}
6684
6685template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6686static void
6687dumpModuleIDMap(StringRef Name,
6688 const ContinuousRangeMap<Key, ModuleFile *,
6689 InitialCapacity> &Map) {
6690 if (Map.begin() == Map.end())
6691 return;
6692
6693 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6694 llvm::errs() << Name << ":\n";
6695 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6696 I != IEnd; ++I) {
6697 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6698 << "\n";
6699 }
6700}
6701
6702void ASTReader::dump() {
6703 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6704 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6705 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6706 dumpModuleIDMap("Global type map", GlobalTypeMap);
6707 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6708 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6709 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6710 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6711 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6712 dumpModuleIDMap("Global preprocessed entity map",
6713 GlobalPreprocessedEntityMap);
6714
6715 llvm::errs() << "\n*** PCH/Modules Loaded:";
6716 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6717 MEnd = ModuleMgr.end();
6718 M != MEnd; ++M)
6719 (*M)->dump();
6720}
6721
6722/// Return the amount of memory used by memory buffers, breaking down
6723/// by heap-backed versus mmap'ed memory.
6724void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6725 for (ModuleConstIterator I = ModuleMgr.begin(),
6726 E = ModuleMgr.end(); I != E; ++I) {
6727 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6728 size_t bytes = buf->getBufferSize();
6729 switch (buf->getBufferKind()) {
6730 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6731 sizes.malloc_bytes += bytes;
6732 break;
6733 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6734 sizes.mmap_bytes += bytes;
6735 break;
6736 }
6737 }
6738 }
6739}
6740
6741void ASTReader::InitializeSema(Sema &S) {
6742 SemaObj = &S;
6743 S.addExternalSource(this);
6744
6745 // Makes sure any declarations that were deserialized "too early"
6746 // still get added to the identifier's declaration chains.
6747 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006748 pushExternalDeclIntoScope(PreloadedDecls[I],
6749 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 }
6751 PreloadedDecls.clear();
6752
Richard Smith3d8e97e2013-10-18 06:54:39 +00006753 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006754 if (!FPPragmaOptions.empty()) {
6755 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6756 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6757 }
6758
Richard Smith3d8e97e2013-10-18 06:54:39 +00006759 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 if (!OpenCLExtensions.empty()) {
6761 unsigned I = 0;
6762#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6763#include "clang/Basic/OpenCLExtensions.def"
6764
6765 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6766 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006767
6768 UpdateSema();
6769}
6770
6771void ASTReader::UpdateSema() {
6772 assert(SemaObj && "no Sema to update");
6773
6774 // Load the offsets of the declarations that Sema references.
6775 // They will be lazily deserialized when needed.
6776 if (!SemaDeclRefs.empty()) {
6777 assert(SemaDeclRefs.size() % 2 == 0);
6778 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6779 if (!SemaObj->StdNamespace)
6780 SemaObj->StdNamespace = SemaDeclRefs[I];
6781 if (!SemaObj->StdBadAlloc)
6782 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6783 }
6784 SemaDeclRefs.clear();
6785 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006786}
6787
6788IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6789 // Note that we are loading an identifier.
6790 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006791 StringRef Name(NameStart, NameEnd - NameStart);
6792
6793 // If there is a global index, look there first to determine which modules
6794 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006795 GlobalModuleIndex::HitSet Hits;
6796 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006797 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006798 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6799 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006800 }
6801 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006802 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006803 NumIdentifierLookups,
6804 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006805 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006806 IdentifierInfo *II = Visitor.getIdentifierInfo();
6807 markIdentifierUpToDate(II);
6808 return II;
6809}
6810
6811namespace clang {
6812 /// \brief An identifier-lookup iterator that enumerates all of the
6813 /// identifiers stored within a set of AST files.
6814 class ASTIdentifierIterator : public IdentifierIterator {
6815 /// \brief The AST reader whose identifiers are being enumerated.
6816 const ASTReader &Reader;
6817
6818 /// \brief The current index into the chain of AST files stored in
6819 /// the AST reader.
6820 unsigned Index;
6821
6822 /// \brief The current position within the identifier lookup table
6823 /// of the current AST file.
6824 ASTIdentifierLookupTable::key_iterator Current;
6825
6826 /// \brief The end position within the identifier lookup table of
6827 /// the current AST file.
6828 ASTIdentifierLookupTable::key_iterator End;
6829
6830 public:
6831 explicit ASTIdentifierIterator(const ASTReader &Reader);
6832
Craig Topper3e89dfe2014-03-13 02:13:41 +00006833 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 };
6835}
6836
6837ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6838 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6839 ASTIdentifierLookupTable *IdTable
6840 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6841 Current = IdTable->key_begin();
6842 End = IdTable->key_end();
6843}
6844
6845StringRef ASTIdentifierIterator::Next() {
6846 while (Current == End) {
6847 // If we have exhausted all of our AST files, we're done.
6848 if (Index == 0)
6849 return StringRef();
6850
6851 --Index;
6852 ASTIdentifierLookupTable *IdTable
6853 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6854 IdentifierLookupTable;
6855 Current = IdTable->key_begin();
6856 End = IdTable->key_end();
6857 }
6858
6859 // We have any identifiers remaining in the current AST file; return
6860 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006861 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006862 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006863 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006864}
6865
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006866IdentifierIterator *ASTReader::getIdentifiers() {
6867 if (!loadGlobalIndex())
6868 return GlobalIndex->createIdentifierIterator();
6869
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 return new ASTIdentifierIterator(*this);
6871}
6872
6873namespace clang { namespace serialization {
6874 class ReadMethodPoolVisitor {
6875 ASTReader &Reader;
6876 Selector Sel;
6877 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006878 unsigned InstanceBits;
6879 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006880 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6881 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006882
6883 public:
6884 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6885 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006886 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6887 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006888
6889 static bool visit(ModuleFile &M, void *UserData) {
6890 ReadMethodPoolVisitor *This
6891 = static_cast<ReadMethodPoolVisitor *>(UserData);
6892
6893 if (!M.SelectorLookupTable)
6894 return false;
6895
6896 // If we've already searched this module file, skip it now.
6897 if (M.Generation <= This->PriorGeneration)
6898 return true;
6899
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006900 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 ASTSelectorLookupTable *PoolTable
6902 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6903 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6904 if (Pos == PoolTable->end())
6905 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006906
6907 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 ++This->Reader.NumSelectorsRead;
6909 // FIXME: Not quite happy with the statistics here. We probably should
6910 // disable this tracking when called via LoadSelector.
6911 // Also, should entries without methods count as misses?
6912 ++This->Reader.NumMethodPoolEntriesRead;
6913 ASTSelectorLookupTrait::data_type Data = *Pos;
6914 if (This->Reader.DeserializationListener)
6915 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6916 This->Sel);
6917
6918 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6919 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006920 This->InstanceBits = Data.InstanceBits;
6921 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006922 return true;
6923 }
6924
6925 /// \brief Retrieve the instance methods found by this visitor.
6926 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6927 return InstanceMethods;
6928 }
6929
6930 /// \brief Retrieve the instance methods found by this visitor.
6931 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6932 return FactoryMethods;
6933 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006934
6935 unsigned getInstanceBits() const { return InstanceBits; }
6936 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 };
6938} } // end namespace clang::serialization
6939
6940/// \brief Add the given set of methods to the method list.
6941static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6942 ObjCMethodList &List) {
6943 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6944 S.addMethodToGlobalList(&List, Methods[I]);
6945 }
6946}
6947
6948void ASTReader::ReadMethodPool(Selector Sel) {
6949 // Get the selector generation and update it to the current generation.
6950 unsigned &Generation = SelectorGeneration[Sel];
6951 unsigned PriorGeneration = Generation;
6952 Generation = CurrentGeneration;
6953
6954 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006955 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6957 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6958
6959 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006960 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006962
6963 ++NumMethodPoolHits;
6964
Guy Benyei11169dd2012-12-18 14:30:41 +00006965 if (!getSema())
6966 return;
6967
6968 Sema &S = *getSema();
6969 Sema::GlobalMethodPool::iterator Pos
6970 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6971
6972 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6973 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006974 Pos->second.first.setBits(Visitor.getInstanceBits());
6975 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006976}
6977
6978void ASTReader::ReadKnownNamespaces(
6979 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6980 Namespaces.clear();
6981
6982 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6983 if (NamespaceDecl *Namespace
6984 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6985 Namespaces.push_back(Namespace);
6986 }
6987}
6988
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006989void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006990 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006991 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6992 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006993 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006994 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006995 Undefined.insert(std::make_pair(D, Loc));
6996 }
6997}
Nick Lewycky8334af82013-01-26 00:35:08 +00006998
Guy Benyei11169dd2012-12-18 14:30:41 +00006999void ASTReader::ReadTentativeDefinitions(
7000 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7001 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7002 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7003 if (Var)
7004 TentativeDefs.push_back(Var);
7005 }
7006 TentativeDefinitions.clear();
7007}
7008
7009void ASTReader::ReadUnusedFileScopedDecls(
7010 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7011 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7012 DeclaratorDecl *D
7013 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7014 if (D)
7015 Decls.push_back(D);
7016 }
7017 UnusedFileScopedDecls.clear();
7018}
7019
7020void ASTReader::ReadDelegatingConstructors(
7021 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7022 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7023 CXXConstructorDecl *D
7024 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7025 if (D)
7026 Decls.push_back(D);
7027 }
7028 DelegatingCtorDecls.clear();
7029}
7030
7031void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7032 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7033 TypedefNameDecl *D
7034 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7035 if (D)
7036 Decls.push_back(D);
7037 }
7038 ExtVectorDecls.clear();
7039}
7040
7041void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7042 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7043 CXXRecordDecl *D
7044 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7045 if (D)
7046 Decls.push_back(D);
7047 }
7048 DynamicClasses.clear();
7049}
7050
7051void
Richard Smith78165b52013-01-10 23:43:47 +00007052ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7053 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7054 NamedDecl *D
7055 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007056 if (D)
7057 Decls.push_back(D);
7058 }
Richard Smith78165b52013-01-10 23:43:47 +00007059 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007060}
7061
7062void ASTReader::ReadReferencedSelectors(
7063 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7064 if (ReferencedSelectorsData.empty())
7065 return;
7066
7067 // If there are @selector references added them to its pool. This is for
7068 // implementation of -Wselector.
7069 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7070 unsigned I = 0;
7071 while (I < DataSize) {
7072 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7073 SourceLocation SelLoc
7074 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7075 Sels.push_back(std::make_pair(Sel, SelLoc));
7076 }
7077 ReferencedSelectorsData.clear();
7078}
7079
7080void ASTReader::ReadWeakUndeclaredIdentifiers(
7081 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7082 if (WeakUndeclaredIdentifiers.empty())
7083 return;
7084
7085 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7086 IdentifierInfo *WeakId
7087 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7088 IdentifierInfo *AliasId
7089 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7090 SourceLocation Loc
7091 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7092 bool Used = WeakUndeclaredIdentifiers[I++];
7093 WeakInfo WI(AliasId, Loc);
7094 WI.setUsed(Used);
7095 WeakIDs.push_back(std::make_pair(WeakId, WI));
7096 }
7097 WeakUndeclaredIdentifiers.clear();
7098}
7099
7100void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7101 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7102 ExternalVTableUse VT;
7103 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7104 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7105 VT.DefinitionRequired = VTableUses[Idx++];
7106 VTables.push_back(VT);
7107 }
7108
7109 VTableUses.clear();
7110}
7111
7112void ASTReader::ReadPendingInstantiations(
7113 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7114 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7115 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7116 SourceLocation Loc
7117 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7118
7119 Pending.push_back(std::make_pair(D, Loc));
7120 }
7121 PendingInstantiations.clear();
7122}
7123
Richard Smithe40f2ba2013-08-07 21:41:30 +00007124void ASTReader::ReadLateParsedTemplates(
7125 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7126 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7127 /* In loop */) {
7128 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7129
7130 LateParsedTemplate *LT = new LateParsedTemplate;
7131 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7132
7133 ModuleFile *F = getOwningModuleFile(LT->D);
7134 assert(F && "No module");
7135
7136 unsigned TokN = LateParsedTemplates[Idx++];
7137 LT->Toks.reserve(TokN);
7138 for (unsigned T = 0; T < TokN; ++T)
7139 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7140
7141 LPTMap[FD] = LT;
7142 }
7143
7144 LateParsedTemplates.clear();
7145}
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147void ASTReader::LoadSelector(Selector Sel) {
7148 // It would be complicated to avoid reading the methods anyway. So don't.
7149 ReadMethodPool(Sel);
7150}
7151
7152void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7153 assert(ID && "Non-zero identifier ID required");
7154 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7155 IdentifiersLoaded[ID - 1] = II;
7156 if (DeserializationListener)
7157 DeserializationListener->IdentifierRead(ID, II);
7158}
7159
7160/// \brief Set the globally-visible declarations associated with the given
7161/// identifier.
7162///
7163/// If the AST reader is currently in a state where the given declaration IDs
7164/// cannot safely be resolved, they are queued until it is safe to resolve
7165/// them.
7166///
7167/// \param II an IdentifierInfo that refers to one or more globally-visible
7168/// declarations.
7169///
7170/// \param DeclIDs the set of declaration IDs with the name @p II that are
7171/// visible at global scope.
7172///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007173/// \param Decls if non-null, this vector will be populated with the set of
7174/// deserialized declarations. These declarations will not be pushed into
7175/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007176void
7177ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7178 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007179 SmallVectorImpl<Decl *> *Decls) {
7180 if (NumCurrentElementsDeserializing && !Decls) {
7181 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007182 return;
7183 }
7184
7185 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7186 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7187 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007188 // If we're simply supposed to record the declarations, do so now.
7189 if (Decls) {
7190 Decls->push_back(D);
7191 continue;
7192 }
7193
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 // Introduce this declaration into the translation-unit scope
7195 // and add it to the declaration chain for this identifier, so
7196 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007197 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007198 } else {
7199 // Queue this declaration so that it will be added to the
7200 // translation unit scope and identifier's declaration chain
7201 // once a Sema object is known.
7202 PreloadedDecls.push_back(D);
7203 }
7204 }
7205}
7206
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007207IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007208 if (ID == 0)
7209 return 0;
7210
7211 if (IdentifiersLoaded.empty()) {
7212 Error("no identifier table in AST file");
7213 return 0;
7214 }
7215
7216 ID -= 1;
7217 if (!IdentifiersLoaded[ID]) {
7218 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7219 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7220 ModuleFile *M = I->second;
7221 unsigned Index = ID - M->BaseIdentifierID;
7222 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7223
7224 // All of the strings in the AST file are preceded by a 16-bit length.
7225 // Extract that 16-bit length to avoid having to execute strlen().
7226 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7227 // unsigned integers. This is important to avoid integer overflow when
7228 // we cast them to 'unsigned'.
7229 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7230 unsigned StrLen = (((unsigned) StrLenPtr[0])
7231 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007232 IdentifiersLoaded[ID]
7233 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007234 if (DeserializationListener)
7235 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7236 }
7237
7238 return IdentifiersLoaded[ID];
7239}
7240
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007241IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7242 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007243}
7244
7245IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7246 if (LocalID < NUM_PREDEF_IDENT_IDS)
7247 return LocalID;
7248
7249 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7250 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7251 assert(I != M.IdentifierRemap.end()
7252 && "Invalid index into identifier index remap");
7253
7254 return LocalID + I->second;
7255}
7256
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007257MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 if (ID == 0)
7259 return 0;
7260
7261 if (MacrosLoaded.empty()) {
7262 Error("no macro table in AST file");
7263 return 0;
7264 }
7265
7266 ID -= NUM_PREDEF_MACRO_IDS;
7267 if (!MacrosLoaded[ID]) {
7268 GlobalMacroMapType::iterator I
7269 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7270 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7271 ModuleFile *M = I->second;
7272 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007273 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7274
7275 if (DeserializationListener)
7276 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7277 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007278 }
7279
7280 return MacrosLoaded[ID];
7281}
7282
7283MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7284 if (LocalID < NUM_PREDEF_MACRO_IDS)
7285 return LocalID;
7286
7287 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7288 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7289 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7290
7291 return LocalID + I->second;
7292}
7293
7294serialization::SubmoduleID
7295ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7296 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7297 return LocalID;
7298
7299 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7300 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7301 assert(I != M.SubmoduleRemap.end()
7302 && "Invalid index into submodule index remap");
7303
7304 return LocalID + I->second;
7305}
7306
7307Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7308 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7309 assert(GlobalID == 0 && "Unhandled global submodule ID");
7310 return 0;
7311 }
7312
7313 if (GlobalID > SubmodulesLoaded.size()) {
7314 Error("submodule ID out of range in AST file");
7315 return 0;
7316 }
7317
7318 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7319}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007320
7321Module *ASTReader::getModule(unsigned ID) {
7322 return getSubmodule(ID);
7323}
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7326 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7327}
7328
7329Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7330 if (ID == 0)
7331 return Selector();
7332
7333 if (ID > SelectorsLoaded.size()) {
7334 Error("selector ID out of range in AST file");
7335 return Selector();
7336 }
7337
7338 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7339 // Load this selector from the selector table.
7340 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7341 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7342 ModuleFile &M = *I->second;
7343 ASTSelectorLookupTrait Trait(*this, M);
7344 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7345 SelectorsLoaded[ID - 1] =
7346 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7347 if (DeserializationListener)
7348 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7349 }
7350
7351 return SelectorsLoaded[ID - 1];
7352}
7353
7354Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7355 return DecodeSelector(ID);
7356}
7357
7358uint32_t ASTReader::GetNumExternalSelectors() {
7359 // ID 0 (the null selector) is considered an external selector.
7360 return getTotalNumSelectors() + 1;
7361}
7362
7363serialization::SelectorID
7364ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7365 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7366 return LocalID;
7367
7368 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7369 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7370 assert(I != M.SelectorRemap.end()
7371 && "Invalid index into selector index remap");
7372
7373 return LocalID + I->second;
7374}
7375
7376DeclarationName
7377ASTReader::ReadDeclarationName(ModuleFile &F,
7378 const RecordData &Record, unsigned &Idx) {
7379 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7380 switch (Kind) {
7381 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007382 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007383
7384 case DeclarationName::ObjCZeroArgSelector:
7385 case DeclarationName::ObjCOneArgSelector:
7386 case DeclarationName::ObjCMultiArgSelector:
7387 return DeclarationName(ReadSelector(F, Record, Idx));
7388
7389 case DeclarationName::CXXConstructorName:
7390 return Context.DeclarationNames.getCXXConstructorName(
7391 Context.getCanonicalType(readType(F, Record, Idx)));
7392
7393 case DeclarationName::CXXDestructorName:
7394 return Context.DeclarationNames.getCXXDestructorName(
7395 Context.getCanonicalType(readType(F, Record, Idx)));
7396
7397 case DeclarationName::CXXConversionFunctionName:
7398 return Context.DeclarationNames.getCXXConversionFunctionName(
7399 Context.getCanonicalType(readType(F, Record, Idx)));
7400
7401 case DeclarationName::CXXOperatorName:
7402 return Context.DeclarationNames.getCXXOperatorName(
7403 (OverloadedOperatorKind)Record[Idx++]);
7404
7405 case DeclarationName::CXXLiteralOperatorName:
7406 return Context.DeclarationNames.getCXXLiteralOperatorName(
7407 GetIdentifierInfo(F, Record, Idx));
7408
7409 case DeclarationName::CXXUsingDirective:
7410 return DeclarationName::getUsingDirectiveName();
7411 }
7412
7413 llvm_unreachable("Invalid NameKind!");
7414}
7415
7416void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7417 DeclarationNameLoc &DNLoc,
7418 DeclarationName Name,
7419 const RecordData &Record, unsigned &Idx) {
7420 switch (Name.getNameKind()) {
7421 case DeclarationName::CXXConstructorName:
7422 case DeclarationName::CXXDestructorName:
7423 case DeclarationName::CXXConversionFunctionName:
7424 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7425 break;
7426
7427 case DeclarationName::CXXOperatorName:
7428 DNLoc.CXXOperatorName.BeginOpNameLoc
7429 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7430 DNLoc.CXXOperatorName.EndOpNameLoc
7431 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7432 break;
7433
7434 case DeclarationName::CXXLiteralOperatorName:
7435 DNLoc.CXXLiteralOperatorName.OpNameLoc
7436 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7437 break;
7438
7439 case DeclarationName::Identifier:
7440 case DeclarationName::ObjCZeroArgSelector:
7441 case DeclarationName::ObjCOneArgSelector:
7442 case DeclarationName::ObjCMultiArgSelector:
7443 case DeclarationName::CXXUsingDirective:
7444 break;
7445 }
7446}
7447
7448void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7449 DeclarationNameInfo &NameInfo,
7450 const RecordData &Record, unsigned &Idx) {
7451 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7452 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7453 DeclarationNameLoc DNLoc;
7454 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7455 NameInfo.setInfo(DNLoc);
7456}
7457
7458void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7459 const RecordData &Record, unsigned &Idx) {
7460 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7461 unsigned NumTPLists = Record[Idx++];
7462 Info.NumTemplParamLists = NumTPLists;
7463 if (NumTPLists) {
7464 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7465 for (unsigned i=0; i != NumTPLists; ++i)
7466 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7467 }
7468}
7469
7470TemplateName
7471ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7472 unsigned &Idx) {
7473 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7474 switch (Kind) {
7475 case TemplateName::Template:
7476 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7477
7478 case TemplateName::OverloadedTemplate: {
7479 unsigned size = Record[Idx++];
7480 UnresolvedSet<8> Decls;
7481 while (size--)
7482 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7483
7484 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7485 }
7486
7487 case TemplateName::QualifiedTemplate: {
7488 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7489 bool hasTemplKeyword = Record[Idx++];
7490 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7491 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7492 }
7493
7494 case TemplateName::DependentTemplate: {
7495 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7496 if (Record[Idx++]) // isIdentifier
7497 return Context.getDependentTemplateName(NNS,
7498 GetIdentifierInfo(F, Record,
7499 Idx));
7500 return Context.getDependentTemplateName(NNS,
7501 (OverloadedOperatorKind)Record[Idx++]);
7502 }
7503
7504 case TemplateName::SubstTemplateTemplateParm: {
7505 TemplateTemplateParmDecl *param
7506 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7507 if (!param) return TemplateName();
7508 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7509 return Context.getSubstTemplateTemplateParm(param, replacement);
7510 }
7511
7512 case TemplateName::SubstTemplateTemplateParmPack: {
7513 TemplateTemplateParmDecl *Param
7514 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7515 if (!Param)
7516 return TemplateName();
7517
7518 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7519 if (ArgPack.getKind() != TemplateArgument::Pack)
7520 return TemplateName();
7521
7522 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7523 }
7524 }
7525
7526 llvm_unreachable("Unhandled template name kind!");
7527}
7528
7529TemplateArgument
7530ASTReader::ReadTemplateArgument(ModuleFile &F,
7531 const RecordData &Record, unsigned &Idx) {
7532 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7533 switch (Kind) {
7534 case TemplateArgument::Null:
7535 return TemplateArgument();
7536 case TemplateArgument::Type:
7537 return TemplateArgument(readType(F, Record, Idx));
7538 case TemplateArgument::Declaration: {
7539 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7540 bool ForReferenceParam = Record[Idx++];
7541 return TemplateArgument(D, ForReferenceParam);
7542 }
7543 case TemplateArgument::NullPtr:
7544 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7545 case TemplateArgument::Integral: {
7546 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7547 QualType T = readType(F, Record, Idx);
7548 return TemplateArgument(Context, Value, T);
7549 }
7550 case TemplateArgument::Template:
7551 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7552 case TemplateArgument::TemplateExpansion: {
7553 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007554 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 if (unsigned NumExpansions = Record[Idx++])
7556 NumTemplateExpansions = NumExpansions - 1;
7557 return TemplateArgument(Name, NumTemplateExpansions);
7558 }
7559 case TemplateArgument::Expression:
7560 return TemplateArgument(ReadExpr(F));
7561 case TemplateArgument::Pack: {
7562 unsigned NumArgs = Record[Idx++];
7563 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7564 for (unsigned I = 0; I != NumArgs; ++I)
7565 Args[I] = ReadTemplateArgument(F, Record, Idx);
7566 return TemplateArgument(Args, NumArgs);
7567 }
7568 }
7569
7570 llvm_unreachable("Unhandled template argument kind!");
7571}
7572
7573TemplateParameterList *
7574ASTReader::ReadTemplateParameterList(ModuleFile &F,
7575 const RecordData &Record, unsigned &Idx) {
7576 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7577 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7578 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7579
7580 unsigned NumParams = Record[Idx++];
7581 SmallVector<NamedDecl *, 16> Params;
7582 Params.reserve(NumParams);
7583 while (NumParams--)
7584 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7585
7586 TemplateParameterList* TemplateParams =
7587 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7588 Params.data(), Params.size(), RAngleLoc);
7589 return TemplateParams;
7590}
7591
7592void
7593ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007594ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 ModuleFile &F, const RecordData &Record,
7596 unsigned &Idx) {
7597 unsigned NumTemplateArgs = Record[Idx++];
7598 TemplArgs.reserve(NumTemplateArgs);
7599 while (NumTemplateArgs--)
7600 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7601}
7602
7603/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007604void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 const RecordData &Record, unsigned &Idx) {
7606 unsigned NumDecls = Record[Idx++];
7607 Set.reserve(Context, NumDecls);
7608 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007609 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007611 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 }
7613}
7614
7615CXXBaseSpecifier
7616ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7617 const RecordData &Record, unsigned &Idx) {
7618 bool isVirtual = static_cast<bool>(Record[Idx++]);
7619 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7620 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7621 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7622 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7623 SourceRange Range = ReadSourceRange(F, Record, Idx);
7624 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7625 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7626 EllipsisLoc);
7627 Result.setInheritConstructors(inheritConstructors);
7628 return Result;
7629}
7630
7631std::pair<CXXCtorInitializer **, unsigned>
7632ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7633 unsigned &Idx) {
7634 CXXCtorInitializer **CtorInitializers = 0;
7635 unsigned NumInitializers = Record[Idx++];
7636 if (NumInitializers) {
7637 CtorInitializers
7638 = new (Context) CXXCtorInitializer*[NumInitializers];
7639 for (unsigned i=0; i != NumInitializers; ++i) {
7640 TypeSourceInfo *TInfo = 0;
7641 bool IsBaseVirtual = false;
7642 FieldDecl *Member = 0;
7643 IndirectFieldDecl *IndirectMember = 0;
7644
7645 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7646 switch (Type) {
7647 case CTOR_INITIALIZER_BASE:
7648 TInfo = GetTypeSourceInfo(F, Record, Idx);
7649 IsBaseVirtual = Record[Idx++];
7650 break;
7651
7652 case CTOR_INITIALIZER_DELEGATING:
7653 TInfo = GetTypeSourceInfo(F, Record, Idx);
7654 break;
7655
7656 case CTOR_INITIALIZER_MEMBER:
7657 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7658 break;
7659
7660 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7661 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7662 break;
7663 }
7664
7665 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7666 Expr *Init = ReadExpr(F);
7667 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7668 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7669 bool IsWritten = Record[Idx++];
7670 unsigned SourceOrderOrNumArrayIndices;
7671 SmallVector<VarDecl *, 8> Indices;
7672 if (IsWritten) {
7673 SourceOrderOrNumArrayIndices = Record[Idx++];
7674 } else {
7675 SourceOrderOrNumArrayIndices = Record[Idx++];
7676 Indices.reserve(SourceOrderOrNumArrayIndices);
7677 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7678 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7679 }
7680
7681 CXXCtorInitializer *BOMInit;
7682 if (Type == CTOR_INITIALIZER_BASE) {
7683 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7684 LParenLoc, Init, RParenLoc,
7685 MemberOrEllipsisLoc);
7686 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7687 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7688 Init, RParenLoc);
7689 } else if (IsWritten) {
7690 if (Member)
7691 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7692 LParenLoc, Init, RParenLoc);
7693 else
7694 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7695 MemberOrEllipsisLoc, LParenLoc,
7696 Init, RParenLoc);
7697 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007698 if (IndirectMember) {
7699 assert(Indices.empty() && "Indirect field improperly initialized");
7700 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7701 MemberOrEllipsisLoc, LParenLoc,
7702 Init, RParenLoc);
7703 } else {
7704 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7705 LParenLoc, Init, RParenLoc,
7706 Indices.data(), Indices.size());
7707 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 }
7709
7710 if (IsWritten)
7711 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7712 CtorInitializers[i] = BOMInit;
7713 }
7714 }
7715
7716 return std::make_pair(CtorInitializers, NumInitializers);
7717}
7718
7719NestedNameSpecifier *
7720ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7721 const RecordData &Record, unsigned &Idx) {
7722 unsigned N = Record[Idx++];
7723 NestedNameSpecifier *NNS = 0, *Prev = 0;
7724 for (unsigned I = 0; I != N; ++I) {
7725 NestedNameSpecifier::SpecifierKind Kind
7726 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7727 switch (Kind) {
7728 case NestedNameSpecifier::Identifier: {
7729 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7730 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7731 break;
7732 }
7733
7734 case NestedNameSpecifier::Namespace: {
7735 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7736 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7737 break;
7738 }
7739
7740 case NestedNameSpecifier::NamespaceAlias: {
7741 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7742 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7743 break;
7744 }
7745
7746 case NestedNameSpecifier::TypeSpec:
7747 case NestedNameSpecifier::TypeSpecWithTemplate: {
7748 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7749 if (!T)
7750 return 0;
7751
7752 bool Template = Record[Idx++];
7753 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7754 break;
7755 }
7756
7757 case NestedNameSpecifier::Global: {
7758 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7759 // No associated value, and there can't be a prefix.
7760 break;
7761 }
7762 }
7763 Prev = NNS;
7764 }
7765 return NNS;
7766}
7767
7768NestedNameSpecifierLoc
7769ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7770 unsigned &Idx) {
7771 unsigned N = Record[Idx++];
7772 NestedNameSpecifierLocBuilder Builder;
7773 for (unsigned I = 0; I != N; ++I) {
7774 NestedNameSpecifier::SpecifierKind Kind
7775 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7776 switch (Kind) {
7777 case NestedNameSpecifier::Identifier: {
7778 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7779 SourceRange Range = ReadSourceRange(F, Record, Idx);
7780 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7781 break;
7782 }
7783
7784 case NestedNameSpecifier::Namespace: {
7785 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7786 SourceRange Range = ReadSourceRange(F, Record, Idx);
7787 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7788 break;
7789 }
7790
7791 case NestedNameSpecifier::NamespaceAlias: {
7792 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7793 SourceRange Range = ReadSourceRange(F, Record, Idx);
7794 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7795 break;
7796 }
7797
7798 case NestedNameSpecifier::TypeSpec:
7799 case NestedNameSpecifier::TypeSpecWithTemplate: {
7800 bool Template = Record[Idx++];
7801 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7802 if (!T)
7803 return NestedNameSpecifierLoc();
7804 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7805
7806 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7807 Builder.Extend(Context,
7808 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7809 T->getTypeLoc(), ColonColonLoc);
7810 break;
7811 }
7812
7813 case NestedNameSpecifier::Global: {
7814 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7815 Builder.MakeGlobal(Context, ColonColonLoc);
7816 break;
7817 }
7818 }
7819 }
7820
7821 return Builder.getWithLocInContext(Context);
7822}
7823
7824SourceRange
7825ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7826 unsigned &Idx) {
7827 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7828 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7829 return SourceRange(beg, end);
7830}
7831
7832/// \brief Read an integral value
7833llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7834 unsigned BitWidth = Record[Idx++];
7835 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7836 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7837 Idx += NumWords;
7838 return Result;
7839}
7840
7841/// \brief Read a signed integral value
7842llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7843 bool isUnsigned = Record[Idx++];
7844 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7845}
7846
7847/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007848llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7849 const llvm::fltSemantics &Sem,
7850 unsigned &Idx) {
7851 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007852}
7853
7854// \brief Read a string
7855std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7856 unsigned Len = Record[Idx++];
7857 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7858 Idx += Len;
7859 return Result;
7860}
7861
7862VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7863 unsigned &Idx) {
7864 unsigned Major = Record[Idx++];
7865 unsigned Minor = Record[Idx++];
7866 unsigned Subminor = Record[Idx++];
7867 if (Minor == 0)
7868 return VersionTuple(Major);
7869 if (Subminor == 0)
7870 return VersionTuple(Major, Minor - 1);
7871 return VersionTuple(Major, Minor - 1, Subminor - 1);
7872}
7873
7874CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7875 const RecordData &Record,
7876 unsigned &Idx) {
7877 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7878 return CXXTemporary::Create(Context, Decl);
7879}
7880
7881DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007882 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007883}
7884
7885DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7886 return Diags.Report(Loc, DiagID);
7887}
7888
7889/// \brief Retrieve the identifier table associated with the
7890/// preprocessor.
7891IdentifierTable &ASTReader::getIdentifierTable() {
7892 return PP.getIdentifierTable();
7893}
7894
7895/// \brief Record that the given ID maps to the given switch-case
7896/// statement.
7897void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7898 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7899 "Already have a SwitchCase with this ID");
7900 (*CurrSwitchCaseStmts)[ID] = SC;
7901}
7902
7903/// \brief Retrieve the switch-case statement with the given ID.
7904SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7905 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7906 return (*CurrSwitchCaseStmts)[ID];
7907}
7908
7909void ASTReader::ClearSwitchCaseIDs() {
7910 CurrSwitchCaseStmts->clear();
7911}
7912
7913void ASTReader::ReadComments() {
7914 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007915 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007916 serialization::ModuleFile *> >::iterator
7917 I = CommentsCursors.begin(),
7918 E = CommentsCursors.end();
7919 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007920 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007921 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007922 serialization::ModuleFile &F = *I->second;
7923 SavedStreamPosition SavedPosition(Cursor);
7924
7925 RecordData Record;
7926 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007927 llvm::BitstreamEntry Entry =
7928 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007929
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007930 switch (Entry.Kind) {
7931 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7932 case llvm::BitstreamEntry::Error:
7933 Error("malformed block record in AST file");
7934 return;
7935 case llvm::BitstreamEntry::EndBlock:
7936 goto NextCursor;
7937 case llvm::BitstreamEntry::Record:
7938 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 }
7941
7942 // Read a record.
7943 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007944 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007945 case COMMENTS_RAW_COMMENT: {
7946 unsigned Idx = 0;
7947 SourceRange SR = ReadSourceRange(F, Record, Idx);
7948 RawComment::CommentKind Kind =
7949 (RawComment::CommentKind) Record[Idx++];
7950 bool IsTrailingComment = Record[Idx++];
7951 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007952 Comments.push_back(new (Context) RawComment(
7953 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7954 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 break;
7956 }
7957 }
7958 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007959 NextCursor:
7960 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007962}
7963
Richard Smithcd45dbc2014-04-19 03:48:30 +00007964std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7965 // If we know the owning module, use it.
7966 if (Module *M = D->getOwningModule())
7967 return M->getFullModuleName();
7968
7969 // Otherwise, use the name of the top-level module the decl is within.
7970 if (ModuleFile *M = getOwningModuleFile(D))
7971 return M->ModuleName;
7972
7973 // Not from a module.
7974 return "";
7975}
7976
Guy Benyei11169dd2012-12-18 14:30:41 +00007977void ASTReader::finishPendingActions() {
7978 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007979 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7980 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 // If any identifiers with corresponding top-level declarations have
7982 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007983 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7984 TopLevelDeclsMap;
7985 TopLevelDeclsMap TopLevelDecls;
7986
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007988 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007989 SmallVector<uint32_t, 4> DeclIDs =
7990 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007991 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007992
7993 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 // Load pending declaration chains.
7997 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7998 loadPendingDeclChain(PendingDeclChains[I]);
7999 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8000 }
8001 PendingDeclChains.clear();
8002
Douglas Gregor6168bd22013-02-18 15:53:43 +00008003 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008004 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8005 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008006 IdentifierInfo *II = TLD->first;
8007 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008008 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008009 }
8010 }
8011
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 // Load any pending macro definitions.
8013 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008014 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8015 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8016 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8017 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008018 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008019 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008020 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8021 if (Info.M->Kind != MK_Module)
8022 resolvePendingMacro(II, Info);
8023 }
8024 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008025 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008026 ++IDIdx) {
8027 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8028 if (Info.M->Kind == MK_Module)
8029 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 }
8031 }
8032 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008033
8034 // Wire up the DeclContexts for Decls that we delayed setting until
8035 // recursive loading is completed.
8036 while (!PendingDeclContextInfos.empty()) {
8037 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8038 PendingDeclContextInfos.pop_front();
8039 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8040 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8041 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8042 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008043
Richard Smithd1c46742014-04-30 02:24:17 +00008044 // Perform any pending declaration updates.
8045 while (!PendingUpdateRecords.empty()) {
8046 auto Update = PendingUpdateRecords.pop_back_val();
8047 ReadingKindTracker ReadingKind(Read_Decl, *this);
8048 loadDeclUpdateRecords(Update.first, Update.second);
8049 }
8050
Richard Smithcd45dbc2014-04-19 03:48:30 +00008051 // Trigger the import of the full definition of each class that had any
8052 // odr-merging problems, so we can produce better diagnostics for them.
8053 for (auto &Merge : PendingOdrMergeFailures) {
8054 Merge.first->buildLookup();
8055 Merge.first->decls_begin();
8056 Merge.first->bases_begin();
8057 Merge.first->vbases_begin();
8058 for (auto *RD : Merge.second) {
8059 RD->decls_begin();
8060 RD->bases_begin();
8061 RD->vbases_begin();
8062 }
8063 }
8064
Richard Smith2b9e3e32013-10-18 06:05:18 +00008065 // For each declaration from a merged context, check that the canonical
8066 // definition of that context also contains a declaration of the same
8067 // entity.
8068 while (!PendingOdrMergeChecks.empty()) {
8069 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8070
8071 // FIXME: Skip over implicit declarations for now. This matters for things
8072 // like implicitly-declared special member functions. This isn't entirely
8073 // correct; we can end up with multiple unmerged declarations of the same
8074 // implicit entity.
8075 if (D->isImplicit())
8076 continue;
8077
8078 DeclContext *CanonDef = D->getDeclContext();
8079 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8080
8081 bool Found = false;
8082 const Decl *DCanon = D->getCanonicalDecl();
8083
8084 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8085 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8086 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008087 for (auto RI : (*I)->redecls()) {
8088 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008089 // This declaration is present in the canonical definition. If it's
8090 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008091 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008092 Found = true;
8093 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008094 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008095 break;
8096 }
8097 }
8098 }
8099
8100 if (!Found) {
8101 D->setInvalidDecl();
8102
Richard Smithcd45dbc2014-04-19 03:48:30 +00008103 std::string CanonDefModule =
8104 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008105 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008106 << D << getOwningModuleNameForDiagnostic(D)
8107 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008108
8109 if (Candidates.empty())
8110 Diag(cast<Decl>(CanonDef)->getLocation(),
8111 diag::note_module_odr_violation_no_possible_decls) << D;
8112 else {
8113 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8114 Diag(Candidates[I]->getLocation(),
8115 diag::note_module_odr_violation_possible_decl)
8116 << Candidates[I];
8117 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008118
8119 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008120 }
8121 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 }
8123
8124 // If we deserialized any C++ or Objective-C class definitions, any
8125 // Objective-C protocol definitions, or any redeclarable templates, make sure
8126 // that all redeclarations point to the definitions. Note that this can only
8127 // happen now, after the redeclaration chains have been fully wired.
8128 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8129 DEnd = PendingDefinitions.end();
8130 D != DEnd; ++D) {
8131 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008132 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 // Make sure that the TagType points at the definition.
8134 const_cast<TagType*>(TagT)->decl = TD;
8135 }
8136
Aaron Ballman86c93902014-03-06 23:45:36 +00008137 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8138 for (auto R : RD->redecls())
8139 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008140
8141 }
8142
8143 continue;
8144 }
8145
Aaron Ballman86c93902014-03-06 23:45:36 +00008146 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 // Make sure that the ObjCInterfaceType points at the definition.
8148 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8149 ->Decl = ID;
8150
Aaron Ballman86c93902014-03-06 23:45:36 +00008151 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008152 R->Data = ID->Data;
8153
8154 continue;
8155 }
8156
Aaron Ballman86c93902014-03-06 23:45:36 +00008157 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8158 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 R->Data = PD->Data;
8160
8161 continue;
8162 }
8163
Aaron Ballman86c93902014-03-06 23:45:36 +00008164 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8165 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 R->Common = RTD->Common;
8167 }
8168 PendingDefinitions.clear();
8169
8170 // Load the bodies of any functions or methods we've encountered. We do
8171 // this now (delayed) so that we can be sure that the declaration chains
8172 // have been fully wired up.
8173 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8174 PBEnd = PendingBodies.end();
8175 PB != PBEnd; ++PB) {
8176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8177 // FIXME: Check for =delete/=default?
8178 // FIXME: Complain about ODR violations here?
8179 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8180 FD->setLazyBody(PB->second);
8181 continue;
8182 }
8183
8184 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8185 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8186 MD->setLazyBody(PB->second);
8187 }
8188 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008189
8190 // Issue any pending ODR-failure diagnostics.
8191 for (auto &Merge : PendingOdrMergeFailures) {
8192 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8193 continue;
8194
8195 bool Diagnosed = false;
8196 for (auto *RD : Merge.second) {
8197 // Multiple different declarations got merged together; tell the user
8198 // where they came from.
8199 if (Merge.first != RD) {
8200 // FIXME: Walk the definition, figure out what's different,
8201 // and diagnose that.
8202 if (!Diagnosed) {
8203 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8204 Diag(Merge.first->getLocation(),
8205 diag::err_module_odr_violation_different_definitions)
8206 << Merge.first << Module.empty() << Module;
8207 Diagnosed = true;
8208 }
8209
8210 Diag(RD->getLocation(),
8211 diag::note_module_odr_violation_different_definitions)
8212 << getOwningModuleNameForDiagnostic(RD);
8213 }
8214 }
8215
8216 if (!Diagnosed) {
8217 // All definitions are updates to the same declaration. This happens if a
8218 // module instantiates the declaration of a class template specialization
8219 // and two or more other modules instantiate its definition.
8220 //
8221 // FIXME: Indicate which modules had instantiations of this definition.
8222 // FIXME: How can this even happen?
8223 Diag(Merge.first->getLocation(),
8224 diag::err_module_odr_violation_different_instantiations)
8225 << Merge.first;
8226 }
8227 }
8228 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008229}
8230
8231void ASTReader::FinishedDeserializing() {
8232 assert(NumCurrentElementsDeserializing &&
8233 "FinishedDeserializing not paired with StartedDeserializing");
8234 if (NumCurrentElementsDeserializing == 1) {
8235 // We decrease NumCurrentElementsDeserializing only after pending actions
8236 // are finished, to avoid recursively re-calling finishPendingActions().
8237 finishPendingActions();
8238 }
8239 --NumCurrentElementsDeserializing;
8240
Richard Smith04d05b52014-03-23 00:27:18 +00008241 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8242 // We are not in recursive loading, so it's safe to pass the "interesting"
8243 // decls to the consumer.
8244 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 }
8246}
8247
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008248void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008249 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008250
8251 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8252 SemaObj->TUScope->AddDecl(D);
8253 } else if (SemaObj->TUScope) {
8254 // Adding the decl to IdResolver may have failed because it was already in
8255 // (even though it was not added in scope). If it is already in, make sure
8256 // it gets in the scope as well.
8257 if (std::find(SemaObj->IdResolver.begin(Name),
8258 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8259 SemaObj->TUScope->AddDecl(D);
8260 }
8261}
8262
Guy Benyei11169dd2012-12-18 14:30:41 +00008263ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8264 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008265 bool AllowASTWithCompilerErrors,
8266 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008267 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008268 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8270 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
8271 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
8272 Consumer(0), ModuleMgr(PP.getFileManager()),
8273 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008274 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008275 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008276 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00008277 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00008278 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8279 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008280 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
8281 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
8282 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008283 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8284 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8285 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8287 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8288 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8289 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00008290 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00008291{
8292 SourceMgr.setExternalSLocEntrySource(this);
8293}
8294
8295ASTReader::~ASTReader() {
8296 for (DeclContextVisibleUpdatesPending::iterator
8297 I = PendingVisibleUpdates.begin(),
8298 E = PendingVisibleUpdates.end();
8299 I != E; ++I) {
8300 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8301 F = I->second.end();
8302 J != F; ++J)
8303 delete J->first;
8304 }
8305}