blob: c6aec4592ba4d92186c4d4266fdcaf2dc011153e [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 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
223#undef CHECK_TARGET_OPT
224
225 // Compare feature sets.
226 SmallVector<StringRef, 4> ExistingFeatures(
227 ExistingTargetOpts.FeaturesAsWritten.begin(),
228 ExistingTargetOpts.FeaturesAsWritten.end());
229 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
230 TargetOpts.FeaturesAsWritten.end());
231 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
232 std::sort(ReadFeatures.begin(), ReadFeatures.end());
233
234 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
235 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
236 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
237 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
238 ++ExistingIdx;
239 ++ReadIdx;
240 continue;
241 }
242
243 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
244 if (Diags)
245 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
246 << false << ReadFeatures[ReadIdx];
247 return true;
248 }
249
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << true << ExistingFeatures[ExistingIdx];
253 return true;
254 }
255
256 if (ExistingIdx < ExistingN) {
257 if (Diags)
258 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
259 << true << ExistingFeatures[ExistingIdx];
260 return true;
261 }
262
263 if (ReadIdx < ReadN) {
264 if (Diags)
265 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
266 << false << ReadFeatures[ReadIdx];
267 return true;
268 }
269
270 return false;
271}
272
273bool
274PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
275 bool Complain) {
276 const LangOptions &ExistingLangOpts = PP.getLangOpts();
277 return checkLanguageOptions(LangOpts, ExistingLangOpts,
278 Complain? &Reader.Diags : 0);
279}
280
281bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
282 bool Complain) {
283 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
284 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
285 Complain? &Reader.Diags : 0);
286}
287
288namespace {
289 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
290 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000291 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
292 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
Ben Langmuirb92de022014-04-29 16:25:26 +0000295static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
296 DiagnosticsEngine &Diags,
297 bool Complain) {
298 typedef DiagnosticsEngine::Level Level;
299
300 // Check current mappings for new -Werror mappings, and the stored mappings
301 // for cases that were explicitly mapped to *not* be errors that are now
302 // errors because of options like -Werror.
303 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
304
305 for (DiagnosticsEngine *MappingSource : MappingSources) {
306 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
307 diag::kind DiagID = DiagIDMappingPair.first;
308 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
309 if (CurLevel < DiagnosticsEngine::Error)
310 continue; // not significant
311 Level StoredLevel =
312 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
313 if (StoredLevel < DiagnosticsEngine::Error) {
314 if (Complain)
315 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
316 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
317 return true;
318 }
319 }
320 }
321
322 return false;
323}
324
325static DiagnosticsEngine::ExtensionHandling
326isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
327 DiagnosticsEngine::ExtensionHandling Ext =
328 Diags.getExtensionHandlingBehavior();
329 if (Ext == DiagnosticsEngine::Ext_Warn && Diags.getWarningsAsErrors())
330 Ext = DiagnosticsEngine::Ext_Error;
331 return Ext;
332}
333
334static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
335 DiagnosticsEngine &Diags,
336 bool IsSystem, bool Complain) {
337 // Top-level options
338 if (IsSystem) {
339 if (Diags.getSuppressSystemWarnings())
340 return false;
341 // If -Wsystem-headers was not enabled before, be conservative
342 if (StoredDiags.getSuppressSystemWarnings()) {
343 if (Complain)
344 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
345 return true;
346 }
347 }
348
349 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
350 if (Complain)
351 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
352 return true;
353 }
354
355 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
356 !StoredDiags.getEnableAllWarnings()) {
357 if (Complain)
358 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
359 return true;
360 }
361
362 if (isExtHandlingFromDiagsError(Diags) &&
363 !isExtHandlingFromDiagsError(StoredDiags)) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
366 return true;
367 }
368
369 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
370}
371
372bool PCHValidator::ReadDiagnosticOptions(
373 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
374 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
375 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
376 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
377 new DiagnosticsEngine(DiagIDs, DiagOpts.getPtr()));
378 // This should never fail, because we would have processed these options
379 // before writing them to an ASTFile.
380 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
381
382 ModuleManager &ModuleMgr = Reader.getModuleManager();
383 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
384
385 // If the original import came from a file explicitly generated by the user,
386 // don't check the diagnostic mappings.
387 // FIXME: currently this is approximated by checking whether this is not a
388 // module import.
389 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
390 // the transitive closure of its imports, since unrelated modules cannot be
391 // imported until after this module finishes validation.
392 ModuleFile *TopImport = *ModuleMgr.rbegin();
393 while (!TopImport->ImportedBy.empty())
394 TopImport = TopImport->ImportedBy[0];
395 if (TopImport->Kind != MK_Module)
396 return false;
397
398 StringRef ModuleName = TopImport->ModuleName;
399 assert(!ModuleName.empty() && "diagnostic options read before module name");
400
401 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
402 assert(M && "missing module");
403
404 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
405 // contains the union of their flags.
406 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
407}
408
Guy Benyei11169dd2012-12-18 14:30:41 +0000409/// \brief Collect the macro definitions provided by the given preprocessor
410/// options.
411static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
412 MacroDefinitionsMap &Macros,
413 SmallVectorImpl<StringRef> *MacroNames = 0){
414 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
415 StringRef Macro = PPOpts.Macros[I].first;
416 bool IsUndef = PPOpts.Macros[I].second;
417
418 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
419 StringRef MacroName = MacroPair.first;
420 StringRef MacroBody = MacroPair.second;
421
422 // For an #undef'd macro, we only care about the name.
423 if (IsUndef) {
424 if (MacroNames && !Macros.count(MacroName))
425 MacroNames->push_back(MacroName);
426
427 Macros[MacroName] = std::make_pair("", true);
428 continue;
429 }
430
431 // For a #define'd macro, figure out the actual definition.
432 if (MacroName.size() == Macro.size())
433 MacroBody = "1";
434 else {
435 // Note: GCC drops anything following an end-of-line character.
436 StringRef::size_type End = MacroBody.find_first_of("\n\r");
437 MacroBody = MacroBody.substr(0, End);
438 }
439
440 if (MacroNames && !Macros.count(MacroName))
441 MacroNames->push_back(MacroName);
442 Macros[MacroName] = std::make_pair(MacroBody, false);
443 }
444}
445
446/// \brief Check the preprocessor options deserialized from the control block
447/// against the preprocessor options in an existing preprocessor.
448///
449/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
450static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
451 const PreprocessorOptions &ExistingPPOpts,
452 DiagnosticsEngine *Diags,
453 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000454 std::string &SuggestedPredefines,
455 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 // Check macro definitions.
457 MacroDefinitionsMap ASTFileMacros;
458 collectMacroDefinitions(PPOpts, ASTFileMacros);
459 MacroDefinitionsMap ExistingMacros;
460 SmallVector<StringRef, 4> ExistingMacroNames;
461 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
462
463 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
464 // Dig out the macro definition in the existing preprocessor options.
465 StringRef MacroName = ExistingMacroNames[I];
466 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
467
468 // Check whether we know anything about this macro name or not.
469 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
470 = ASTFileMacros.find(MacroName);
471 if (Known == ASTFileMacros.end()) {
472 // FIXME: Check whether this identifier was referenced anywhere in the
473 // AST file. If so, we should reject the AST file. Unfortunately, this
474 // information isn't in the control block. What shall we do about it?
475
476 if (Existing.second) {
477 SuggestedPredefines += "#undef ";
478 SuggestedPredefines += MacroName.str();
479 SuggestedPredefines += '\n';
480 } else {
481 SuggestedPredefines += "#define ";
482 SuggestedPredefines += MacroName.str();
483 SuggestedPredefines += ' ';
484 SuggestedPredefines += Existing.first.str();
485 SuggestedPredefines += '\n';
486 }
487 continue;
488 }
489
490 // If the macro was defined in one but undef'd in the other, we have a
491 // conflict.
492 if (Existing.second != Known->second.second) {
493 if (Diags) {
494 Diags->Report(diag::err_pch_macro_def_undef)
495 << MacroName << Known->second.second;
496 }
497 return true;
498 }
499
500 // If the macro was #undef'd in both, or if the macro bodies are identical,
501 // it's fine.
502 if (Existing.second || Existing.first == Known->second.first)
503 continue;
504
505 // The macro bodies differ; complain.
506 if (Diags) {
507 Diags->Report(diag::err_pch_macro_def_conflict)
508 << MacroName << Known->second.first << Existing.first;
509 }
510 return true;
511 }
512
513 // Check whether we're using predefines.
514 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
515 if (Diags) {
516 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
517 }
518 return true;
519 }
520
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000521 // Detailed record is important since it is used for the module cache hash.
522 if (LangOpts.Modules &&
523 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
524 if (Diags) {
525 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
526 }
527 return true;
528 }
529
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 // Compute the #include and #include_macros lines we need.
531 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
532 StringRef File = ExistingPPOpts.Includes[I];
533 if (File == ExistingPPOpts.ImplicitPCHInclude)
534 continue;
535
536 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
537 != PPOpts.Includes.end())
538 continue;
539
540 SuggestedPredefines += "#include \"";
541 SuggestedPredefines +=
542 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
543 SuggestedPredefines += "\"\n";
544 }
545
546 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
547 StringRef File = ExistingPPOpts.MacroIncludes[I];
548 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
549 File)
550 != PPOpts.MacroIncludes.end())
551 continue;
552
553 SuggestedPredefines += "#__include_macros \"";
554 SuggestedPredefines +=
555 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
556 SuggestedPredefines += "\"\n##\n";
557 }
558
559 return false;
560}
561
562bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
563 bool Complain,
564 std::string &SuggestedPredefines) {
565 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
566
567 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
568 Complain? &Reader.Diags : 0,
569 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000570 SuggestedPredefines,
571 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000572}
573
Guy Benyei11169dd2012-12-18 14:30:41 +0000574void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
575 PP.setCounterValue(Value);
576}
577
578//===----------------------------------------------------------------------===//
579// AST reader implementation
580//===----------------------------------------------------------------------===//
581
582void
583ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
584 DeserializationListener = Listener;
585}
586
587
588
589unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
590 return serialization::ComputeHash(Sel);
591}
592
593
594std::pair<unsigned, unsigned>
595ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000596 using namespace llvm::support;
597 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
598 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 return std::make_pair(KeyLen, DataLen);
600}
601
602ASTSelectorLookupTrait::internal_key_type
603ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000604 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000606 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
607 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
608 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 if (N == 0)
610 return SelTable.getNullarySelector(FirstII);
611 else if (N == 1)
612 return SelTable.getUnarySelector(FirstII);
613
614 SmallVector<IdentifierInfo *, 16> Args;
615 Args.push_back(FirstII);
616 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000617 Args.push_back(Reader.getLocalIdentifier(
618 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000619
620 return SelTable.getSelector(N, Args.data());
621}
622
623ASTSelectorLookupTrait::data_type
624ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
625 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000626 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000627
628 data_type Result;
629
Justin Bogner57ba0b22014-03-28 22:03:24 +0000630 Result.ID = Reader.getGlobalSelectorID(
631 F, endian::readNext<uint32_t, little, unaligned>(d));
632 unsigned NumInstanceMethodsAndBits =
633 endian::readNext<uint16_t, little, unaligned>(d);
634 unsigned NumFactoryMethodsAndBits =
635 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000636 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
637 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
638 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
639 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640
641 // Load instance methods
642 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000643 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
644 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 Result.Instance.push_back(Method);
646 }
647
648 // Load factory methods
649 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
651 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 Result.Factory.push_back(Method);
653 }
654
655 return Result;
656}
657
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000658unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
659 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660}
661
662std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000663ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000664 using namespace llvm::support;
665 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
666 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000667 return std::make_pair(KeyLen, DataLen);
668}
669
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000670ASTIdentifierLookupTraitBase::internal_key_type
671ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000672 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000673 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000674}
675
Douglas Gregordcf25082013-02-11 18:16:18 +0000676/// \brief Whether the given identifier is "interesting".
677static bool isInterestingIdentifier(IdentifierInfo &II) {
678 return II.isPoisoned() ||
679 II.isExtensionToken() ||
680 II.getObjCOrBuiltinID() ||
681 II.hasRevertedTokenIDToIdentifier() ||
682 II.hadMacroDefinition() ||
683 II.getFETokenInfo<void>();
684}
685
Guy Benyei11169dd2012-12-18 14:30:41 +0000686IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
687 const unsigned char* d,
688 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000689 using namespace llvm::support;
690 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 bool IsInteresting = RawID & 0x01;
692
693 // Wipe out the "is interesting" bit.
694 RawID = RawID >> 1;
695
696 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
697 if (!IsInteresting) {
698 // For uninteresting identifiers, just build the IdentifierInfo
699 // and associate it with the persistent ID.
700 IdentifierInfo *II = KnownII;
701 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000702 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000703 KnownII = II;
704 }
705 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000706 if (!II->isFromAST()) {
707 bool WasInteresting = isInterestingIdentifier(*II);
708 II->setIsFromAST();
709 if (WasInteresting)
710 II->setChangedSinceDeserialization();
711 }
712 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 return II;
714 }
715
Justin Bogner57ba0b22014-03-28 22:03:24 +0000716 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
717 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 bool CPlusPlusOperatorKeyword = Bits & 0x01;
719 Bits >>= 1;
720 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
721 Bits >>= 1;
722 bool Poisoned = Bits & 0x01;
723 Bits >>= 1;
724 bool ExtensionToken = Bits & 0x01;
725 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000726 bool hasSubmoduleMacros = Bits & 0x01;
727 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 bool hadMacroDefinition = Bits & 0x01;
729 Bits >>= 1;
730
731 assert(Bits == 0 && "Extra bits in the identifier?");
732 DataLen -= 8;
733
734 // Build the IdentifierInfo itself and link the identifier ID with
735 // the new IdentifierInfo.
736 IdentifierInfo *II = KnownII;
737 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 KnownII = II;
740 }
741 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000742 if (!II->isFromAST()) {
743 bool WasInteresting = isInterestingIdentifier(*II);
744 II->setIsFromAST();
745 if (WasInteresting)
746 II->setChangedSinceDeserialization();
747 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000748
749 // Set or check the various bits in the IdentifierInfo structure.
750 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000751 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 II->RevertTokenIDToIdentifier();
753 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
754 assert(II->isExtensionToken() == ExtensionToken &&
755 "Incorrect extension token flag");
756 (void)ExtensionToken;
757 if (Poisoned)
758 II->setIsPoisoned(true);
759 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
760 "Incorrect C++ operator keyword flag");
761 (void)CPlusPlusOperatorKeyword;
762
763 // If this identifier is a macro, deserialize the macro
764 // definition.
765 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 uint32_t MacroDirectivesOffset =
767 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000768 DataLen -= 4;
769 SmallVector<uint32_t, 8> LocalMacroIDs;
770 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000771 while (uint32_t LocalMacroID =
772 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000773 DataLen -= 4;
774 LocalMacroIDs.push_back(LocalMacroID);
775 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000776 DataLen -= 4;
777 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000778
779 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000780 // Macro definitions are stored from newest to oldest, so reverse them
781 // before registering them.
782 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000783 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000784 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
785 unsigned Size = 1;
786
787 static const uint32_t HasOverridesFlag = 0x80000000U;
788 if (I + 1 != E && (I[1] & HasOverridesFlag))
789 Size += 1 + (I[1] & ~HasOverridesFlag);
790
791 MacroSizes.push_back(Size);
792 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000793 }
Richard Smith49f906a2014-03-01 00:08:04 +0000794
795 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
796 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
797 SE = MacroSizes.rend();
798 SI != SE; ++SI) {
799 I -= *SI;
800
801 uint32_t LocalMacroID = *I;
802 llvm::ArrayRef<uint32_t> Overrides;
803 if (*SI != 1)
804 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
805 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
806 }
807 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000808 } else {
809 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
810 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000811 }
812
813 Reader.SetIdentifierInfo(ID, II);
814
815 // Read all of the declarations visible at global scope with this
816 // name.
817 if (DataLen > 0) {
818 SmallVector<uint32_t, 4> DeclIDs;
819 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 DeclIDs.push_back(Reader.getGlobalDeclID(
821 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 Reader.SetGloballyVisibleDecls(II, DeclIDs);
823 }
824
825 return II;
826}
827
828unsigned
829ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
830 llvm::FoldingSetNodeID ID;
831 ID.AddInteger(Key.Kind);
832
833 switch (Key.Kind) {
834 case DeclarationName::Identifier:
835 case DeclarationName::CXXLiteralOperatorName:
836 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
837 break;
838 case DeclarationName::ObjCZeroArgSelector:
839 case DeclarationName::ObjCOneArgSelector:
840 case DeclarationName::ObjCMultiArgSelector:
841 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
842 break;
843 case DeclarationName::CXXOperatorName:
844 ID.AddInteger((OverloadedOperatorKind)Key.Data);
845 break;
846 case DeclarationName::CXXConstructorName:
847 case DeclarationName::CXXDestructorName:
848 case DeclarationName::CXXConversionFunctionName:
849 case DeclarationName::CXXUsingDirective:
850 break;
851 }
852
853 return ID.ComputeHash();
854}
855
856ASTDeclContextNameLookupTrait::internal_key_type
857ASTDeclContextNameLookupTrait::GetInternalKey(
858 const external_key_type& Name) const {
859 DeclNameKey Key;
860 Key.Kind = Name.getNameKind();
861 switch (Name.getNameKind()) {
862 case DeclarationName::Identifier:
863 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
864 break;
865 case DeclarationName::ObjCZeroArgSelector:
866 case DeclarationName::ObjCOneArgSelector:
867 case DeclarationName::ObjCMultiArgSelector:
868 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
869 break;
870 case DeclarationName::CXXOperatorName:
871 Key.Data = Name.getCXXOverloadedOperator();
872 break;
873 case DeclarationName::CXXLiteralOperatorName:
874 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
875 break;
876 case DeclarationName::CXXConstructorName:
877 case DeclarationName::CXXDestructorName:
878 case DeclarationName::CXXConversionFunctionName:
879 case DeclarationName::CXXUsingDirective:
880 Key.Data = 0;
881 break;
882 }
883
884 return Key;
885}
886
887std::pair<unsigned, unsigned>
888ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000889 using namespace llvm::support;
890 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
891 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 return std::make_pair(KeyLen, DataLen);
893}
894
895ASTDeclContextNameLookupTrait::internal_key_type
896ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000897 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000898
899 DeclNameKey Key;
900 Key.Kind = (DeclarationName::NameKind)*d++;
901 switch (Key.Kind) {
902 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000903 Key.Data = (uint64_t)Reader.getLocalIdentifier(
904 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000905 break;
906 case DeclarationName::ObjCZeroArgSelector:
907 case DeclarationName::ObjCOneArgSelector:
908 case DeclarationName::ObjCMultiArgSelector:
909 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 (uint64_t)Reader.getLocalSelector(
911 F, endian::readNext<uint32_t, little, unaligned>(
912 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 break;
914 case DeclarationName::CXXOperatorName:
915 Key.Data = *d++; // OverloadedOperatorKind
916 break;
917 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::CXXConstructorName:
922 case DeclarationName::CXXDestructorName:
923 case DeclarationName::CXXConversionFunctionName:
924 case DeclarationName::CXXUsingDirective:
925 Key.Data = 0;
926 break;
927 }
928
929 return Key;
930}
931
932ASTDeclContextNameLookupTrait::data_type
933ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
934 const unsigned char* d,
935 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000936 using namespace llvm::support;
937 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000938 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
939 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 return std::make_pair(Start, Start + NumDecls);
941}
942
943bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000944 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 const std::pair<uint64_t, uint64_t> &Offsets,
946 DeclContextInfo &Info) {
947 SavedStreamPosition SavedPosition(Cursor);
948 // First the lexical decls.
949 if (Offsets.first != 0) {
950 Cursor.JumpToBit(Offsets.first);
951
952 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000953 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000955 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 if (RecCode != DECL_CONTEXT_LEXICAL) {
957 Error("Expected lexical block");
958 return true;
959 }
960
Chris Lattner0e6c9402013-01-20 02:38:54 +0000961 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
962 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 }
964
965 // Now the lookup table.
966 if (Offsets.second != 0) {
967 Cursor.JumpToBit(Offsets.second);
968
969 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000970 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000972 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 if (RecCode != DECL_CONTEXT_VISIBLE) {
974 Error("Expected visible lookup table block");
975 return true;
976 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000977 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
978 (const unsigned char *)Blob.data() + Record[0],
979 (const unsigned char *)Blob.data() + sizeof(uint32_t),
980 (const unsigned char *)Blob.data(),
981 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 }
983
984 return false;
985}
986
987void ASTReader::Error(StringRef Msg) {
988 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000989 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
990 Diag(diag::note_module_cache_path)
991 << PP.getHeaderSearchInfo().getModuleCachePath();
992 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000993}
994
995void ASTReader::Error(unsigned DiagID,
996 StringRef Arg1, StringRef Arg2) {
997 if (Diags.isDiagnosticInFlight())
998 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
999 else
1000 Diag(DiagID) << Arg1 << Arg2;
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// Source Manager Deserialization
1005//===----------------------------------------------------------------------===//
1006
1007/// \brief Read the line table in the source manager block.
1008/// \returns true if there was an error.
1009bool ASTReader::ParseLineTable(ModuleFile &F,
1010 SmallVectorImpl<uint64_t> &Record) {
1011 unsigned Idx = 0;
1012 LineTableInfo &LineTable = SourceMgr.getLineTable();
1013
1014 // Parse the file names
1015 std::map<int, int> FileIDs;
1016 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1017 // Extract the file name
1018 unsigned FilenameLen = Record[Idx++];
1019 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1020 Idx += FilenameLen;
1021 MaybeAddSystemRootToFilename(F, Filename);
1022 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1023 }
1024
1025 // Parse the line entries
1026 std::vector<LineEntry> Entries;
1027 while (Idx < Record.size()) {
1028 int FID = Record[Idx++];
1029 assert(FID >= 0 && "Serialized line entries for non-local file.");
1030 // Remap FileID from 1-based old view.
1031 FID += F.SLocEntryBaseID - 1;
1032
1033 // Extract the line entries
1034 unsigned NumEntries = Record[Idx++];
1035 assert(NumEntries && "Numentries is 00000");
1036 Entries.clear();
1037 Entries.reserve(NumEntries);
1038 for (unsigned I = 0; I != NumEntries; ++I) {
1039 unsigned FileOffset = Record[Idx++];
1040 unsigned LineNo = Record[Idx++];
1041 int FilenameID = FileIDs[Record[Idx++]];
1042 SrcMgr::CharacteristicKind FileKind
1043 = (SrcMgr::CharacteristicKind)Record[Idx++];
1044 unsigned IncludeOffset = Record[Idx++];
1045 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1046 FileKind, IncludeOffset));
1047 }
1048 LineTable.AddEntry(FileID::get(FID), Entries);
1049 }
1050
1051 return false;
1052}
1053
1054/// \brief Read a source manager block
1055bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1056 using namespace SrcMgr;
1057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001058 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001059
1060 // Set the source-location entry cursor to the current position in
1061 // the stream. This cursor will be used to read the contents of the
1062 // source manager block initially, and then lazily read
1063 // source-location entries as needed.
1064 SLocEntryCursor = F.Stream;
1065
1066 // The stream itself is going to skip over the source manager block.
1067 if (F.Stream.SkipBlock()) {
1068 Error("malformed block record in AST file");
1069 return true;
1070 }
1071
1072 // Enter the source manager block.
1073 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1074 Error("malformed source manager block record in AST file");
1075 return true;
1076 }
1077
1078 RecordData Record;
1079 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001080 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1081
1082 switch (E.Kind) {
1083 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1084 case llvm::BitstreamEntry::Error:
1085 Error("malformed block record in AST file");
1086 return true;
1087 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001088 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 case llvm::BitstreamEntry::Record:
1090 // The interesting case.
1091 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001092 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001093
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001096 StringRef Blob;
1097 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 default: // Default behavior: ignore.
1099 break;
1100
1101 case SM_SLOC_FILE_ENTRY:
1102 case SM_SLOC_BUFFER_ENTRY:
1103 case SM_SLOC_EXPANSION_ENTRY:
1104 // Once we hit one of the source location entries, we're done.
1105 return false;
1106 }
1107 }
1108}
1109
1110/// \brief If a header file is not found at the path that we expect it to be
1111/// and the PCH file was moved from its original location, try to resolve the
1112/// file by assuming that header+PCH were moved together and the header is in
1113/// the same place relative to the PCH.
1114static std::string
1115resolveFileRelativeToOriginalDir(const std::string &Filename,
1116 const std::string &OriginalDir,
1117 const std::string &CurrDir) {
1118 assert(OriginalDir != CurrDir &&
1119 "No point trying to resolve the file if the PCH dir didn't change");
1120 using namespace llvm::sys;
1121 SmallString<128> filePath(Filename);
1122 fs::make_absolute(filePath);
1123 assert(path::is_absolute(OriginalDir));
1124 SmallString<128> currPCHPath(CurrDir);
1125
1126 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1127 fileDirE = path::end(path::parent_path(filePath));
1128 path::const_iterator origDirI = path::begin(OriginalDir),
1129 origDirE = path::end(OriginalDir);
1130 // Skip the common path components from filePath and OriginalDir.
1131 while (fileDirI != fileDirE && origDirI != origDirE &&
1132 *fileDirI == *origDirI) {
1133 ++fileDirI;
1134 ++origDirI;
1135 }
1136 for (; origDirI != origDirE; ++origDirI)
1137 path::append(currPCHPath, "..");
1138 path::append(currPCHPath, fileDirI, fileDirE);
1139 path::append(currPCHPath, path::filename(Filename));
1140 return currPCHPath.str();
1141}
1142
1143bool ASTReader::ReadSLocEntry(int ID) {
1144 if (ID == 0)
1145 return false;
1146
1147 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1148 Error("source location entry ID out-of-range for AST file");
1149 return true;
1150 }
1151
1152 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1153 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001154 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 unsigned BaseOffset = F->SLocEntryBaseOffset;
1156
1157 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001158 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1159 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 Error("incorrectly-formatted source location entry in AST file");
1161 return true;
1162 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001163
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001165 StringRef Blob;
1166 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 default:
1168 Error("incorrectly-formatted source location entry in AST file");
1169 return true;
1170
1171 case SM_SLOC_FILE_ENTRY: {
1172 // We will detect whether a file changed and return 'Failure' for it, but
1173 // we will also try to fail gracefully by setting up the SLocEntry.
1174 unsigned InputID = Record[4];
1175 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001176 const FileEntry *File = IF.getFile();
1177 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001178
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001179 // Note that we only check if a File was returned. If it was out-of-date
1180 // we have complained but we will continue creating a FileID to recover
1181 // gracefully.
1182 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 return true;
1184
1185 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1186 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1187 // This is the module's main file.
1188 IncludeLoc = getImportLocation(F);
1189 }
1190 SrcMgr::CharacteristicKind
1191 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1192 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1193 ID, BaseOffset + Record[0]);
1194 SrcMgr::FileInfo &FileInfo =
1195 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1196 FileInfo.NumCreatedFIDs = Record[5];
1197 if (Record[3])
1198 FileInfo.setHasLineDirectives();
1199
1200 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1201 unsigned NumFileDecls = Record[7];
1202 if (NumFileDecls) {
1203 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1204 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1205 NumFileDecls));
1206 }
1207
1208 const SrcMgr::ContentCache *ContentCache
1209 = SourceMgr.getOrCreateContentCache(File,
1210 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1211 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1212 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1213 unsigned Code = SLocEntryCursor.ReadCode();
1214 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001215 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001216
1217 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1218 Error("AST record has invalid code");
1219 return true;
1220 }
1221
1222 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001223 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 SourceMgr.overrideFileContents(File, Buffer);
1225 }
1226
1227 break;
1228 }
1229
1230 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001231 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 unsigned Offset = Record[0];
1233 SrcMgr::CharacteristicKind
1234 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1235 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1236 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1237 IncludeLoc = getImportLocation(F);
1238 }
1239 unsigned Code = SLocEntryCursor.ReadCode();
1240 Record.clear();
1241 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001242 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001243
1244 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1245 Error("AST record has invalid code");
1246 return true;
1247 }
1248
1249 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1252 BaseOffset + Offset, IncludeLoc);
1253 break;
1254 }
1255
1256 case SM_SLOC_EXPANSION_ENTRY: {
1257 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1258 SourceMgr.createExpansionLoc(SpellingLoc,
1259 ReadSourceLocation(*F, Record[2]),
1260 ReadSourceLocation(*F, Record[3]),
1261 Record[4],
1262 ID,
1263 BaseOffset + Record[0]);
1264 break;
1265 }
1266 }
1267
1268 return false;
1269}
1270
1271std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1272 if (ID == 0)
1273 return std::make_pair(SourceLocation(), "");
1274
1275 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1276 Error("source location entry ID out-of-range for AST file");
1277 return std::make_pair(SourceLocation(), "");
1278 }
1279
1280 // Find which module file this entry lands in.
1281 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1282 if (M->Kind != MK_Module)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 // FIXME: Can we map this down to a particular submodule? That would be
1286 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001287 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001288}
1289
1290/// \brief Find the location where the module F is imported.
1291SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1292 if (F->ImportLoc.isValid())
1293 return F->ImportLoc;
1294
1295 // Otherwise we have a PCH. It's considered to be "imported" at the first
1296 // location of its includer.
1297 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001298 // Main file is the importer.
1299 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1300 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 return F->ImportedBy[0]->FirstLoc;
1303}
1304
1305/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1306/// specified cursor. Read the abbreviations that are at the top of the block
1307/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 if (Cursor.EnterSubBlock(BlockID)) {
1310 Error("malformed block record in AST file");
1311 return Failure;
1312 }
1313
1314 while (true) {
1315 uint64_t Offset = Cursor.GetCurrentBitNo();
1316 unsigned Code = Cursor.ReadCode();
1317
1318 // We expect all abbrevs to be at the start of the block.
1319 if (Code != llvm::bitc::DEFINE_ABBREV) {
1320 Cursor.JumpToBit(Offset);
1321 return false;
1322 }
1323 Cursor.ReadAbbrevRecord();
1324 }
1325}
1326
Richard Smithe40f2ba2013-08-07 21:41:30 +00001327Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001328 unsigned &Idx) {
1329 Token Tok;
1330 Tok.startToken();
1331 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1332 Tok.setLength(Record[Idx++]);
1333 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1334 Tok.setIdentifierInfo(II);
1335 Tok.setKind((tok::TokenKind)Record[Idx++]);
1336 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1337 return Tok;
1338}
1339
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001340MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001341 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001342
1343 // Keep track of where we are in the stream, then jump back there
1344 // after reading this macro.
1345 SavedStreamPosition SavedPosition(Stream);
1346
1347 Stream.JumpToBit(Offset);
1348 RecordData Record;
1349 SmallVector<IdentifierInfo*, 16> MacroArgs;
1350 MacroInfo *Macro = 0;
1351
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001353 // Advance to the next record, but if we get to the end of the block, don't
1354 // pop it (removing all the abbreviations from the cursor) since we want to
1355 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001356 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001357 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1358
1359 switch (Entry.Kind) {
1360 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1361 case llvm::BitstreamEntry::Error:
1362 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001363 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001365 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001366 case llvm::BitstreamEntry::Record:
1367 // The interesting case.
1368 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 }
1370
1371 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 Record.clear();
1373 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001374 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376 case PP_MACRO_DIRECTIVE_HISTORY:
1377 return Macro;
1378
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 case PP_MACRO_OBJECT_LIKE:
1380 case PP_MACRO_FUNCTION_LIKE: {
1381 // If we already have a macro, that means that we've hit the end
1382 // of the definition of the macro we were looking for. We're
1383 // done.
1384 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001385 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 unsigned NextIndex = 1; // Skip identifier ID.
1388 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001391 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001393 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1396 // Decode function-like macro info.
1397 bool isC99VarArgs = Record[NextIndex++];
1398 bool isGNUVarArgs = Record[NextIndex++];
1399 bool hasCommaPasting = Record[NextIndex++];
1400 MacroArgs.clear();
1401 unsigned NumArgs = Record[NextIndex++];
1402 for (unsigned i = 0; i != NumArgs; ++i)
1403 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1404
1405 // Install function-like macro info.
1406 MI->setIsFunctionLike();
1407 if (isC99VarArgs) MI->setIsC99Varargs();
1408 if (isGNUVarArgs) MI->setIsGNUVarargs();
1409 if (hasCommaPasting) MI->setHasCommaPasting();
1410 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1411 PP.getPreprocessorAllocator());
1412 }
1413
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 // Remember that we saw this macro last so that we add the tokens that
1415 // form its body to it.
1416 Macro = MI;
1417
1418 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1419 Record[NextIndex]) {
1420 // We have a macro definition. Register the association
1421 PreprocessedEntityID
1422 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1423 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001424 PreprocessingRecord::PPEntityID
1425 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1426 MacroDefinition *PPDef =
1427 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1428 if (PPDef)
1429 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 }
1431
1432 ++NumMacrosRead;
1433 break;
1434 }
1435
1436 case PP_TOKEN: {
1437 // If we see a TOKEN before a PP_MACRO_*, then the file is
1438 // erroneous, just pretend we didn't see this.
1439 if (Macro == 0) break;
1440
John McCallf413f5e2013-05-03 00:10:13 +00001441 unsigned Idx = 0;
1442 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 Macro->AddTokenToBody(Tok);
1444 break;
1445 }
1446 }
1447 }
1448}
1449
1450PreprocessedEntityID
1451ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1452 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1453 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1454 assert(I != M.PreprocessedEntityRemap.end()
1455 && "Invalid index into preprocessed entity index remap");
1456
1457 return LocalID + I->second;
1458}
1459
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001460unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1461 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001462}
1463
1464HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001465HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1466 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1467 FE->getName() };
1468 return ikey;
1469}
Guy Benyei11169dd2012-12-18 14:30:41 +00001470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1472 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 return false;
1474
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001475 if (strcmp(a.Filename, b.Filename) == 0)
1476 return true;
1477
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001479 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1481 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001482 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001483}
1484
1485std::pair<unsigned, unsigned>
1486HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001487 using namespace llvm::support;
1488 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001490 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001491}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492
1493HeaderFileInfoTrait::internal_key_type
1494HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001495 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001496 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001497 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1498 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001499 ikey.Filename = (const char *)d;
1500 return ikey;
1501}
1502
Guy Benyei11169dd2012-12-18 14:30:41 +00001503HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001504HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 unsigned DataLen) {
1506 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001507 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 HeaderFileInfo HFI;
1509 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001510 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1511 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 HFI.isImport = (Flags >> 5) & 0x01;
1513 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1514 HFI.DirInfo = (Flags >> 2) & 0x03;
1515 HFI.Resolved = (Flags >> 1) & 0x01;
1516 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1518 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1519 M, endian::readNext<uint32_t, little, unaligned>(d));
1520 if (unsigned FrameworkOffset =
1521 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 // The framework offset is 1 greater than the actual offset,
1523 // since 0 is used as an indicator for "no framework name".
1524 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1525 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1526 }
1527
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001528 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001530 if (LocalSMID) {
1531 // This header is part of a module. Associate it with the module to enable
1532 // implicit module import.
1533 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1534 Module *Mod = Reader.getSubmodule(GlobalSMID);
1535 HFI.isModuleHeader = true;
1536 FileManager &FileMgr = Reader.getFileManager();
1537 ModuleMap &ModMap =
1538 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001539 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001540 }
1541 }
1542
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1544 (void)End;
1545
1546 // This HeaderFileInfo was externally loaded.
1547 HFI.External = true;
1548 return HFI;
1549}
1550
Richard Smith49f906a2014-03-01 00:08:04 +00001551void
1552ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1553 GlobalMacroID GMacID,
1554 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001556 SubmoduleID *OverrideData = 0;
1557 if (!Overrides.empty()) {
1558 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1559 OverrideData[0] = Overrides.size();
1560 for (unsigned I = 0; I != Overrides.size(); ++I)
1561 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1562 }
1563 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001564}
1565
1566void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1567 ModuleFile *M,
1568 uint64_t MacroDirectivesOffset) {
1569 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1570 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001571}
1572
1573void ASTReader::ReadDefinedMacros() {
1574 // Note that we are loading defined macros.
1575 Deserializing Macros(this);
1576
1577 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1578 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001579 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001580
1581 // If there was no preprocessor block, skip this file.
1582 if (!MacroCursor.getBitStreamReader())
1583 continue;
1584
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001585 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 Cursor.JumpToBit((*I)->MacroStartOffset);
1587
1588 RecordData Record;
1589 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001590 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1591
1592 switch (E.Kind) {
1593 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1594 case llvm::BitstreamEntry::Error:
1595 Error("malformed block record in AST file");
1596 return;
1597 case llvm::BitstreamEntry::EndBlock:
1598 goto NextCursor;
1599
1600 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001601 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001602 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001603 default: // Default behavior: ignore.
1604 break;
1605
1606 case PP_MACRO_OBJECT_LIKE:
1607 case PP_MACRO_FUNCTION_LIKE:
1608 getLocalIdentifier(**I, Record[0]);
1609 break;
1610
1611 case PP_TOKEN:
1612 // Ignore tokens.
1613 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 break;
1616 }
1617 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 }
1620}
1621
1622namespace {
1623 /// \brief Visitor class used to look up identifirs in an AST file.
1624 class IdentifierLookupVisitor {
1625 StringRef Name;
1626 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001627 unsigned &NumIdentifierLookups;
1628 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001632 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1633 unsigned &NumIdentifierLookups,
1634 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001635 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001636 NumIdentifierLookups(NumIdentifierLookups),
1637 NumIdentifierLookupHits(NumIdentifierLookupHits),
1638 Found()
1639 {
1640 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001641
1642 static bool visit(ModuleFile &M, void *UserData) {
1643 IdentifierLookupVisitor *This
1644 = static_cast<IdentifierLookupVisitor *>(UserData);
1645
1646 // If we've already searched this module file, skip it now.
1647 if (M.Generation <= This->PriorGeneration)
1648 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001649
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 ASTIdentifierLookupTable *IdTable
1651 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1652 if (!IdTable)
1653 return false;
1654
1655 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1656 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001657 ++This->NumIdentifierLookups;
1658 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 if (Pos == IdTable->end())
1660 return false;
1661
1662 // Dereferencing the iterator has the effect of building the
1663 // IdentifierInfo node and populating it with the various
1664 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 This->Found = *Pos;
1667 return true;
1668 }
1669
1670 // \brief Retrieve the identifier info found within the module
1671 // files.
1672 IdentifierInfo *getIdentifierInfo() const { return Found; }
1673 };
1674}
1675
1676void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1677 // Note that we are loading an identifier.
1678 Deserializing AnIdentifier(this);
1679
1680 unsigned PriorGeneration = 0;
1681 if (getContext().getLangOpts().Modules)
1682 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001683
1684 // If there is a global index, look there first to determine which modules
1685 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001686 GlobalModuleIndex::HitSet Hits;
1687 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001688 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001689 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1690 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001691 }
1692 }
1693
Douglas Gregor7211ac12013-01-25 23:32:03 +00001694 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001695 NumIdentifierLookups,
1696 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001697 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 markIdentifierUpToDate(&II);
1699}
1700
1701void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1702 if (!II)
1703 return;
1704
1705 II->setOutOfDate(false);
1706
1707 // Update the generation for this identifier.
1708 if (getContext().getLangOpts().Modules)
1709 IdentifierGeneration[II] = CurrentGeneration;
1710}
1711
Richard Smith49f906a2014-03-01 00:08:04 +00001712struct ASTReader::ModuleMacroInfo {
1713 SubmoduleID SubModID;
1714 MacroInfo *MI;
1715 SubmoduleID *Overrides;
1716 // FIXME: Remove this.
1717 ModuleFile *F;
1718
1719 bool isDefine() const { return MI; }
1720
1721 SubmoduleID getSubmoduleID() const { return SubModID; }
1722
1723 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1724 if (!Overrides)
1725 return llvm::ArrayRef<SubmoduleID>();
1726 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1727 }
1728
1729 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1730 if (!MI)
1731 return 0;
1732 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1733 }
1734};
1735
1736ASTReader::ModuleMacroInfo *
1737ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1738 ModuleMacroInfo Info;
1739
1740 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1741 if (ID & 1) {
1742 // Macro undefinition.
1743 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1744 Info.MI = 0;
1745 } else {
1746 // Macro definition.
1747 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1748 assert(GMacID);
1749
1750 // If this macro has already been loaded, don't do so again.
1751 // FIXME: This is highly dubious. Multiple macro definitions can have the
1752 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1753 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1754 return 0;
1755
1756 Info.MI = getMacro(GMacID);
1757 Info.SubModID = Info.MI->getOwningModuleID();
1758 }
1759 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1760 Info.F = PMInfo.M;
1761
1762 return new (Context) ModuleMacroInfo(Info);
1763}
1764
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001765void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1766 const PendingMacroInfo &PMInfo) {
1767 assert(II);
1768
1769 if (PMInfo.M->Kind != MK_Module) {
1770 installPCHMacroDirectives(II, *PMInfo.M,
1771 PMInfo.PCHMacroData.MacroDirectivesOffset);
1772 return;
1773 }
Richard Smith49f906a2014-03-01 00:08:04 +00001774
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001775 // Module Macro.
1776
Richard Smith49f906a2014-03-01 00:08:04 +00001777 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1778 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001779 return;
1780
Richard Smith49f906a2014-03-01 00:08:04 +00001781 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1782 if (Owner && Owner->NameVisibility == Module::Hidden) {
1783 // Macros in the owning module are hidden. Just remember this macro to
1784 // install if we make this module visible.
1785 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1786 } else {
1787 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001789}
1790
1791void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1792 ModuleFile &M, uint64_t Offset) {
1793 assert(M.Kind != MK_Module);
1794
1795 BitstreamCursor &Cursor = M.MacroCursor;
1796 SavedStreamPosition SavedPosition(Cursor);
1797 Cursor.JumpToBit(Offset);
1798
1799 llvm::BitstreamEntry Entry =
1800 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1801 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1802 Error("malformed block record in AST file");
1803 return;
1804 }
1805
1806 RecordData Record;
1807 PreprocessorRecordTypes RecType =
1808 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1809 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1810 Error("malformed block record in AST file");
1811 return;
1812 }
1813
1814 // Deserialize the macro directives history in reverse source-order.
1815 MacroDirective *Latest = 0, *Earliest = 0;
1816 unsigned Idx = 0, N = Record.size();
1817 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001818 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001819 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001820 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1821 switch (K) {
1822 case MacroDirective::MD_Define: {
1823 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1824 MacroInfo *MI = getMacro(GMacID);
1825 bool isImported = Record[Idx++];
1826 bool isAmbiguous = Record[Idx++];
1827 DefMacroDirective *DefMD =
1828 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1829 DefMD->setAmbiguous(isAmbiguous);
1830 MD = DefMD;
1831 break;
1832 }
1833 case MacroDirective::MD_Undefine:
1834 MD = PP.AllocateUndefMacroDirective(Loc);
1835 break;
1836 case MacroDirective::MD_Visibility: {
1837 bool isPublic = Record[Idx++];
1838 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1839 break;
1840 }
1841 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001842
1843 if (!Latest)
1844 Latest = MD;
1845 if (Earliest)
1846 Earliest->setPrevious(MD);
1847 Earliest = MD;
1848 }
1849
1850 PP.setLoadedMacroDirective(II, Latest);
1851}
1852
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001853/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001854/// modules.
1855static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001856 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001857 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001858 Module *PrevOwner = 0;
1859 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1860 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001861 SourceManager &SrcMgr = Reader.getSourceManager();
1862 bool PrevInSystem
1863 = PrevOwner? PrevOwner->IsSystem
1864 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1865 bool NewInSystem
1866 = NewOwner? NewOwner->IsSystem
1867 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1868 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001869 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001870 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001871}
1872
Richard Smith49f906a2014-03-01 00:08:04 +00001873void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1874 AmbiguousMacros &Ambig,
1875 llvm::ArrayRef<SubmoduleID> Overrides) {
1876 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1877 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001878
Richard Smith49f906a2014-03-01 00:08:04 +00001879 // If this macro is not yet visible, remove it from the hidden names list.
1880 Module *Owner = getSubmodule(OwnerID);
1881 HiddenNames &Hidden = HiddenNamesMap[Owner];
1882 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1883 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001884 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001885 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001886 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001887 }
1888
1889 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001890 Ambig.erase(
1891 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1892 return MD->getInfo()->getOwningModuleID() == OwnerID;
1893 }),
1894 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001895 }
1896}
1897
1898ASTReader::AmbiguousMacros *
1899ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1900 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001901 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001902 if (!Prev && Overrides.empty())
1903 return 0;
1904
1905 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1906 if (PrevDef && PrevDef->isAmbiguous()) {
1907 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1908 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1909 Ambig.push_back(PrevDef);
1910
1911 removeOverriddenMacros(II, Ambig, Overrides);
1912
1913 if (!Ambig.empty())
1914 return &Ambig;
1915
1916 AmbiguousMacroDefs.erase(II);
1917 } else {
1918 // There's no ambiguity yet. Maybe we're introducing one.
1919 llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1920 if (PrevDef)
1921 Ambig.push_back(PrevDef);
1922
1923 removeOverriddenMacros(II, Ambig, Overrides);
1924
1925 if (!Ambig.empty()) {
1926 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1927 Result.swap(Ambig);
1928 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001929 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001930 }
Richard Smith49f906a2014-03-01 00:08:04 +00001931
1932 // We ended up with no ambiguity.
1933 return 0;
1934}
1935
1936void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1937 Module *Owner) {
1938 assert(II && Owner);
1939
1940 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1941 if (ImportLoc.isInvalid()) {
1942 // FIXME: If we made macros from this module visible but didn't provide a
1943 // source location for the import, we don't have a location for the macro.
1944 // Use the location at which the containing module file was first imported
1945 // for now.
1946 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001947 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001948 }
1949
1950 llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1951 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1952
1953
1954 // Create a synthetic macro definition corresponding to the import (or null
1955 // if this was an undefinition of the macro).
1956 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1957
1958 // If there's no ambiguity, just install the macro.
1959 if (!Prev) {
1960 if (MD)
1961 PP.appendMacroDirective(II, MD);
1962 else
1963 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1964 return;
1965 }
1966 assert(!Prev->empty());
1967
1968 if (!MD) {
1969 // We imported a #undef that didn't remove all prior definitions. The most
1970 // recent prior definition remains, and we install it in the place of the
1971 // imported directive.
1972 MacroInfo *NewMI = Prev->back()->getInfo();
1973 Prev->pop_back();
1974 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1975 }
1976
1977 // We're introducing a macro definition that creates or adds to an ambiguity.
1978 // We can resolve that ambiguity if this macro is token-for-token identical to
1979 // all of the existing definitions.
1980 MacroInfo *NewMI = MD->getInfo();
1981 assert(NewMI && "macro definition with no MacroInfo?");
1982 while (!Prev->empty()) {
1983 MacroInfo *PrevMI = Prev->back()->getInfo();
1984 assert(PrevMI && "macro definition with no MacroInfo?");
1985
1986 // Before marking the macros as ambiguous, check if this is a case where
1987 // both macros are in system headers. If so, we trust that the system
1988 // did not get it wrong. This also handles cases where Clang's own
1989 // headers have a different spelling of certain system macros:
1990 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1991 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1992 //
1993 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1994 // overrides the system limits.h's macros, so there's no conflict here.
1995 if (NewMI != PrevMI &&
1996 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1997 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1998 break;
1999
2000 // The previous definition is the same as this one (or both are defined in
2001 // system modules so we can assume they're equivalent); we don't need to
2002 // track it any more.
2003 Prev->pop_back();
2004 }
2005
2006 if (!Prev->empty())
2007 MD->setAmbiguous(true);
2008
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002009 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002010}
2011
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002012ASTReader::InputFileInfo
2013ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002014 // Go find this input file.
2015 BitstreamCursor &Cursor = F.InputFilesCursor;
2016 SavedStreamPosition SavedPosition(Cursor);
2017 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2018
2019 unsigned Code = Cursor.ReadCode();
2020 RecordData Record;
2021 StringRef Blob;
2022
2023 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2024 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2025 "invalid record type for input file");
2026 (void)Result;
2027
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002028 std::string Filename;
2029 off_t StoredSize;
2030 time_t StoredTime;
2031 bool Overridden;
2032
Ben Langmuir198c1682014-03-07 07:27:49 +00002033 assert(Record[0] == ID && "Bogus stored ID or offset");
2034 StoredSize = static_cast<off_t>(Record[1]);
2035 StoredTime = static_cast<time_t>(Record[2]);
2036 Overridden = static_cast<bool>(Record[3]);
2037 Filename = Blob;
2038 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002039
Hans Wennborg73945142014-03-14 17:45:06 +00002040 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2041 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002042}
2043
2044std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002045 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002046}
2047
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002048InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002049 // If this ID is bogus, just return an empty input file.
2050 if (ID == 0 || ID > F.InputFilesLoaded.size())
2051 return InputFile();
2052
2053 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002054 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002055 return F.InputFilesLoaded[ID-1];
2056
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002057 if (F.InputFilesLoaded[ID-1].isNotFound())
2058 return InputFile();
2059
Guy Benyei11169dd2012-12-18 14:30:41 +00002060 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002061 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 SavedStreamPosition SavedPosition(Cursor);
2063 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2064
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002065 InputFileInfo FI = readInputFileInfo(F, ID);
2066 off_t StoredSize = FI.StoredSize;
2067 time_t StoredTime = FI.StoredTime;
2068 bool Overridden = FI.Overridden;
2069 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002070
Ben Langmuir198c1682014-03-07 07:27:49 +00002071 const FileEntry *File
2072 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2073 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2074
2075 // If we didn't find the file, resolve it relative to the
2076 // original directory from which this AST file was created.
2077 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2078 F.OriginalDir != CurrentDir) {
2079 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2080 F.OriginalDir,
2081 CurrentDir);
2082 if (!Resolved.empty())
2083 File = FileMgr.getFile(Resolved);
2084 }
2085
2086 // For an overridden file, create a virtual file with the stored
2087 // size/timestamp.
2088 if (Overridden && File == 0) {
2089 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2090 }
2091
2092 if (File == 0) {
2093 if (Complain) {
2094 std::string ErrorStr = "could not find file '";
2095 ErrorStr += Filename;
2096 ErrorStr += "' referenced by AST file";
2097 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002099 // Record that we didn't find the file.
2100 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2101 return InputFile();
2102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002103
Ben Langmuir198c1682014-03-07 07:27:49 +00002104 // Check if there was a request to override the contents of the file
2105 // that was part of the precompiled header. Overridding such a file
2106 // can lead to problems when lexing using the source locations from the
2107 // PCH.
2108 SourceManager &SM = getSourceManager();
2109 if (!Overridden && SM.isFileOverridden(File)) {
2110 if (Complain)
2111 Error(diag::err_fe_pch_file_overridden, Filename);
2112 // After emitting the diagnostic, recover by disabling the override so
2113 // that the original file will be used.
2114 SM.disableFileContentsOverride(File);
2115 // The FileEntry is a virtual file entry with the size of the contents
2116 // that would override the original contents. Set it to the original's
2117 // size/time.
2118 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2119 StoredSize, StoredTime);
2120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002121
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 bool IsOutOfDate = false;
2123
2124 // For an overridden file, there is nothing to validate.
2125 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002126#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002127 // In our regression testing, the Windows file system seems to
2128 // have inconsistent modification times that sometimes
2129 // erroneously trigger this error-handling path.
2130 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002131#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002132 )) {
2133 if (Complain) {
2134 // Build a list of the PCH imports that got us here (in reverse).
2135 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2136 while (ImportStack.back()->ImportedBy.size() > 0)
2137 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002138
Ben Langmuir198c1682014-03-07 07:27:49 +00002139 // The top-level PCH is stale.
2140 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2141 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002142
Ben Langmuir198c1682014-03-07 07:27:49 +00002143 // Print the import stack.
2144 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2145 Diag(diag::note_pch_required_by)
2146 << Filename << ImportStack[0]->FileName;
2147 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002148 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002150 }
2151
Ben Langmuir198c1682014-03-07 07:27:49 +00002152 if (!Diags.isDiagnosticInFlight())
2153 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 }
2155
Ben Langmuir198c1682014-03-07 07:27:49 +00002156 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002157 }
2158
Ben Langmuir198c1682014-03-07 07:27:49 +00002159 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2160
2161 // Note that we've loaded this input file.
2162 F.InputFilesLoaded[ID-1] = IF;
2163 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002164}
2165
2166const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2167 ModuleFile &M = ModuleMgr.getPrimaryModule();
2168 std::string Filename = filenameStrRef;
2169 MaybeAddSystemRootToFilename(M, Filename);
2170 const FileEntry *File = FileMgr.getFile(Filename);
2171 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2172 M.OriginalDir != CurrentDir) {
2173 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2174 M.OriginalDir,
2175 CurrentDir);
2176 if (!resolved.empty())
2177 File = FileMgr.getFile(resolved);
2178 }
2179
2180 return File;
2181}
2182
2183/// \brief If we are loading a relocatable PCH file, and the filename is
2184/// not an absolute path, add the system root to the beginning of the file
2185/// name.
2186void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2187 std::string &Filename) {
2188 // If this is not a relocatable PCH file, there's nothing to do.
2189 if (!M.RelocatablePCH)
2190 return;
2191
2192 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2193 return;
2194
2195 if (isysroot.empty()) {
2196 // If no system root was given, default to '/'
2197 Filename.insert(Filename.begin(), '/');
2198 return;
2199 }
2200
2201 unsigned Length = isysroot.size();
2202 if (isysroot[Length - 1] != '/')
2203 Filename.insert(Filename.begin(), '/');
2204
2205 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2206}
2207
2208ASTReader::ASTReadResult
2209ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002210 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002211 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002213 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002214
2215 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2216 Error("malformed block record in AST file");
2217 return Failure;
2218 }
2219
2220 // Read all of the records and blocks in the control block.
2221 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002222 while (1) {
2223 llvm::BitstreamEntry Entry = Stream.advance();
2224
2225 switch (Entry.Kind) {
2226 case llvm::BitstreamEntry::Error:
2227 Error("malformed block record in AST file");
2228 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002229 case llvm::BitstreamEntry::EndBlock: {
2230 // Validate input files.
2231 const HeaderSearchOptions &HSOpts =
2232 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002233
2234 // All user input files reside at the index range [0, Record[1]), and
2235 // system input files reside at [Record[1], Record[0]).
2236 // Record is the one from INPUT_FILE_OFFSETS.
2237 unsigned NumInputs = Record[0];
2238 unsigned NumUserInputs = Record[1];
2239
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002240 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002241 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002242 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002244
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002245 // If we are reading a module, we will create a verification timestamp,
2246 // so we verify all input files. Otherwise, verify only user input
2247 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002248
2249 unsigned N = NumUserInputs;
2250 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002251 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2252 N = NumInputs;
2253
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002254 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002255 InputFile IF = getInputFile(F, I+1, Complain);
2256 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002260
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002261 if (Listener)
2262 Listener->visitModuleFile(F.FileName);
2263
Ben Langmuircb69b572014-03-07 06:40:32 +00002264 if (Listener && Listener->needsInputFileVisitation()) {
2265 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2266 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002267 for (unsigned I = 0; I < N; ++I) {
2268 bool IsSystem = I >= NumUserInputs;
2269 InputFileInfo FI = readInputFileInfo(F, I+1);
2270 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2271 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002272 }
2273
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002275 }
2276
Chris Lattnere7b154b2013-01-19 21:39:22 +00002277 case llvm::BitstreamEntry::SubBlock:
2278 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 case INPUT_FILES_BLOCK_ID:
2280 F.InputFilesCursor = Stream;
2281 if (Stream.SkipBlock() || // Skip with the main cursor
2282 // Read the abbreviations
2283 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2284 Error("malformed block record in AST file");
2285 return Failure;
2286 }
2287 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002288
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002290 if (Stream.SkipBlock()) {
2291 Error("malformed block record in AST file");
2292 return Failure;
2293 }
2294 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002296
2297 case llvm::BitstreamEntry::Record:
2298 // The interesting case.
2299 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 }
2301
2302 // Read and process a record.
2303 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002304 StringRef Blob;
2305 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 case METADATA: {
2307 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2308 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002309 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2310 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 return VersionMismatch;
2312 }
2313
2314 bool hasErrors = Record[5];
2315 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2316 Diag(diag::err_pch_with_compiler_errors);
2317 return HadErrors;
2318 }
2319
2320 F.RelocatablePCH = Record[4];
2321
2322 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002323 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2325 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002326 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 return VersionMismatch;
2328 }
2329 break;
2330 }
2331
2332 case IMPORTS: {
2333 // Load each of the imported PCH files.
2334 unsigned Idx = 0, N = Record.size();
2335 while (Idx < N) {
2336 // Read information about the AST file.
2337 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2338 // The import location will be the local one for now; we will adjust
2339 // all import locations of module imports after the global source
2340 // location info are setup.
2341 SourceLocation ImportLoc =
2342 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002343 off_t StoredSize = (off_t)Record[Idx++];
2344 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 unsigned Length = Record[Idx++];
2346 SmallString<128> ImportedFile(Record.begin() + Idx,
2347 Record.begin() + Idx + Length);
2348 Idx += Length;
2349
2350 // Load the AST file.
2351 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002352 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 ClientLoadCapabilities)) {
2354 case Failure: return Failure;
2355 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002356 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 case OutOfDate: return OutOfDate;
2358 case VersionMismatch: return VersionMismatch;
2359 case ConfigurationMismatch: return ConfigurationMismatch;
2360 case HadErrors: return HadErrors;
2361 case Success: break;
2362 }
2363 }
2364 break;
2365 }
2366
2367 case LANGUAGE_OPTIONS: {
2368 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2369 if (Listener && &F == *ModuleMgr.begin() &&
2370 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002371 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 return ConfigurationMismatch;
2373 break;
2374 }
2375
2376 case TARGET_OPTIONS: {
2377 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2378 if (Listener && &F == *ModuleMgr.begin() &&
2379 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002380 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 return ConfigurationMismatch;
2382 break;
2383 }
2384
2385 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002386 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 if (Listener && &F == *ModuleMgr.begin() &&
2388 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002389 !DisableValidation)
2390 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 break;
2392 }
2393
2394 case FILE_SYSTEM_OPTIONS: {
2395 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2396 if (Listener && &F == *ModuleMgr.begin() &&
2397 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002398 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 return ConfigurationMismatch;
2400 break;
2401 }
2402
2403 case HEADER_SEARCH_OPTIONS: {
2404 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2405 if (Listener && &F == *ModuleMgr.begin() &&
2406 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002407 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 return ConfigurationMismatch;
2409 break;
2410 }
2411
2412 case PREPROCESSOR_OPTIONS: {
2413 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2414 if (Listener && &F == *ModuleMgr.begin() &&
2415 ParsePreprocessorOptions(Record, Complain, *Listener,
2416 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002417 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 return ConfigurationMismatch;
2419 break;
2420 }
2421
2422 case ORIGINAL_FILE:
2423 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002424 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2426 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2427 break;
2428
2429 case ORIGINAL_FILE_ID:
2430 F.OriginalSourceFileID = FileID::get(Record[0]);
2431 break;
2432
2433 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002434 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 break;
2436
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002437 case MODULE_NAME:
2438 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002439 if (Listener)
2440 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002441 break;
2442
2443 case MODULE_MAP_FILE:
2444 F.ModuleMapPath = Blob;
2445
2446 // Try to resolve ModuleName in the current header search context and
2447 // verify that it is found in the same module map file as we saved. If the
2448 // top-level AST file is a main file, skip this check because there is no
2449 // usable header search context.
2450 assert(!F.ModuleName.empty() &&
2451 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2452 if (F.Kind == MK_Module &&
2453 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2454 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2455 if (!M) {
2456 assert(ImportedBy && "top-level import should be verified");
2457 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2458 Diag(diag::err_imported_module_not_found)
2459 << F.ModuleName << ImportedBy->FileName;
2460 return Missing;
2461 }
2462
2463 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2464 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2465 assert(M->ModuleMap && "found module is missing module map file");
2466 assert(M->Name == F.ModuleName && "found module with different name");
2467 assert(ImportedBy && "top-level import should be verified");
2468 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2469 Diag(diag::err_imported_module_modmap_changed)
2470 << F.ModuleName << ImportedBy->FileName
2471 << M->ModuleMap->getName() << F.ModuleMapPath;
2472 return OutOfDate;
2473 }
2474 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002475
2476 if (Listener)
2477 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002478 break;
2479
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002481 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 F.InputFilesLoaded.resize(Record[0]);
2483 break;
2484 }
2485 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002486}
2487
Ben Langmuir2c9af442014-04-10 17:57:43 +00002488ASTReader::ASTReadResult
2489ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002490 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002491
2492 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2493 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 }
2496
2497 // Read all of the records and blocks for the AST file.
2498 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002499 while (1) {
2500 llvm::BitstreamEntry Entry = Stream.advance();
2501
2502 switch (Entry.Kind) {
2503 case llvm::BitstreamEntry::Error:
2504 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002505 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002506 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002507 // Outside of C++, we do not store a lookup map for the translation unit.
2508 // Instead, mark it as needing a lookup map to be built if this module
2509 // contains any declarations lexically within it (which it always does!).
2510 // This usually has no cost, since we very rarely need the lookup map for
2511 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002513 if (DC->hasExternalLexicalStorage() &&
2514 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002515 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002516
Ben Langmuir2c9af442014-04-10 17:57:43 +00002517 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002519 case llvm::BitstreamEntry::SubBlock:
2520 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 case DECLTYPES_BLOCK_ID:
2522 // We lazily load the decls block, but we want to set up the
2523 // DeclsCursor cursor to point into it. Clone our current bitcode
2524 // cursor to it, enter the block and read the abbrevs in that block.
2525 // With the main cursor, we just skip over it.
2526 F.DeclsCursor = Stream;
2527 if (Stream.SkipBlock() || // Skip with the main cursor.
2528 // Read the abbrevs.
2529 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2530 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 }
2533 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002534
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 case PREPROCESSOR_BLOCK_ID:
2536 F.MacroCursor = Stream;
2537 if (!PP.getExternalSource())
2538 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002539
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 if (Stream.SkipBlock() ||
2541 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2542 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002543 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 }
2545 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2546 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 case PREPROCESSOR_DETAIL_BLOCK_ID:
2549 F.PreprocessorDetailCursor = Stream;
2550 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002551 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002554 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002557 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 if (!PP.getPreprocessingRecord())
2560 PP.createPreprocessingRecord();
2561 if (!PP.getPreprocessingRecord()->getExternalSource())
2562 PP.getPreprocessingRecord()->SetExternalSource(*this);
2563 break;
2564
2565 case SOURCE_MANAGER_BLOCK_ID:
2566 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002567 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002569
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002571 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2572 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002574
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002576 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 if (Stream.SkipBlock() ||
2578 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2579 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002580 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 }
2582 CommentsCursors.push_back(std::make_pair(C, &F));
2583 break;
2584 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587 if (Stream.SkipBlock()) {
2588 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002589 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002590 }
2591 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 }
2593 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594
2595 case llvm::BitstreamEntry::Record:
2596 // The interesting case.
2597 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 }
2599
2600 // Read and process a record.
2601 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002602 StringRef Blob;
2603 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 default: // Default behavior: ignore.
2605 break;
2606
2607 case TYPE_OFFSET: {
2608 if (F.LocalNumTypes != 0) {
2609 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002612 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 F.LocalNumTypes = Record[0];
2614 unsigned LocalBaseTypeIndex = Record[1];
2615 F.BaseTypeIndex = getTotalNumTypes();
2616
2617 if (F.LocalNumTypes > 0) {
2618 // Introduce the global -> local mapping for types within this module.
2619 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2620
2621 // Introduce the local -> global mapping for types within this module.
2622 F.TypeRemap.insertOrReplace(
2623 std::make_pair(LocalBaseTypeIndex,
2624 F.BaseTypeIndex - LocalBaseTypeIndex));
2625
2626 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2627 }
2628 break;
2629 }
2630
2631 case DECL_OFFSET: {
2632 if (F.LocalNumDecls != 0) {
2633 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002634 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumDecls = Record[0];
2638 unsigned LocalBaseDeclID = Record[1];
2639 F.BaseDeclID = getTotalNumDecls();
2640
2641 if (F.LocalNumDecls > 0) {
2642 // Introduce the global -> local mapping for declarations within this
2643 // module.
2644 GlobalDeclMap.insert(
2645 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2646
2647 // Introduce the local -> global mapping for declarations within this
2648 // module.
2649 F.DeclRemap.insertOrReplace(
2650 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2651
2652 // Introduce the global -> local mapping for declarations within this
2653 // module.
2654 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2655
2656 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2657 }
2658 break;
2659 }
2660
2661 case TU_UPDATE_LEXICAL: {
2662 DeclContext *TU = Context.getTranslationUnitDecl();
2663 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002664 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002666 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 TU->setHasExternalLexicalStorage(true);
2668 break;
2669 }
2670
2671 case UPDATE_VISIBLE: {
2672 unsigned Idx = 0;
2673 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2674 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002675 ASTDeclContextNameLookupTable::Create(
2676 (const unsigned char *)Blob.data() + Record[Idx++],
2677 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2678 (const unsigned char *)Blob.data(),
2679 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002680 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002681 auto *DC = cast<DeclContext>(D);
2682 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002683 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002684 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002685 delete LookupTable;
2686 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 } else
2688 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2689 break;
2690 }
2691
2692 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002693 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002695 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2696 (const unsigned char *)F.IdentifierTableData + Record[0],
2697 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2698 (const unsigned char *)F.IdentifierTableData,
2699 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002700
2701 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2702 }
2703 break;
2704
2705 case IDENTIFIER_OFFSET: {
2706 if (F.LocalNumIdentifiers != 0) {
2707 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002708 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002710 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 F.LocalNumIdentifiers = Record[0];
2712 unsigned LocalBaseIdentifierID = Record[1];
2713 F.BaseIdentifierID = getTotalNumIdentifiers();
2714
2715 if (F.LocalNumIdentifiers > 0) {
2716 // Introduce the global -> local mapping for identifiers within this
2717 // module.
2718 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2719 &F));
2720
2721 // Introduce the local -> global mapping for identifiers within this
2722 // module.
2723 F.IdentifierRemap.insertOrReplace(
2724 std::make_pair(LocalBaseIdentifierID,
2725 F.BaseIdentifierID - LocalBaseIdentifierID));
2726
2727 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2728 + F.LocalNumIdentifiers);
2729 }
2730 break;
2731 }
2732
Ben Langmuir332aafe2014-01-31 01:06:56 +00002733 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002735 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 break;
2737
2738 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002739 if (SpecialTypes.empty()) {
2740 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2741 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2742 break;
2743 }
2744
2745 if (SpecialTypes.size() != Record.size()) {
2746 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002747 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002748 }
2749
2750 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2751 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2752 if (!SpecialTypes[I])
2753 SpecialTypes[I] = ID;
2754 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2755 // merge step?
2756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 break;
2758
2759 case STATISTICS:
2760 TotalNumStatements += Record[0];
2761 TotalNumMacros += Record[1];
2762 TotalLexicalDeclContexts += Record[2];
2763 TotalVisibleDeclContexts += Record[3];
2764 break;
2765
2766 case UNUSED_FILESCOPED_DECLS:
2767 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2768 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2769 break;
2770
2771 case DELEGATING_CTORS:
2772 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2773 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2774 break;
2775
2776 case WEAK_UNDECLARED_IDENTIFIERS:
2777 if (Record.size() % 4 != 0) {
2778 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002779 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 }
2781
2782 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2783 // files. This isn't the way to do it :)
2784 WeakUndeclaredIdentifiers.clear();
2785
2786 // Translate the weak, undeclared identifiers into global IDs.
2787 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2788 WeakUndeclaredIdentifiers.push_back(
2789 getGlobalIdentifierID(F, Record[I++]));
2790 WeakUndeclaredIdentifiers.push_back(
2791 getGlobalIdentifierID(F, Record[I++]));
2792 WeakUndeclaredIdentifiers.push_back(
2793 ReadSourceLocation(F, Record, I).getRawEncoding());
2794 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2795 }
2796 break;
2797
Richard Smith78165b52013-01-10 23:43:47 +00002798 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002800 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 break;
2802
2803 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002804 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 F.LocalNumSelectors = Record[0];
2806 unsigned LocalBaseSelectorID = Record[1];
2807 F.BaseSelectorID = getTotalNumSelectors();
2808
2809 if (F.LocalNumSelectors > 0) {
2810 // Introduce the global -> local mapping for selectors within this
2811 // module.
2812 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2813
2814 // Introduce the local -> global mapping for selectors within this
2815 // module.
2816 F.SelectorRemap.insertOrReplace(
2817 std::make_pair(LocalBaseSelectorID,
2818 F.BaseSelectorID - LocalBaseSelectorID));
2819
2820 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2821 }
2822 break;
2823 }
2824
2825 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002826 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 if (Record[0])
2828 F.SelectorLookupTable
2829 = ASTSelectorLookupTable::Create(
2830 F.SelectorLookupTableData + Record[0],
2831 F.SelectorLookupTableData,
2832 ASTSelectorLookupTrait(*this, F));
2833 TotalNumMethodPoolEntries += Record[1];
2834 break;
2835
2836 case REFERENCED_SELECTOR_POOL:
2837 if (!Record.empty()) {
2838 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2839 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2840 Record[Idx++]));
2841 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2842 getRawEncoding());
2843 }
2844 }
2845 break;
2846
2847 case PP_COUNTER_VALUE:
2848 if (!Record.empty() && Listener)
2849 Listener->ReadCounter(F, Record[0]);
2850 break;
2851
2852 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002853 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 F.NumFileSortedDecls = Record[0];
2855 break;
2856
2857 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002858 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 F.LocalNumSLocEntries = Record[0];
2860 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002861 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2863 SLocSpaceSize);
2864 // Make our entry in the range map. BaseID is negative and growing, so
2865 // we invert it. Because we invert it, though, we need the other end of
2866 // the range.
2867 unsigned RangeStart =
2868 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2869 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2870 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2871
2872 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2873 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2874 GlobalSLocOffsetMap.insert(
2875 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2876 - SLocSpaceSize,&F));
2877
2878 // Initialize the remapping table.
2879 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002880 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002882 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2884
2885 TotalNumSLocEntries += F.LocalNumSLocEntries;
2886 break;
2887 }
2888
2889 case MODULE_OFFSET_MAP: {
2890 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002891 const unsigned char *Data = (const unsigned char*)Blob.data();
2892 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002893
2894 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2895 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2896 F.SLocRemap.insert(std::make_pair(0U, 0));
2897 F.SLocRemap.insert(std::make_pair(2U, 1));
2898 }
2899
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 // Continuous range maps we may be updating in our module.
2901 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2902 ContinuousRangeMap<uint32_t, int, 2>::Builder
2903 IdentifierRemap(F.IdentifierRemap);
2904 ContinuousRangeMap<uint32_t, int, 2>::Builder
2905 MacroRemap(F.MacroRemap);
2906 ContinuousRangeMap<uint32_t, int, 2>::Builder
2907 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2908 ContinuousRangeMap<uint32_t, int, 2>::Builder
2909 SubmoduleRemap(F.SubmoduleRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder
2911 SelectorRemap(F.SelectorRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2913 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2914
2915 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002916 using namespace llvm::support;
2917 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 StringRef Name = StringRef((const char*)Data, Len);
2919 Data += Len;
2920 ModuleFile *OM = ModuleMgr.lookup(Name);
2921 if (!OM) {
2922 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002923 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 }
2925
Justin Bogner57ba0b22014-03-28 22:03:24 +00002926 uint32_t SLocOffset =
2927 endian::readNext<uint32_t, little, unaligned>(Data);
2928 uint32_t IdentifierIDOffset =
2929 endian::readNext<uint32_t, little, unaligned>(Data);
2930 uint32_t MacroIDOffset =
2931 endian::readNext<uint32_t, little, unaligned>(Data);
2932 uint32_t PreprocessedEntityIDOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t SubmoduleIDOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t SelectorIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t DeclIDOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940 uint32_t TypeIndexOffset =
2941 endian::readNext<uint32_t, little, unaligned>(Data);
2942
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2944 SLocRemap.insert(std::make_pair(SLocOffset,
2945 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2946 IdentifierRemap.insert(
2947 std::make_pair(IdentifierIDOffset,
2948 OM->BaseIdentifierID - IdentifierIDOffset));
2949 MacroRemap.insert(std::make_pair(MacroIDOffset,
2950 OM->BaseMacroID - MacroIDOffset));
2951 PreprocessedEntityRemap.insert(
2952 std::make_pair(PreprocessedEntityIDOffset,
2953 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2954 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2955 OM->BaseSubmoduleID - SubmoduleIDOffset));
2956 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2957 OM->BaseSelectorID - SelectorIDOffset));
2958 DeclRemap.insert(std::make_pair(DeclIDOffset,
2959 OM->BaseDeclID - DeclIDOffset));
2960
2961 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2962 OM->BaseTypeIndex - TypeIndexOffset));
2963
2964 // Global -> local mappings.
2965 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2966 }
2967 break;
2968 }
2969
2970 case SOURCE_MANAGER_LINE_TABLE:
2971 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 break;
2974
2975 case SOURCE_LOCATION_PRELOADS: {
2976 // Need to transform from the local view (1-based IDs) to the global view,
2977 // which is based off F.SLocEntryBaseID.
2978 if (!F.PreloadSLocEntries.empty()) {
2979 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 }
2982
2983 F.PreloadSLocEntries.swap(Record);
2984 break;
2985 }
2986
2987 case EXT_VECTOR_DECLS:
2988 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2989 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2990 break;
2991
2992 case VTABLE_USES:
2993 if (Record.size() % 3 != 0) {
2994 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002995 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 }
2997
2998 // Later tables overwrite earlier ones.
2999 // FIXME: Modules will have some trouble with this. This is clearly not
3000 // the right way to do this.
3001 VTableUses.clear();
3002
3003 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3004 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3005 VTableUses.push_back(
3006 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3007 VTableUses.push_back(Record[Idx++]);
3008 }
3009 break;
3010
3011 case DYNAMIC_CLASSES:
3012 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3013 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3014 break;
3015
3016 case PENDING_IMPLICIT_INSTANTIATIONS:
3017 if (PendingInstantiations.size() % 2 != 0) {
3018 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 }
3021
3022 if (Record.size() % 2 != 0) {
3023 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 }
3026
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3028 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3029 PendingInstantiations.push_back(
3030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
3033
3034 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003035 if (Record.size() != 2) {
3036 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003037 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003038 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3040 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3041 break;
3042
3043 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003044 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3045 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3046 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003047
3048 unsigned LocalBasePreprocessedEntityID = Record[0];
3049
3050 unsigned StartingID;
3051 if (!PP.getPreprocessingRecord())
3052 PP.createPreprocessingRecord();
3053 if (!PP.getPreprocessingRecord()->getExternalSource())
3054 PP.getPreprocessingRecord()->SetExternalSource(*this);
3055 StartingID
3056 = PP.getPreprocessingRecord()
3057 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3058 F.BasePreprocessedEntityID = StartingID;
3059
3060 if (F.NumPreprocessedEntities > 0) {
3061 // Introduce the global -> local mapping for preprocessed entities in
3062 // this module.
3063 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3064
3065 // Introduce the local -> global mapping for preprocessed entities in
3066 // this module.
3067 F.PreprocessedEntityRemap.insertOrReplace(
3068 std::make_pair(LocalBasePreprocessedEntityID,
3069 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3070 }
3071
3072 break;
3073 }
3074
3075 case DECL_UPDATE_OFFSETS: {
3076 if (Record.size() % 2 != 0) {
3077 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003078 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003080 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3081 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3082 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3083
3084 // If we've already loaded the decl, perform the updates when we finish
3085 // loading this block.
3086 if (Decl *D = GetExistingDecl(ID))
3087 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3088 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 break;
3090 }
3091
3092 case DECL_REPLACEMENTS: {
3093 if (Record.size() % 3 != 0) {
3094 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003095 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 }
3097 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3098 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3099 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3100 break;
3101 }
3102
3103 case OBJC_CATEGORIES_MAP: {
3104 if (F.LocalNumObjCCategoriesInMap != 0) {
3105 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003106 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
3108
3109 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003110 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 break;
3112 }
3113
3114 case OBJC_CATEGORIES:
3115 F.ObjCCategories.swap(Record);
3116 break;
3117
3118 case CXX_BASE_SPECIFIER_OFFSETS: {
3119 if (F.LocalNumCXXBaseSpecifiers != 0) {
3120 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003121 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 }
3123
3124 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003125 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3127 break;
3128 }
3129
3130 case DIAG_PRAGMA_MAPPINGS:
3131 if (F.PragmaDiagMappings.empty())
3132 F.PragmaDiagMappings.swap(Record);
3133 else
3134 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3135 Record.begin(), Record.end());
3136 break;
3137
3138 case CUDA_SPECIAL_DECL_REFS:
3139 // Later tables overwrite earlier ones.
3140 // FIXME: Modules will have trouble with this.
3141 CUDASpecialDeclRefs.clear();
3142 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3143 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3144 break;
3145
3146 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003147 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 if (Record[0]) {
3150 F.HeaderFileInfoTable
3151 = HeaderFileInfoLookupTable::Create(
3152 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3153 (const unsigned char *)F.HeaderFileInfoTableData,
3154 HeaderFileInfoTrait(*this, F,
3155 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003156 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003157
3158 PP.getHeaderSearchInfo().SetExternalSource(this);
3159 if (!PP.getHeaderSearchInfo().getExternalLookup())
3160 PP.getHeaderSearchInfo().SetExternalLookup(this);
3161 }
3162 break;
3163 }
3164
3165 case FP_PRAGMA_OPTIONS:
3166 // Later tables overwrite earlier ones.
3167 FPPragmaOptions.swap(Record);
3168 break;
3169
3170 case OPENCL_EXTENSIONS:
3171 // Later tables overwrite earlier ones.
3172 OpenCLExtensions.swap(Record);
3173 break;
3174
3175 case TENTATIVE_DEFINITIONS:
3176 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3177 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3178 break;
3179
3180 case KNOWN_NAMESPACES:
3181 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3182 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3183 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003184
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003185 case UNDEFINED_BUT_USED:
3186 if (UndefinedButUsed.size() % 2 != 0) {
3187 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003188 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003189 }
3190
3191 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003192 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003193 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003194 }
3195 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003196 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3197 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003198 ReadSourceLocation(F, Record, I).getRawEncoding());
3199 }
3200 break;
3201
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 case IMPORTED_MODULES: {
3203 if (F.Kind != MK_Module) {
3204 // If we aren't loading a module (which has its own exports), make
3205 // all of the imported modules visible.
3206 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003207 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3208 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3209 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3210 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003211 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 }
3213 }
3214 break;
3215 }
3216
3217 case LOCAL_REDECLARATIONS: {
3218 F.RedeclarationChains.swap(Record);
3219 break;
3220 }
3221
3222 case LOCAL_REDECLARATIONS_MAP: {
3223 if (F.LocalNumRedeclarationsInMap != 0) {
3224 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003225 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 }
3227
3228 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003229 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 break;
3231 }
3232
3233 case MERGED_DECLARATIONS: {
3234 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3235 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3236 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3237 for (unsigned N = Record[Idx++]; N > 0; --N)
3238 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3239 }
3240 break;
3241 }
3242
3243 case MACRO_OFFSET: {
3244 if (F.LocalNumMacros != 0) {
3245 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003246 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003248 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 F.LocalNumMacros = Record[0];
3250 unsigned LocalBaseMacroID = Record[1];
3251 F.BaseMacroID = getTotalNumMacros();
3252
3253 if (F.LocalNumMacros > 0) {
3254 // Introduce the global -> local mapping for macros within this module.
3255 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3256
3257 // Introduce the local -> global mapping for macros within this module.
3258 F.MacroRemap.insertOrReplace(
3259 std::make_pair(LocalBaseMacroID,
3260 F.BaseMacroID - LocalBaseMacroID));
3261
3262 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3263 }
3264 break;
3265 }
3266
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003267 case MACRO_TABLE: {
3268 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 break;
3270 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003271
3272 case LATE_PARSED_TEMPLATE: {
3273 LateParsedTemplates.append(Record.begin(), Record.end());
3274 break;
3275 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 }
3277 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003278}
3279
Douglas Gregorc1489562013-02-12 23:36:21 +00003280/// \brief Move the given method to the back of the global list of methods.
3281static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3282 // Find the entry for this selector in the method pool.
3283 Sema::GlobalMethodPool::iterator Known
3284 = S.MethodPool.find(Method->getSelector());
3285 if (Known == S.MethodPool.end())
3286 return;
3287
3288 // Retrieve the appropriate method list.
3289 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3290 : Known->second.second;
3291 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003292 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003293 if (!Found) {
3294 if (List->Method == Method) {
3295 Found = true;
3296 } else {
3297 // Keep searching.
3298 continue;
3299 }
3300 }
3301
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003302 if (List->getNext())
3303 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003304 else
3305 List->Method = Method;
3306 }
3307}
3308
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003309void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003310 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3311 Decl *D = Names.HiddenDecls[I];
3312 bool wasHidden = D->Hidden;
3313 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003314
Richard Smith49f906a2014-03-01 00:08:04 +00003315 if (wasHidden && SemaObj) {
3316 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3317 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 }
3320 }
Richard Smith49f906a2014-03-01 00:08:04 +00003321
3322 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3323 E = Names.HiddenMacros.end();
3324 I != E; ++I)
3325 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003326}
3327
Richard Smith49f906a2014-03-01 00:08:04 +00003328void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003329 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003330 SourceLocation ImportLoc,
3331 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003333 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003334 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003335 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003336 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003337
3338 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003339 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 // there is nothing more to do.
3341 continue;
3342 }
Richard Smith49f906a2014-03-01 00:08:04 +00003343
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 if (!Mod->isAvailable()) {
3345 // Modules that aren't available cannot be made visible.
3346 continue;
3347 }
3348
3349 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003350 if (NameVisibility >= Module::MacrosVisible &&
3351 Mod->NameVisibility < Module::MacrosVisible)
3352 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003354
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 // If we've already deserialized any names from this module,
3356 // mark them as visible.
3357 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3358 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003359 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 HiddenNamesMap.erase(Hidden);
3361 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003362
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003364 SmallVector<Module *, 16> Exports;
3365 Mod->getExportedModules(Exports);
3366 for (SmallVectorImpl<Module *>::iterator
3367 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3368 Module *Exported = *I;
3369 if (Visited.insert(Exported))
3370 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003372
3373 // Detect any conflicts.
3374 if (Complain) {
3375 assert(ImportLoc.isValid() && "Missing import location");
3376 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3377 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3378 Diag(ImportLoc, diag::warn_module_conflict)
3379 << Mod->getFullModuleName()
3380 << Mod->Conflicts[I].Other->getFullModuleName()
3381 << Mod->Conflicts[I].Message;
3382 // FIXME: Need note where the other module was imported.
3383 }
3384 }
3385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 }
3387}
3388
Douglas Gregore060e572013-01-25 01:03:03 +00003389bool ASTReader::loadGlobalIndex() {
3390 if (GlobalIndex)
3391 return false;
3392
3393 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3394 !Context.getLangOpts().Modules)
3395 return true;
3396
3397 // Try to load the global index.
3398 TriedLoadingGlobalIndex = true;
3399 StringRef ModuleCachePath
3400 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3401 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003402 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003403 if (!Result.first)
3404 return true;
3405
3406 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003407 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003408 return false;
3409}
3410
3411bool ASTReader::isGlobalIndexUnavailable() const {
3412 return Context.getLangOpts().Modules && UseGlobalIndex &&
3413 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3414}
3415
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003416static void updateModuleTimestamp(ModuleFile &MF) {
3417 // Overwrite the timestamp file contents so that file's mtime changes.
3418 std::string TimestampFilename = MF.getTimestampFilename();
3419 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003420 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003421 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003422 if (!ErrorInfo.empty())
3423 return;
3424 OS << "Timestamp file\n";
3425}
3426
Guy Benyei11169dd2012-12-18 14:30:41 +00003427ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3428 ModuleKind Type,
3429 SourceLocation ImportLoc,
3430 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003431 llvm::SaveAndRestore<SourceLocation>
3432 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3433
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 // Bump the generation number.
3435 unsigned PreviousGeneration = CurrentGeneration++;
3436
3437 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003438 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3440 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003441 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 ClientLoadCapabilities)) {
3443 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003444 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 case OutOfDate:
3446 case VersionMismatch:
3447 case ConfigurationMismatch:
3448 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003449 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3450 Context.getLangOpts().Modules
3451 ? &PP.getHeaderSearchInfo().getModuleMap()
3452 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003453
3454 // If we find that any modules are unusable, the global index is going
3455 // to be out-of-date. Just remove it.
3456 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003457 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003458 return ReadResult;
3459
3460 case Success:
3461 break;
3462 }
3463
3464 // Here comes stuff that we only do once the entire chain is loaded.
3465
3466 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003467 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3468 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 M != MEnd; ++M) {
3470 ModuleFile &F = *M->Mod;
3471
3472 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003473 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3474 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003475
3476 // Once read, set the ModuleFile bit base offset and update the size in
3477 // bits of all files we've seen.
3478 F.GlobalBitOffset = TotalModulesSizeInBits;
3479 TotalModulesSizeInBits += F.SizeInBits;
3480 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3481
3482 // Preload SLocEntries.
3483 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3484 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3485 // Load it through the SourceManager and don't call ReadSLocEntry()
3486 // directly because the entry may have already been loaded in which case
3487 // calling ReadSLocEntry() directly would trigger an assertion in
3488 // SourceManager.
3489 SourceMgr.getLoadedSLocEntryByID(Index);
3490 }
3491 }
3492
Douglas Gregor603cd862013-03-22 18:50:14 +00003493 // Setup the import locations and notify the module manager that we've
3494 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003495 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3496 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 M != MEnd; ++M) {
3498 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003499
3500 ModuleMgr.moduleFileAccepted(&F);
3501
3502 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003503 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 if (!M->ImportedBy)
3505 F.ImportLoc = M->ImportLoc;
3506 else
3507 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3508 M->ImportLoc.getRawEncoding());
3509 }
3510
3511 // Mark all of the identifiers in the identifier table as being out of date,
3512 // so that various accessors know to check the loaded modules when the
3513 // identifier is used.
3514 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3515 IdEnd = PP.getIdentifierTable().end();
3516 Id != IdEnd; ++Id)
3517 Id->second->setOutOfDate(true);
3518
3519 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003520 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3521 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3523 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003524
3525 switch (Unresolved.Kind) {
3526 case UnresolvedModuleRef::Conflict:
3527 if (ResolvedMod) {
3528 Module::Conflict Conflict;
3529 Conflict.Other = ResolvedMod;
3530 Conflict.Message = Unresolved.String.str();
3531 Unresolved.Mod->Conflicts.push_back(Conflict);
3532 }
3533 continue;
3534
3535 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 if (ResolvedMod)
3537 Unresolved.Mod->Imports.push_back(ResolvedMod);
3538 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003539
Douglas Gregorfb912652013-03-20 21:10:35 +00003540 case UnresolvedModuleRef::Export:
3541 if (ResolvedMod || Unresolved.IsWildcard)
3542 Unresolved.Mod->Exports.push_back(
3543 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3544 continue;
3545 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003547 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003548
3549 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3550 // Might be unnecessary as use declarations are only used to build the
3551 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003552
3553 InitializeContext();
3554
Richard Smith3d8e97e2013-10-18 06:54:39 +00003555 if (SemaObj)
3556 UpdateSema();
3557
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 if (DeserializationListener)
3559 DeserializationListener->ReaderInitialized(this);
3560
3561 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3562 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3563 PrimaryModule.OriginalSourceFileID
3564 = FileID::get(PrimaryModule.SLocEntryBaseID
3565 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3566
3567 // If this AST file is a precompiled preamble, then set the
3568 // preamble file ID of the source manager to the file source file
3569 // from which the preamble was built.
3570 if (Type == MK_Preamble) {
3571 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3572 } else if (Type == MK_MainFile) {
3573 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3574 }
3575 }
3576
3577 // For any Objective-C class definitions we have already loaded, make sure
3578 // that we load any additional categories.
3579 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3580 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3581 ObjCClassesLoaded[I],
3582 PreviousGeneration);
3583 }
Douglas Gregore060e572013-01-25 01:03:03 +00003584
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003585 if (PP.getHeaderSearchInfo()
3586 .getHeaderSearchOpts()
3587 .ModulesValidateOncePerBuildSession) {
3588 // Now we are certain that the module and all modules it depends on are
3589 // up to date. Create or update timestamp files for modules that are
3590 // located in the module cache (not for PCH files that could be anywhere
3591 // in the filesystem).
3592 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3593 ImportedModule &M = Loaded[I];
3594 if (M.Mod->Kind == MK_Module) {
3595 updateModuleTimestamp(*M.Mod);
3596 }
3597 }
3598 }
3599
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 return Success;
3601}
3602
3603ASTReader::ASTReadResult
3604ASTReader::ReadASTCore(StringRef FileName,
3605 ModuleKind Type,
3606 SourceLocation ImportLoc,
3607 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003608 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 unsigned ClientLoadCapabilities) {
3611 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003612 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003613 ModuleManager::AddModuleResult AddResult
3614 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3615 CurrentGeneration, ExpectedSize, ExpectedModTime,
3616 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003617
Douglas Gregor7029ce12013-03-19 00:28:20 +00003618 switch (AddResult) {
3619 case ModuleManager::AlreadyLoaded:
3620 return Success;
3621
3622 case ModuleManager::NewlyLoaded:
3623 // Load module file below.
3624 break;
3625
3626 case ModuleManager::Missing:
3627 // The module file was missing; if the client handle handle, that, return
3628 // it.
3629 if (ClientLoadCapabilities & ARR_Missing)
3630 return Missing;
3631
3632 // Otherwise, return an error.
3633 {
3634 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3635 + ErrorStr;
3636 Error(Msg);
3637 }
3638 return Failure;
3639
3640 case ModuleManager::OutOfDate:
3641 // We couldn't load the module file because it is out-of-date. If the
3642 // client can handle out-of-date, return it.
3643 if (ClientLoadCapabilities & ARR_OutOfDate)
3644 return OutOfDate;
3645
3646 // Otherwise, return an error.
3647 {
3648 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3649 + ErrorStr;
3650 Error(Msg);
3651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 return Failure;
3653 }
3654
Douglas Gregor7029ce12013-03-19 00:28:20 +00003655 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003656
3657 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3658 // module?
3659 if (FileName != "-") {
3660 CurrentDir = llvm::sys::path::parent_path(FileName);
3661 if (CurrentDir.empty()) CurrentDir = ".";
3662 }
3663
3664 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003665 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 Stream.init(F.StreamFile);
3667 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3668
3669 // Sniff for the signature.
3670 if (Stream.Read(8) != 'C' ||
3671 Stream.Read(8) != 'P' ||
3672 Stream.Read(8) != 'C' ||
3673 Stream.Read(8) != 'H') {
3674 Diag(diag::err_not_a_pch_file) << FileName;
3675 return Failure;
3676 }
3677
3678 // This is used for compatibility with older PCH formats.
3679 bool HaveReadControlBlock = false;
3680
Chris Lattnerefa77172013-01-20 00:00:22 +00003681 while (1) {
3682 llvm::BitstreamEntry Entry = Stream.advance();
3683
3684 switch (Entry.Kind) {
3685 case llvm::BitstreamEntry::Error:
3686 case llvm::BitstreamEntry::EndBlock:
3687 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 Error("invalid record at top-level of AST file");
3689 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003690
3691 case llvm::BitstreamEntry::SubBlock:
3692 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 }
3694
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003696 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3698 if (Stream.ReadBlockInfoBlock()) {
3699 Error("malformed BlockInfoBlock in AST file");
3700 return Failure;
3701 }
3702 break;
3703 case CONTROL_BLOCK_ID:
3704 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003705 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 case Success:
3707 break;
3708
3709 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003710 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 case OutOfDate: return OutOfDate;
3712 case VersionMismatch: return VersionMismatch;
3713 case ConfigurationMismatch: return ConfigurationMismatch;
3714 case HadErrors: return HadErrors;
3715 }
3716 break;
3717 case AST_BLOCK_ID:
3718 if (!HaveReadControlBlock) {
3719 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003720 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003721 return VersionMismatch;
3722 }
3723
3724 // Record that we've loaded this module.
3725 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3726 return Success;
3727
3728 default:
3729 if (Stream.SkipBlock()) {
3730 Error("malformed block record in AST file");
3731 return Failure;
3732 }
3733 break;
3734 }
3735 }
3736
3737 return Success;
3738}
3739
3740void ASTReader::InitializeContext() {
3741 // If there's a listener, notify them that we "read" the translation unit.
3742 if (DeserializationListener)
3743 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3744 Context.getTranslationUnitDecl());
3745
Richard Smithcd45dbc2014-04-19 03:48:30 +00003746 // For any declarations we have already loaded, load any update records.
3747 {
3748 // We're not back to a consistent state until all our pending update
3749 // records have been loaded. There can be interdependencies between them.
3750 Deserializing SomeUpdateRecords(this);
3751 ReadingKindTracker ReadingKind(Read_Decl, *this);
3752
3753 // Make sure we load the declaration update records for the translation
3754 // unit, if there are any.
3755 // FIXME: Is this necessary any more?
3756 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3757 Context.getTranslationUnitDecl());
3758
3759 for (auto &Update : PendingUpdateRecords)
3760 loadDeclUpdateRecords(Update.first, Update.second);
3761 PendingUpdateRecords.clear();
3762 }
3763
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 // FIXME: Find a better way to deal with collisions between these
3765 // built-in types. Right now, we just ignore the problem.
3766
3767 // Load the special types.
3768 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3769 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3770 if (!Context.CFConstantStringTypeDecl)
3771 Context.setCFConstantStringType(GetType(String));
3772 }
3773
3774 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3775 QualType FileType = GetType(File);
3776 if (FileType.isNull()) {
3777 Error("FILE type is NULL");
3778 return;
3779 }
3780
3781 if (!Context.FILEDecl) {
3782 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3783 Context.setFILEDecl(Typedef->getDecl());
3784 else {
3785 const TagType *Tag = FileType->getAs<TagType>();
3786 if (!Tag) {
3787 Error("Invalid FILE type in AST file");
3788 return;
3789 }
3790 Context.setFILEDecl(Tag->getDecl());
3791 }
3792 }
3793 }
3794
3795 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3796 QualType Jmp_bufType = GetType(Jmp_buf);
3797 if (Jmp_bufType.isNull()) {
3798 Error("jmp_buf type is NULL");
3799 return;
3800 }
3801
3802 if (!Context.jmp_bufDecl) {
3803 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3804 Context.setjmp_bufDecl(Typedef->getDecl());
3805 else {
3806 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3807 if (!Tag) {
3808 Error("Invalid jmp_buf type in AST file");
3809 return;
3810 }
3811 Context.setjmp_bufDecl(Tag->getDecl());
3812 }
3813 }
3814 }
3815
3816 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3817 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3818 if (Sigjmp_bufType.isNull()) {
3819 Error("sigjmp_buf type is NULL");
3820 return;
3821 }
3822
3823 if (!Context.sigjmp_bufDecl) {
3824 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3825 Context.setsigjmp_bufDecl(Typedef->getDecl());
3826 else {
3827 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3828 assert(Tag && "Invalid sigjmp_buf type in AST file");
3829 Context.setsigjmp_bufDecl(Tag->getDecl());
3830 }
3831 }
3832 }
3833
3834 if (unsigned ObjCIdRedef
3835 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3836 if (Context.ObjCIdRedefinitionType.isNull())
3837 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3838 }
3839
3840 if (unsigned ObjCClassRedef
3841 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3842 if (Context.ObjCClassRedefinitionType.isNull())
3843 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3844 }
3845
3846 if (unsigned ObjCSelRedef
3847 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3848 if (Context.ObjCSelRedefinitionType.isNull())
3849 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3850 }
3851
3852 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3853 QualType Ucontext_tType = GetType(Ucontext_t);
3854 if (Ucontext_tType.isNull()) {
3855 Error("ucontext_t type is NULL");
3856 return;
3857 }
3858
3859 if (!Context.ucontext_tDecl) {
3860 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3861 Context.setucontext_tDecl(Typedef->getDecl());
3862 else {
3863 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3864 assert(Tag && "Invalid ucontext_t type in AST file");
3865 Context.setucontext_tDecl(Tag->getDecl());
3866 }
3867 }
3868 }
3869 }
3870
3871 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3872
3873 // If there were any CUDA special declarations, deserialize them.
3874 if (!CUDASpecialDeclRefs.empty()) {
3875 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3876 Context.setcudaConfigureCallDecl(
3877 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3878 }
Richard Smith56be7542014-03-21 00:33:59 +00003879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003881 // FIXME: This does not make macro-only imports visible again. It also doesn't
3882 // make #includes mapped to module imports visible.
3883 for (auto &Import : ImportedModules) {
3884 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003885 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003886 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003887 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 }
3889 ImportedModules.clear();
3890}
3891
3892void ASTReader::finalizeForWriting() {
3893 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3894 HiddenEnd = HiddenNamesMap.end();
3895 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003896 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 }
3898 HiddenNamesMap.clear();
3899}
3900
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003901/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3902/// cursor into the start of the given block ID, returning false on success and
3903/// true on failure.
3904static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003905 while (1) {
3906 llvm::BitstreamEntry Entry = Cursor.advance();
3907 switch (Entry.Kind) {
3908 case llvm::BitstreamEntry::Error:
3909 case llvm::BitstreamEntry::EndBlock:
3910 return true;
3911
3912 case llvm::BitstreamEntry::Record:
3913 // Ignore top-level records.
3914 Cursor.skipRecord(Entry.ID);
3915 break;
3916
3917 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003918 if (Entry.ID == BlockID) {
3919 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003920 return true;
3921 // Found it!
3922 return false;
3923 }
3924
3925 if (Cursor.SkipBlock())
3926 return true;
3927 }
3928 }
3929}
3930
Guy Benyei11169dd2012-12-18 14:30:41 +00003931/// \brief Retrieve the name of the original source file name
3932/// directly from the AST file, without actually loading the AST
3933/// file.
3934std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3935 FileManager &FileMgr,
3936 DiagnosticsEngine &Diags) {
3937 // Open the AST file.
3938 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003939 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3941 if (!Buffer) {
3942 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3943 return std::string();
3944 }
3945
3946 // Initialize the stream
3947 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003948 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3950 (const unsigned char *)Buffer->getBufferEnd());
3951 Stream.init(StreamFile);
3952
3953 // Sniff for the signature.
3954 if (Stream.Read(8) != 'C' ||
3955 Stream.Read(8) != 'P' ||
3956 Stream.Read(8) != 'C' ||
3957 Stream.Read(8) != 'H') {
3958 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3959 return std::string();
3960 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003961
Chris Lattnere7b154b2013-01-19 21:39:22 +00003962 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003963 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003964 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3965 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003966 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003967
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003968 // Scan for ORIGINAL_FILE inside the control block.
3969 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003970 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003971 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003972 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3973 return std::string();
3974
3975 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3976 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3977 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003979
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003981 StringRef Blob;
3982 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3983 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003985}
3986
3987namespace {
3988 class SimplePCHValidator : public ASTReaderListener {
3989 const LangOptions &ExistingLangOpts;
3990 const TargetOptions &ExistingTargetOpts;
3991 const PreprocessorOptions &ExistingPPOpts;
3992 FileManager &FileMgr;
3993
3994 public:
3995 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3996 const TargetOptions &ExistingTargetOpts,
3997 const PreprocessorOptions &ExistingPPOpts,
3998 FileManager &FileMgr)
3999 : ExistingLangOpts(ExistingLangOpts),
4000 ExistingTargetOpts(ExistingTargetOpts),
4001 ExistingPPOpts(ExistingPPOpts),
4002 FileMgr(FileMgr)
4003 {
4004 }
4005
Craig Topper3e89dfe2014-03-13 02:13:41 +00004006 bool ReadLanguageOptions(const LangOptions &LangOpts,
4007 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
4009 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004010 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4011 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
4013 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004014 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4015 bool Complain,
4016 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004018 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 }
4020 };
4021}
4022
4023bool ASTReader::readASTFileControlBlock(StringRef Filename,
4024 FileManager &FileMgr,
4025 ASTReaderListener &Listener) {
4026 // Open the AST file.
4027 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004028 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4030 if (!Buffer) {
4031 return true;
4032 }
4033
4034 // Initialize the stream
4035 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4038 (const unsigned char *)Buffer->getBufferEnd());
4039 Stream.init(StreamFile);
4040
4041 // Sniff for the signature.
4042 if (Stream.Read(8) != 'C' ||
4043 Stream.Read(8) != 'P' ||
4044 Stream.Read(8) != 'C' ||
4045 Stream.Read(8) != 'H') {
4046 return true;
4047 }
4048
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004049 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004050 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004051 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004052
4053 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004054 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004055 BitstreamCursor InputFilesCursor;
4056 if (NeedsInputFiles) {
4057 InputFilesCursor = Stream;
4058 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4059 return true;
4060
4061 // Read the abbreviations
4062 while (true) {
4063 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4064 unsigned Code = InputFilesCursor.ReadCode();
4065
4066 // We expect all abbrevs to be at the start of the block.
4067 if (Code != llvm::bitc::DEFINE_ABBREV) {
4068 InputFilesCursor.JumpToBit(Offset);
4069 break;
4070 }
4071 InputFilesCursor.ReadAbbrevRecord();
4072 }
4073 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004074
4075 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 while (1) {
4078 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4079 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4080 return false;
4081
4082 if (Entry.Kind != llvm::BitstreamEntry::Record)
4083 return true;
4084
Guy Benyei11169dd2012-12-18 14:30:41 +00004085 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004086 StringRef Blob;
4087 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004088 switch ((ControlRecordTypes)RecCode) {
4089 case METADATA: {
4090 if (Record[0] != VERSION_MAJOR)
4091 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004093 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004094 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004095
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004096 break;
4097 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004098 case MODULE_NAME:
4099 Listener.ReadModuleName(Blob);
4100 break;
4101 case MODULE_MAP_FILE:
4102 Listener.ReadModuleMapFile(Blob);
4103 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004104 case LANGUAGE_OPTIONS:
4105 if (ParseLanguageOptions(Record, false, Listener))
4106 return true;
4107 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004108
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004109 case TARGET_OPTIONS:
4110 if (ParseTargetOptions(Record, false, Listener))
4111 return true;
4112 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004113
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114 case DIAGNOSTIC_OPTIONS:
4115 if (ParseDiagnosticOptions(Record, false, Listener))
4116 return true;
4117 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004118
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004119 case FILE_SYSTEM_OPTIONS:
4120 if (ParseFileSystemOptions(Record, false, Listener))
4121 return true;
4122 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004123
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004124 case HEADER_SEARCH_OPTIONS:
4125 if (ParseHeaderSearchOptions(Record, false, Listener))
4126 return true;
4127 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004128
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004129 case PREPROCESSOR_OPTIONS: {
4130 std::string IgnoredSuggestedPredefines;
4131 if (ParsePreprocessorOptions(Record, false, Listener,
4132 IgnoredSuggestedPredefines))
4133 return true;
4134 break;
4135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004136
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004137 case INPUT_FILE_OFFSETS: {
4138 if (!NeedsInputFiles)
4139 break;
4140
4141 unsigned NumInputFiles = Record[0];
4142 unsigned NumUserFiles = Record[1];
4143 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4144 for (unsigned I = 0; I != NumInputFiles; ++I) {
4145 // Go find this input file.
4146 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004147
4148 if (isSystemFile && !NeedsSystemInputFiles)
4149 break; // the rest are system input files
4150
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004151 BitstreamCursor &Cursor = InputFilesCursor;
4152 SavedStreamPosition SavedPosition(Cursor);
4153 Cursor.JumpToBit(InputFileOffs[I]);
4154
4155 unsigned Code = Cursor.ReadCode();
4156 RecordData Record;
4157 StringRef Blob;
4158 bool shouldContinue = false;
4159 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4160 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004161 bool Overridden = static_cast<bool>(Record[3]);
4162 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004163 break;
4164 }
4165 if (!shouldContinue)
4166 break;
4167 }
4168 break;
4169 }
4170
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004171 default:
4172 // No other validation to perform.
4173 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 }
4175 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004176}
4177
4178
4179bool ASTReader::isAcceptableASTFile(StringRef Filename,
4180 FileManager &FileMgr,
4181 const LangOptions &LangOpts,
4182 const TargetOptions &TargetOpts,
4183 const PreprocessorOptions &PPOpts) {
4184 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4185 return !readASTFileControlBlock(Filename, FileMgr, validator);
4186}
4187
Ben Langmuir2c9af442014-04-10 17:57:43 +00004188ASTReader::ASTReadResult
4189ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 // Enter the submodule block.
4191 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4192 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 }
4195
4196 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4197 bool First = true;
4198 Module *CurrentModule = 0;
4199 RecordData Record;
4200 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004201 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4202
4203 switch (Entry.Kind) {
4204 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4205 case llvm::BitstreamEntry::Error:
4206 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004207 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004208 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004209 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004210 case llvm::BitstreamEntry::Record:
4211 // The interesting case.
4212 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004214
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004216 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004218 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 default: // Default behavior: ignore.
4220 break;
4221
4222 case SUBMODULE_DEFINITION: {
4223 if (First) {
4224 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004225 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 }
4227
Douglas Gregor8d932422013-03-20 03:59:18 +00004228 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004230 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 }
4232
Chris Lattner0e6c9402013-01-20 02:38:54 +00004233 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004234 unsigned Idx = 0;
4235 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4236 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4237 bool IsFramework = Record[Idx++];
4238 bool IsExplicit = Record[Idx++];
4239 bool IsSystem = Record[Idx++];
4240 bool IsExternC = Record[Idx++];
4241 bool InferSubmodules = Record[Idx++];
4242 bool InferExplicitSubmodules = Record[Idx++];
4243 bool InferExportWildcard = Record[Idx++];
4244 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004245
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004246 Module *ParentModule = nullptr;
4247 const FileEntry *ModuleMap = nullptr;
4248 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004250 ModuleMap = ParentModule->ModuleMap;
4251 }
4252
4253 if (!F.ModuleMapPath.empty())
4254 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4255
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 // Retrieve this (sub)module from the module map, creating it if
4257 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004258 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 IsFramework,
4260 IsExplicit).first;
4261 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4262 if (GlobalIndex >= SubmodulesLoaded.size() ||
4263 SubmodulesLoaded[GlobalIndex]) {
4264 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004267
Douglas Gregor7029ce12013-03-19 00:28:20 +00004268 if (!ParentModule) {
4269 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4270 if (CurFile != F.File) {
4271 if (!Diags.isDiagnosticInFlight()) {
4272 Diag(diag::err_module_file_conflict)
4273 << CurrentModule->getTopLevelModuleName()
4274 << CurFile->getName()
4275 << F.File->getName();
4276 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004277 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004278 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004279 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004280
4281 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004282 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004283
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 CurrentModule->IsFromModuleFile = true;
4285 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004286 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004287 CurrentModule->InferSubmodules = InferSubmodules;
4288 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4289 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004290 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 if (DeserializationListener)
4292 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4293
4294 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004295
Douglas Gregorfb912652013-03-20 21:10:35 +00004296 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004297 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004298 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004299 CurrentModule->UnresolvedConflicts.clear();
4300 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 break;
4302 }
4303
4304 case SUBMODULE_UMBRELLA_HEADER: {
4305 if (First) {
4306 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004307 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 }
4309
4310 if (!CurrentModule)
4311 break;
4312
Chris Lattner0e6c9402013-01-20 02:38:54 +00004313 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 if (!CurrentModule->getUmbrellaHeader())
4315 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4316 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004317 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4318 Error("mismatched umbrella headers in submodule");
4319 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 }
4321 }
4322 break;
4323 }
4324
4325 case SUBMODULE_HEADER: {
4326 if (First) {
4327 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004328 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 }
4330
4331 if (!CurrentModule)
4332 break;
4333
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004334 // We lazily associate headers with their modules via the HeaderInfoTable.
4335 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4336 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 break;
4338 }
4339
4340 case SUBMODULE_EXCLUDED_HEADER: {
4341 if (First) {
4342 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004343 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004344 }
4345
4346 if (!CurrentModule)
4347 break;
4348
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004349 // We lazily associate headers with their modules via the HeaderInfoTable.
4350 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4351 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 break;
4353 }
4354
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004355 case SUBMODULE_PRIVATE_HEADER: {
4356 if (First) {
4357 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004358 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004359 }
4360
4361 if (!CurrentModule)
4362 break;
4363
4364 // We lazily associate headers with their modules via the HeaderInfoTable.
4365 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4366 // of complete filenames or remove it entirely.
4367 break;
4368 }
4369
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 case SUBMODULE_TOPHEADER: {
4371 if (First) {
4372 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004373 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 }
4375
4376 if (!CurrentModule)
4377 break;
4378
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004379 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 break;
4381 }
4382
4383 case SUBMODULE_UMBRELLA_DIR: {
4384 if (First) {
4385 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004386 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 }
4388
4389 if (!CurrentModule)
4390 break;
4391
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004393 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 if (!CurrentModule->getUmbrellaDir())
4395 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4396 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004397 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4398 Error("mismatched umbrella directories in submodule");
4399 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 }
4401 }
4402 break;
4403 }
4404
4405 case SUBMODULE_METADATA: {
4406 if (!First) {
4407 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 }
4410 First = false;
4411
4412 F.BaseSubmoduleID = getTotalNumSubmodules();
4413 F.LocalNumSubmodules = Record[0];
4414 unsigned LocalBaseSubmoduleID = Record[1];
4415 if (F.LocalNumSubmodules > 0) {
4416 // Introduce the global -> local mapping for submodules within this
4417 // module.
4418 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4419
4420 // Introduce the local -> global mapping for submodules within this
4421 // module.
4422 F.SubmoduleRemap.insertOrReplace(
4423 std::make_pair(LocalBaseSubmoduleID,
4424 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4425
4426 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4427 }
4428 break;
4429 }
4430
4431 case SUBMODULE_IMPORTS: {
4432 if (First) {
4433 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004434 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 }
4436
4437 if (!CurrentModule)
4438 break;
4439
4440 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004441 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 Unresolved.File = &F;
4443 Unresolved.Mod = CurrentModule;
4444 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004445 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004447 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 }
4449 break;
4450 }
4451
4452 case SUBMODULE_EXPORTS: {
4453 if (First) {
4454 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004455 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 }
4457
4458 if (!CurrentModule)
4459 break;
4460
4461 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004462 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Unresolved.File = &F;
4464 Unresolved.Mod = CurrentModule;
4465 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004466 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004468 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 }
4470
4471 // Once we've loaded the set of exports, there's no reason to keep
4472 // the parsed, unresolved exports around.
4473 CurrentModule->UnresolvedExports.clear();
4474 break;
4475 }
4476 case SUBMODULE_REQUIRES: {
4477 if (First) {
4478 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004479 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 }
4481
4482 if (!CurrentModule)
4483 break;
4484
Richard Smitha3feee22013-10-28 22:18:19 +00004485 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 Context.getTargetInfo());
4487 break;
4488 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004489
4490 case SUBMODULE_LINK_LIBRARY:
4491 if (First) {
4492 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004493 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004494 }
4495
4496 if (!CurrentModule)
4497 break;
4498
4499 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004500 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004501 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004502
4503 case SUBMODULE_CONFIG_MACRO:
4504 if (First) {
4505 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004506 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004507 }
4508
4509 if (!CurrentModule)
4510 break;
4511
4512 CurrentModule->ConfigMacros.push_back(Blob.str());
4513 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004514
4515 case SUBMODULE_CONFLICT: {
4516 if (First) {
4517 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004518 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004519 }
4520
4521 if (!CurrentModule)
4522 break;
4523
4524 UnresolvedModuleRef Unresolved;
4525 Unresolved.File = &F;
4526 Unresolved.Mod = CurrentModule;
4527 Unresolved.ID = Record[0];
4528 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4529 Unresolved.IsWildcard = false;
4530 Unresolved.String = Blob;
4531 UnresolvedModuleRefs.push_back(Unresolved);
4532 break;
4533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535 }
4536}
4537
4538/// \brief Parse the record that corresponds to a LangOptions data
4539/// structure.
4540///
4541/// This routine parses the language options from the AST file and then gives
4542/// them to the AST listener if one is set.
4543///
4544/// \returns true if the listener deems the file unacceptable, false otherwise.
4545bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4546 bool Complain,
4547 ASTReaderListener &Listener) {
4548 LangOptions LangOpts;
4549 unsigned Idx = 0;
4550#define LANGOPT(Name, Bits, Default, Description) \
4551 LangOpts.Name = Record[Idx++];
4552#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4553 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4554#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004555#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4556#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004557
4558 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4559 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4560 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4561
4562 unsigned Length = Record[Idx++];
4563 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4564 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004565
4566 Idx += Length;
4567
4568 // Comment options.
4569 for (unsigned N = Record[Idx++]; N; --N) {
4570 LangOpts.CommentOpts.BlockCommandNames.push_back(
4571 ReadString(Record, Idx));
4572 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004573 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004574
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 return Listener.ReadLanguageOptions(LangOpts, Complain);
4576}
4577
4578bool ASTReader::ParseTargetOptions(const RecordData &Record,
4579 bool Complain,
4580 ASTReaderListener &Listener) {
4581 unsigned Idx = 0;
4582 TargetOptions TargetOpts;
4583 TargetOpts.Triple = ReadString(Record, Idx);
4584 TargetOpts.CPU = ReadString(Record, Idx);
4585 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4587 for (unsigned N = Record[Idx++]; N; --N) {
4588 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4589 }
4590 for (unsigned N = Record[Idx++]; N; --N) {
4591 TargetOpts.Features.push_back(ReadString(Record, Idx));
4592 }
4593
4594 return Listener.ReadTargetOptions(TargetOpts, Complain);
4595}
4596
4597bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4598 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004599 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004601#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004602#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004603 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004604#include "clang/Basic/DiagnosticOptions.def"
4605
4606 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004607 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 }
4609
4610 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4611}
4612
4613bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4614 ASTReaderListener &Listener) {
4615 FileSystemOptions FSOpts;
4616 unsigned Idx = 0;
4617 FSOpts.WorkingDir = ReadString(Record, Idx);
4618 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4619}
4620
4621bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4622 bool Complain,
4623 ASTReaderListener &Listener) {
4624 HeaderSearchOptions HSOpts;
4625 unsigned Idx = 0;
4626 HSOpts.Sysroot = ReadString(Record, Idx);
4627
4628 // Include entries.
4629 for (unsigned N = Record[Idx++]; N; --N) {
4630 std::string Path = ReadString(Record, Idx);
4631 frontend::IncludeDirGroup Group
4632 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 bool IsFramework = Record[Idx++];
4634 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004636 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 }
4638
4639 // System header prefixes.
4640 for (unsigned N = Record[Idx++]; N; --N) {
4641 std::string Prefix = ReadString(Record, Idx);
4642 bool IsSystemHeader = Record[Idx++];
4643 HSOpts.SystemHeaderPrefixes.push_back(
4644 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4645 }
4646
4647 HSOpts.ResourceDir = ReadString(Record, Idx);
4648 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004649 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 HSOpts.DisableModuleHash = Record[Idx++];
4651 HSOpts.UseBuiltinIncludes = Record[Idx++];
4652 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4653 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4654 HSOpts.UseLibcxx = Record[Idx++];
4655
4656 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4657}
4658
4659bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4660 bool Complain,
4661 ASTReaderListener &Listener,
4662 std::string &SuggestedPredefines) {
4663 PreprocessorOptions PPOpts;
4664 unsigned Idx = 0;
4665
4666 // Macro definitions/undefs
4667 for (unsigned N = Record[Idx++]; N; --N) {
4668 std::string Macro = ReadString(Record, Idx);
4669 bool IsUndef = Record[Idx++];
4670 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4671 }
4672
4673 // Includes
4674 for (unsigned N = Record[Idx++]; N; --N) {
4675 PPOpts.Includes.push_back(ReadString(Record, Idx));
4676 }
4677
4678 // Macro Includes
4679 for (unsigned N = Record[Idx++]; N; --N) {
4680 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4681 }
4682
4683 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004684 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4686 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4687 PPOpts.ObjCXXARCStandardLibrary =
4688 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4689 SuggestedPredefines.clear();
4690 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4691 SuggestedPredefines);
4692}
4693
4694std::pair<ModuleFile *, unsigned>
4695ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4696 GlobalPreprocessedEntityMapType::iterator
4697 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4698 assert(I != GlobalPreprocessedEntityMap.end() &&
4699 "Corrupted global preprocessed entity map");
4700 ModuleFile *M = I->second;
4701 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4702 return std::make_pair(M, LocalIndex);
4703}
4704
4705std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4706ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4707 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4708 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4709 Mod.NumPreprocessedEntities);
4710
4711 return std::make_pair(PreprocessingRecord::iterator(),
4712 PreprocessingRecord::iterator());
4713}
4714
4715std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4716ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4717 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4718 ModuleDeclIterator(this, &Mod,
4719 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4720}
4721
4722PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4723 PreprocessedEntityID PPID = Index+1;
4724 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4725 ModuleFile &M = *PPInfo.first;
4726 unsigned LocalIndex = PPInfo.second;
4727 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4728
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 if (!PP.getPreprocessingRecord()) {
4730 Error("no preprocessing record");
4731 return 0;
4732 }
4733
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004734 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4735 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4736
4737 llvm::BitstreamEntry Entry =
4738 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4739 if (Entry.Kind != llvm::BitstreamEntry::Record)
4740 return 0;
4741
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 // Read the record.
4743 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4744 ReadSourceLocation(M, PPOffs.End));
4745 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004746 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 RecordData Record;
4748 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004749 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4750 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 switch (RecType) {
4752 case PPD_MACRO_EXPANSION: {
4753 bool isBuiltin = Record[0];
4754 IdentifierInfo *Name = 0;
4755 MacroDefinition *Def = 0;
4756 if (isBuiltin)
4757 Name = getLocalIdentifier(M, Record[1]);
4758 else {
4759 PreprocessedEntityID
4760 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4761 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4762 }
4763
4764 MacroExpansion *ME;
4765 if (isBuiltin)
4766 ME = new (PPRec) MacroExpansion(Name, Range);
4767 else
4768 ME = new (PPRec) MacroExpansion(Def, Range);
4769
4770 return ME;
4771 }
4772
4773 case PPD_MACRO_DEFINITION: {
4774 // Decode the identifier info and then check again; if the macro is
4775 // still defined and associated with the identifier,
4776 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4777 MacroDefinition *MD
4778 = new (PPRec) MacroDefinition(II, Range);
4779
4780 if (DeserializationListener)
4781 DeserializationListener->MacroDefinitionRead(PPID, MD);
4782
4783 return MD;
4784 }
4785
4786 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004787 const char *FullFileNameStart = Blob.data() + Record[0];
4788 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 const FileEntry *File = 0;
4790 if (!FullFileName.empty())
4791 File = PP.getFileManager().getFile(FullFileName);
4792
4793 // FIXME: Stable encoding
4794 InclusionDirective::InclusionKind Kind
4795 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4796 InclusionDirective *ID
4797 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004798 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 Record[1], Record[3],
4800 File,
4801 Range);
4802 return ID;
4803 }
4804 }
4805
4806 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4807}
4808
4809/// \brief \arg SLocMapI points at a chunk of a module that contains no
4810/// preprocessed entities or the entities it contains are not the ones we are
4811/// looking for. Find the next module that contains entities and return the ID
4812/// of the first entry.
4813PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4814 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4815 ++SLocMapI;
4816 for (GlobalSLocOffsetMapType::const_iterator
4817 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4818 ModuleFile &M = *SLocMapI->second;
4819 if (M.NumPreprocessedEntities)
4820 return M.BasePreprocessedEntityID;
4821 }
4822
4823 return getTotalNumPreprocessedEntities();
4824}
4825
4826namespace {
4827
4828template <unsigned PPEntityOffset::*PPLoc>
4829struct PPEntityComp {
4830 const ASTReader &Reader;
4831 ModuleFile &M;
4832
4833 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4834
4835 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4836 SourceLocation LHS = getLoc(L);
4837 SourceLocation RHS = getLoc(R);
4838 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4839 }
4840
4841 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4842 SourceLocation LHS = getLoc(L);
4843 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4844 }
4845
4846 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4847 SourceLocation RHS = getLoc(R);
4848 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4849 }
4850
4851 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4852 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4853 }
4854};
4855
4856}
4857
4858/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4859PreprocessedEntityID
4860ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4861 if (SourceMgr.isLocalSourceLocation(BLoc))
4862 return getTotalNumPreprocessedEntities();
4863
4864 GlobalSLocOffsetMapType::const_iterator
4865 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004866 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4868 "Corrupted global sloc offset map");
4869
4870 if (SLocMapI->second->NumPreprocessedEntities == 0)
4871 return findNextPreprocessedEntity(SLocMapI);
4872
4873 ModuleFile &M = *SLocMapI->second;
4874 typedef const PPEntityOffset *pp_iterator;
4875 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4876 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4877
4878 size_t Count = M.NumPreprocessedEntities;
4879 size_t Half;
4880 pp_iterator First = pp_begin;
4881 pp_iterator PPI;
4882
4883 // Do a binary search manually instead of using std::lower_bound because
4884 // The end locations of entities may be unordered (when a macro expansion
4885 // is inside another macro argument), but for this case it is not important
4886 // whether we get the first macro expansion or its containing macro.
4887 while (Count > 0) {
4888 Half = Count/2;
4889 PPI = First;
4890 std::advance(PPI, Half);
4891 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4892 BLoc)){
4893 First = PPI;
4894 ++First;
4895 Count = Count - Half - 1;
4896 } else
4897 Count = Half;
4898 }
4899
4900 if (PPI == pp_end)
4901 return findNextPreprocessedEntity(SLocMapI);
4902
4903 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4904}
4905
4906/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4907PreprocessedEntityID
4908ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4909 if (SourceMgr.isLocalSourceLocation(ELoc))
4910 return getTotalNumPreprocessedEntities();
4911
4912 GlobalSLocOffsetMapType::const_iterator
4913 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004914 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4916 "Corrupted global sloc offset map");
4917
4918 if (SLocMapI->second->NumPreprocessedEntities == 0)
4919 return findNextPreprocessedEntity(SLocMapI);
4920
4921 ModuleFile &M = *SLocMapI->second;
4922 typedef const PPEntityOffset *pp_iterator;
4923 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4924 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4925 pp_iterator PPI =
4926 std::upper_bound(pp_begin, pp_end, ELoc,
4927 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4928
4929 if (PPI == pp_end)
4930 return findNextPreprocessedEntity(SLocMapI);
4931
4932 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4933}
4934
4935/// \brief Returns a pair of [Begin, End) indices of preallocated
4936/// preprocessed entities that \arg Range encompasses.
4937std::pair<unsigned, unsigned>
4938 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4939 if (Range.isInvalid())
4940 return std::make_pair(0,0);
4941 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4942
4943 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4944 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4945 return std::make_pair(BeginID, EndID);
4946}
4947
4948/// \brief Optionally returns true or false if the preallocated preprocessed
4949/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004950Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 FileID FID) {
4952 if (FID.isInvalid())
4953 return false;
4954
4955 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4956 ModuleFile &M = *PPInfo.first;
4957 unsigned LocalIndex = PPInfo.second;
4958 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4959
4960 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4961 if (Loc.isInvalid())
4962 return false;
4963
4964 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4965 return true;
4966 else
4967 return false;
4968}
4969
4970namespace {
4971 /// \brief Visitor used to search for information about a header file.
4972 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 const FileEntry *FE;
4974
David Blaikie05785d12013-02-20 22:23:23 +00004975 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004976
4977 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004978 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4979 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004980
4981 static bool visit(ModuleFile &M, void *UserData) {
4982 HeaderFileInfoVisitor *This
4983 = static_cast<HeaderFileInfoVisitor *>(UserData);
4984
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 HeaderFileInfoLookupTable *Table
4986 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4987 if (!Table)
4988 return false;
4989
4990 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004991 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 if (Pos == Table->end())
4993 return false;
4994
4995 This->HFI = *Pos;
4996 return true;
4997 }
4998
David Blaikie05785d12013-02-20 22:23:23 +00004999 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 };
5001}
5002
5003HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005004 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005006 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005008
5009 return HeaderFileInfo();
5010}
5011
5012void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5013 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005014 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5016 ModuleFile &F = *(*I);
5017 unsigned Idx = 0;
5018 DiagStates.clear();
5019 assert(!Diag.DiagStates.empty());
5020 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5021 while (Idx < F.PragmaDiagMappings.size()) {
5022 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5023 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5024 if (DiagStateID != 0) {
5025 Diag.DiagStatePoints.push_back(
5026 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5027 FullSourceLoc(Loc, SourceMgr)));
5028 continue;
5029 }
5030
5031 assert(DiagStateID == 0);
5032 // A new DiagState was created here.
5033 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5034 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5035 DiagStates.push_back(NewState);
5036 Diag.DiagStatePoints.push_back(
5037 DiagnosticsEngine::DiagStatePoint(NewState,
5038 FullSourceLoc(Loc, SourceMgr)));
5039 while (1) {
5040 assert(Idx < F.PragmaDiagMappings.size() &&
5041 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5042 if (Idx >= F.PragmaDiagMappings.size()) {
5043 break; // Something is messed up but at least avoid infinite loop in
5044 // release build.
5045 }
5046 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5047 if (DiagID == (unsigned)-1) {
5048 break; // no more diag/map pairs for this location.
5049 }
5050 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5051 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5052 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5053 }
5054 }
5055 }
5056}
5057
5058/// \brief Get the correct cursor and offset for loading a type.
5059ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5060 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5061 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5062 ModuleFile *M = I->second;
5063 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5064}
5065
5066/// \brief Read and return the type with the given index..
5067///
5068/// The index is the type ID, shifted and minus the number of predefs. This
5069/// routine actually reads the record corresponding to the type at the given
5070/// location. It is a helper routine for GetType, which deals with reading type
5071/// IDs.
5072QualType ASTReader::readTypeRecord(unsigned Index) {
5073 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005074 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005075
5076 // Keep track of where we are in the stream, then jump back there
5077 // after reading this type.
5078 SavedStreamPosition SavedPosition(DeclsCursor);
5079
5080 ReadingKindTracker ReadingKind(Read_Type, *this);
5081
5082 // Note that we are loading a type record.
5083 Deserializing AType(this);
5084
5085 unsigned Idx = 0;
5086 DeclsCursor.JumpToBit(Loc.Offset);
5087 RecordData Record;
5088 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005089 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 case TYPE_EXT_QUAL: {
5091 if (Record.size() != 2) {
5092 Error("Incorrect encoding of extended qualifier type");
5093 return QualType();
5094 }
5095 QualType Base = readType(*Loc.F, Record, Idx);
5096 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5097 return Context.getQualifiedType(Base, Quals);
5098 }
5099
5100 case TYPE_COMPLEX: {
5101 if (Record.size() != 1) {
5102 Error("Incorrect encoding of complex type");
5103 return QualType();
5104 }
5105 QualType ElemType = readType(*Loc.F, Record, Idx);
5106 return Context.getComplexType(ElemType);
5107 }
5108
5109 case TYPE_POINTER: {
5110 if (Record.size() != 1) {
5111 Error("Incorrect encoding of pointer type");
5112 return QualType();
5113 }
5114 QualType PointeeType = readType(*Loc.F, Record, Idx);
5115 return Context.getPointerType(PointeeType);
5116 }
5117
Reid Kleckner8a365022013-06-24 17:51:48 +00005118 case TYPE_DECAYED: {
5119 if (Record.size() != 1) {
5120 Error("Incorrect encoding of decayed type");
5121 return QualType();
5122 }
5123 QualType OriginalType = readType(*Loc.F, Record, Idx);
5124 QualType DT = Context.getAdjustedParameterType(OriginalType);
5125 if (!isa<DecayedType>(DT))
5126 Error("Decayed type does not decay");
5127 return DT;
5128 }
5129
Reid Kleckner0503a872013-12-05 01:23:43 +00005130 case TYPE_ADJUSTED: {
5131 if (Record.size() != 2) {
5132 Error("Incorrect encoding of adjusted type");
5133 return QualType();
5134 }
5135 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5136 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5137 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5138 }
5139
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 case TYPE_BLOCK_POINTER: {
5141 if (Record.size() != 1) {
5142 Error("Incorrect encoding of block pointer type");
5143 return QualType();
5144 }
5145 QualType PointeeType = readType(*Loc.F, Record, Idx);
5146 return Context.getBlockPointerType(PointeeType);
5147 }
5148
5149 case TYPE_LVALUE_REFERENCE: {
5150 if (Record.size() != 2) {
5151 Error("Incorrect encoding of lvalue reference type");
5152 return QualType();
5153 }
5154 QualType PointeeType = readType(*Loc.F, Record, Idx);
5155 return Context.getLValueReferenceType(PointeeType, Record[1]);
5156 }
5157
5158 case TYPE_RVALUE_REFERENCE: {
5159 if (Record.size() != 1) {
5160 Error("Incorrect encoding of rvalue reference type");
5161 return QualType();
5162 }
5163 QualType PointeeType = readType(*Loc.F, Record, Idx);
5164 return Context.getRValueReferenceType(PointeeType);
5165 }
5166
5167 case TYPE_MEMBER_POINTER: {
5168 if (Record.size() != 2) {
5169 Error("Incorrect encoding of member pointer type");
5170 return QualType();
5171 }
5172 QualType PointeeType = readType(*Loc.F, Record, Idx);
5173 QualType ClassType = readType(*Loc.F, Record, Idx);
5174 if (PointeeType.isNull() || ClassType.isNull())
5175 return QualType();
5176
5177 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5178 }
5179
5180 case TYPE_CONSTANT_ARRAY: {
5181 QualType ElementType = readType(*Loc.F, Record, Idx);
5182 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5183 unsigned IndexTypeQuals = Record[2];
5184 unsigned Idx = 3;
5185 llvm::APInt Size = ReadAPInt(Record, Idx);
5186 return Context.getConstantArrayType(ElementType, Size,
5187 ASM, IndexTypeQuals);
5188 }
5189
5190 case TYPE_INCOMPLETE_ARRAY: {
5191 QualType ElementType = readType(*Loc.F, Record, Idx);
5192 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5193 unsigned IndexTypeQuals = Record[2];
5194 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5195 }
5196
5197 case TYPE_VARIABLE_ARRAY: {
5198 QualType ElementType = readType(*Loc.F, Record, Idx);
5199 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5200 unsigned IndexTypeQuals = Record[2];
5201 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5202 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5203 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5204 ASM, IndexTypeQuals,
5205 SourceRange(LBLoc, RBLoc));
5206 }
5207
5208 case TYPE_VECTOR: {
5209 if (Record.size() != 3) {
5210 Error("incorrect encoding of vector type in AST file");
5211 return QualType();
5212 }
5213
5214 QualType ElementType = readType(*Loc.F, Record, Idx);
5215 unsigned NumElements = Record[1];
5216 unsigned VecKind = Record[2];
5217 return Context.getVectorType(ElementType, NumElements,
5218 (VectorType::VectorKind)VecKind);
5219 }
5220
5221 case TYPE_EXT_VECTOR: {
5222 if (Record.size() != 3) {
5223 Error("incorrect encoding of extended vector type in AST file");
5224 return QualType();
5225 }
5226
5227 QualType ElementType = readType(*Loc.F, Record, Idx);
5228 unsigned NumElements = Record[1];
5229 return Context.getExtVectorType(ElementType, NumElements);
5230 }
5231
5232 case TYPE_FUNCTION_NO_PROTO: {
5233 if (Record.size() != 6) {
5234 Error("incorrect encoding of no-proto function type");
5235 return QualType();
5236 }
5237 QualType ResultType = readType(*Loc.F, Record, Idx);
5238 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5239 (CallingConv)Record[4], Record[5]);
5240 return Context.getFunctionNoProtoType(ResultType, Info);
5241 }
5242
5243 case TYPE_FUNCTION_PROTO: {
5244 QualType ResultType = readType(*Loc.F, Record, Idx);
5245
5246 FunctionProtoType::ExtProtoInfo EPI;
5247 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5248 /*hasregparm*/ Record[2],
5249 /*regparm*/ Record[3],
5250 static_cast<CallingConv>(Record[4]),
5251 /*produces*/ Record[5]);
5252
5253 unsigned Idx = 6;
5254 unsigned NumParams = Record[Idx++];
5255 SmallVector<QualType, 16> ParamTypes;
5256 for (unsigned I = 0; I != NumParams; ++I)
5257 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5258
5259 EPI.Variadic = Record[Idx++];
5260 EPI.HasTrailingReturn = Record[Idx++];
5261 EPI.TypeQuals = Record[Idx++];
5262 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005263 SmallVector<QualType, 8> ExceptionStorage;
5264 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005265 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 }
5267
5268 case TYPE_UNRESOLVED_USING: {
5269 unsigned Idx = 0;
5270 return Context.getTypeDeclType(
5271 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5272 }
5273
5274 case TYPE_TYPEDEF: {
5275 if (Record.size() != 2) {
5276 Error("incorrect encoding of typedef type");
5277 return QualType();
5278 }
5279 unsigned Idx = 0;
5280 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5281 QualType Canonical = readType(*Loc.F, Record, Idx);
5282 if (!Canonical.isNull())
5283 Canonical = Context.getCanonicalType(Canonical);
5284 return Context.getTypedefType(Decl, Canonical);
5285 }
5286
5287 case TYPE_TYPEOF_EXPR:
5288 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5289
5290 case TYPE_TYPEOF: {
5291 if (Record.size() != 1) {
5292 Error("incorrect encoding of typeof(type) in AST file");
5293 return QualType();
5294 }
5295 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5296 return Context.getTypeOfType(UnderlyingType);
5297 }
5298
5299 case TYPE_DECLTYPE: {
5300 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5301 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5302 }
5303
5304 case TYPE_UNARY_TRANSFORM: {
5305 QualType BaseType = readType(*Loc.F, Record, Idx);
5306 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5307 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5308 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5309 }
5310
Richard Smith74aeef52013-04-26 16:15:35 +00005311 case TYPE_AUTO: {
5312 QualType Deduced = readType(*Loc.F, Record, Idx);
5313 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005314 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005315 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005317
5318 case TYPE_RECORD: {
5319 if (Record.size() != 2) {
5320 Error("incorrect encoding of record type");
5321 return QualType();
5322 }
5323 unsigned Idx = 0;
5324 bool IsDependent = Record[Idx++];
5325 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5326 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5327 QualType T = Context.getRecordType(RD);
5328 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5329 return T;
5330 }
5331
5332 case TYPE_ENUM: {
5333 if (Record.size() != 2) {
5334 Error("incorrect encoding of enum type");
5335 return QualType();
5336 }
5337 unsigned Idx = 0;
5338 bool IsDependent = Record[Idx++];
5339 QualType T
5340 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5341 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5342 return T;
5343 }
5344
5345 case TYPE_ATTRIBUTED: {
5346 if (Record.size() != 3) {
5347 Error("incorrect encoding of attributed type");
5348 return QualType();
5349 }
5350 QualType modifiedType = readType(*Loc.F, Record, Idx);
5351 QualType equivalentType = readType(*Loc.F, Record, Idx);
5352 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5353 return Context.getAttributedType(kind, modifiedType, equivalentType);
5354 }
5355
5356 case TYPE_PAREN: {
5357 if (Record.size() != 1) {
5358 Error("incorrect encoding of paren type");
5359 return QualType();
5360 }
5361 QualType InnerType = readType(*Loc.F, Record, Idx);
5362 return Context.getParenType(InnerType);
5363 }
5364
5365 case TYPE_PACK_EXPANSION: {
5366 if (Record.size() != 2) {
5367 Error("incorrect encoding of pack expansion type");
5368 return QualType();
5369 }
5370 QualType Pattern = readType(*Loc.F, Record, Idx);
5371 if (Pattern.isNull())
5372 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005373 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 if (Record[1])
5375 NumExpansions = Record[1] - 1;
5376 return Context.getPackExpansionType(Pattern, NumExpansions);
5377 }
5378
5379 case TYPE_ELABORATED: {
5380 unsigned Idx = 0;
5381 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5382 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5383 QualType NamedType = readType(*Loc.F, Record, Idx);
5384 return Context.getElaboratedType(Keyword, NNS, NamedType);
5385 }
5386
5387 case TYPE_OBJC_INTERFACE: {
5388 unsigned Idx = 0;
5389 ObjCInterfaceDecl *ItfD
5390 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5391 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5392 }
5393
5394 case TYPE_OBJC_OBJECT: {
5395 unsigned Idx = 0;
5396 QualType Base = readType(*Loc.F, Record, Idx);
5397 unsigned NumProtos = Record[Idx++];
5398 SmallVector<ObjCProtocolDecl*, 4> Protos;
5399 for (unsigned I = 0; I != NumProtos; ++I)
5400 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5401 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5402 }
5403
5404 case TYPE_OBJC_OBJECT_POINTER: {
5405 unsigned Idx = 0;
5406 QualType Pointee = readType(*Loc.F, Record, Idx);
5407 return Context.getObjCObjectPointerType(Pointee);
5408 }
5409
5410 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5411 unsigned Idx = 0;
5412 QualType Parm = readType(*Loc.F, Record, Idx);
5413 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005414 return Context.getSubstTemplateTypeParmType(
5415 cast<TemplateTypeParmType>(Parm),
5416 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005417 }
5418
5419 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5420 unsigned Idx = 0;
5421 QualType Parm = readType(*Loc.F, Record, Idx);
5422 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5423 return Context.getSubstTemplateTypeParmPackType(
5424 cast<TemplateTypeParmType>(Parm),
5425 ArgPack);
5426 }
5427
5428 case TYPE_INJECTED_CLASS_NAME: {
5429 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5430 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5431 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5432 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005433 const Type *T;
5434 if (const Type *Existing = D->getTypeForDecl())
5435 T = Existing;
5436 else if (auto *Prev = D->getPreviousDecl())
5437 T = Prev->getTypeForDecl();
5438 else
5439 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5440 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 }
5442
5443 case TYPE_TEMPLATE_TYPE_PARM: {
5444 unsigned Idx = 0;
5445 unsigned Depth = Record[Idx++];
5446 unsigned Index = Record[Idx++];
5447 bool Pack = Record[Idx++];
5448 TemplateTypeParmDecl *D
5449 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5450 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5451 }
5452
5453 case TYPE_DEPENDENT_NAME: {
5454 unsigned Idx = 0;
5455 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5456 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5457 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5458 QualType Canon = readType(*Loc.F, Record, Idx);
5459 if (!Canon.isNull())
5460 Canon = Context.getCanonicalType(Canon);
5461 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5462 }
5463
5464 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5465 unsigned Idx = 0;
5466 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5467 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5468 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5469 unsigned NumArgs = Record[Idx++];
5470 SmallVector<TemplateArgument, 8> Args;
5471 Args.reserve(NumArgs);
5472 while (NumArgs--)
5473 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5474 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5475 Args.size(), Args.data());
5476 }
5477
5478 case TYPE_DEPENDENT_SIZED_ARRAY: {
5479 unsigned Idx = 0;
5480
5481 // ArrayType
5482 QualType ElementType = readType(*Loc.F, Record, Idx);
5483 ArrayType::ArraySizeModifier ASM
5484 = (ArrayType::ArraySizeModifier)Record[Idx++];
5485 unsigned IndexTypeQuals = Record[Idx++];
5486
5487 // DependentSizedArrayType
5488 Expr *NumElts = ReadExpr(*Loc.F);
5489 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5490
5491 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5492 IndexTypeQuals, Brackets);
5493 }
5494
5495 case TYPE_TEMPLATE_SPECIALIZATION: {
5496 unsigned Idx = 0;
5497 bool IsDependent = Record[Idx++];
5498 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5499 SmallVector<TemplateArgument, 8> Args;
5500 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5501 QualType Underlying = readType(*Loc.F, Record, Idx);
5502 QualType T;
5503 if (Underlying.isNull())
5504 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5505 Args.size());
5506 else
5507 T = Context.getTemplateSpecializationType(Name, Args.data(),
5508 Args.size(), Underlying);
5509 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5510 return T;
5511 }
5512
5513 case TYPE_ATOMIC: {
5514 if (Record.size() != 1) {
5515 Error("Incorrect encoding of atomic type");
5516 return QualType();
5517 }
5518 QualType ValueType = readType(*Loc.F, Record, Idx);
5519 return Context.getAtomicType(ValueType);
5520 }
5521 }
5522 llvm_unreachable("Invalid TypeCode!");
5523}
5524
Richard Smith564417a2014-03-20 21:47:22 +00005525void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5526 SmallVectorImpl<QualType> &Exceptions,
5527 FunctionProtoType::ExtProtoInfo &EPI,
5528 const RecordData &Record, unsigned &Idx) {
5529 ExceptionSpecificationType EST =
5530 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5531 EPI.ExceptionSpecType = EST;
5532 if (EST == EST_Dynamic) {
5533 EPI.NumExceptions = Record[Idx++];
5534 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5535 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5536 EPI.Exceptions = Exceptions.data();
5537 } else if (EST == EST_ComputedNoexcept) {
5538 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5539 } else if (EST == EST_Uninstantiated) {
5540 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5541 EPI.ExceptionSpecTemplate =
5542 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5543 } else if (EST == EST_Unevaluated) {
5544 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5545 }
5546}
5547
Guy Benyei11169dd2012-12-18 14:30:41 +00005548class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5549 ASTReader &Reader;
5550 ModuleFile &F;
5551 const ASTReader::RecordData &Record;
5552 unsigned &Idx;
5553
5554 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5555 unsigned &I) {
5556 return Reader.ReadSourceLocation(F, R, I);
5557 }
5558
5559 template<typename T>
5560 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5561 return Reader.ReadDeclAs<T>(F, Record, Idx);
5562 }
5563
5564public:
5565 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5566 const ASTReader::RecordData &Record, unsigned &Idx)
5567 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5568 { }
5569
5570 // We want compile-time assurance that we've enumerated all of
5571 // these, so unfortunately we have to declare them first, then
5572 // define them out-of-line.
5573#define ABSTRACT_TYPELOC(CLASS, PARENT)
5574#define TYPELOC(CLASS, PARENT) \
5575 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5576#include "clang/AST/TypeLocNodes.def"
5577
5578 void VisitFunctionTypeLoc(FunctionTypeLoc);
5579 void VisitArrayTypeLoc(ArrayTypeLoc);
5580};
5581
5582void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5583 // nothing to do
5584}
5585void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5586 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5587 if (TL.needsExtraLocalData()) {
5588 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5589 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5590 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5591 TL.setModeAttr(Record[Idx++]);
5592 }
5593}
5594void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5595 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5596}
5597void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5598 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5599}
Reid Kleckner8a365022013-06-24 17:51:48 +00005600void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5601 // nothing to do
5602}
Reid Kleckner0503a872013-12-05 01:23:43 +00005603void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5604 // nothing to do
5605}
Guy Benyei11169dd2012-12-18 14:30:41 +00005606void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5607 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5610 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5611}
5612void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5613 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5614}
5615void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5616 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5617 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5618}
5619void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5620 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5621 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5622 if (Record[Idx++])
5623 TL.setSizeExpr(Reader.ReadExpr(F));
5624 else
5625 TL.setSizeExpr(0);
5626}
5627void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5628 VisitArrayTypeLoc(TL);
5629}
5630void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5631 VisitArrayTypeLoc(TL);
5632}
5633void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5634 VisitArrayTypeLoc(TL);
5635}
5636void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5637 DependentSizedArrayTypeLoc TL) {
5638 VisitArrayTypeLoc(TL);
5639}
5640void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5641 DependentSizedExtVectorTypeLoc TL) {
5642 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5643}
5644void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5648 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5649}
5650void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5651 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5652 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5653 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5654 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005655 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5656 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 }
5658}
5659void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5660 VisitFunctionTypeLoc(TL);
5661}
5662void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5663 VisitFunctionTypeLoc(TL);
5664}
5665void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5669 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5670}
5671void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5672 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5673 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5674 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5677 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5678 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5679 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5680 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5681}
5682void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5683 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5684}
5685void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5686 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5687 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5688 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5689 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5690}
5691void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5692 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5695 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5696}
5697void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5698 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5699}
5700void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5701 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5702 if (TL.hasAttrOperand()) {
5703 SourceRange range;
5704 range.setBegin(ReadSourceLocation(Record, Idx));
5705 range.setEnd(ReadSourceLocation(Record, Idx));
5706 TL.setAttrOperandParensRange(range);
5707 }
5708 if (TL.hasAttrExprOperand()) {
5709 if (Record[Idx++])
5710 TL.setAttrExprOperand(Reader.ReadExpr(F));
5711 else
5712 TL.setAttrExprOperand(0);
5713 } else if (TL.hasAttrEnumOperand())
5714 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5715}
5716void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5717 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5718}
5719void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5720 SubstTemplateTypeParmTypeLoc TL) {
5721 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5722}
5723void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5724 SubstTemplateTypeParmPackTypeLoc TL) {
5725 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5728 TemplateSpecializationTypeLoc TL) {
5729 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5730 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5731 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5732 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5733 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5734 TL.setArgLocInfo(i,
5735 Reader.GetTemplateArgumentLocInfo(F,
5736 TL.getTypePtr()->getArg(i).getKind(),
5737 Record, Idx));
5738}
5739void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5740 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5741 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5742}
5743void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5744 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5745 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5746}
5747void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5748 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5749}
5750void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5751 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5752 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5756 DependentTemplateSpecializationTypeLoc TL) {
5757 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5758 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5759 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5760 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5761 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5762 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5763 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5764 TL.setArgLocInfo(I,
5765 Reader.GetTemplateArgumentLocInfo(F,
5766 TL.getTypePtr()->getArg(I).getKind(),
5767 Record, Idx));
5768}
5769void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5770 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5771}
5772void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5773 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5774}
5775void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5776 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5777 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5778 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5779 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5780 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5781}
5782void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5783 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5784}
5785void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5786 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5787 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5788 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5789}
5790
5791TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5792 const RecordData &Record,
5793 unsigned &Idx) {
5794 QualType InfoTy = readType(F, Record, Idx);
5795 if (InfoTy.isNull())
5796 return 0;
5797
5798 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5799 TypeLocReader TLR(*this, F, Record, Idx);
5800 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5801 TLR.Visit(TL);
5802 return TInfo;
5803}
5804
5805QualType ASTReader::GetType(TypeID ID) {
5806 unsigned FastQuals = ID & Qualifiers::FastMask;
5807 unsigned Index = ID >> Qualifiers::FastWidth;
5808
5809 if (Index < NUM_PREDEF_TYPE_IDS) {
5810 QualType T;
5811 switch ((PredefinedTypeIDs)Index) {
5812 case PREDEF_TYPE_NULL_ID: return QualType();
5813 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5814 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5815
5816 case PREDEF_TYPE_CHAR_U_ID:
5817 case PREDEF_TYPE_CHAR_S_ID:
5818 // FIXME: Check that the signedness of CharTy is correct!
5819 T = Context.CharTy;
5820 break;
5821
5822 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5823 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5824 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5825 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5826 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5827 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5828 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5829 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5830 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5831 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5832 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5833 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5834 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5835 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5836 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5837 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5838 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5839 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5840 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5841 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5842 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5843 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5844 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5845 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5846 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5847 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5848 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5849 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005850 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5851 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5852 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5853 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5854 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5855 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005856 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005857 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005858 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5859
5860 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5861 T = Context.getAutoRRefDeductType();
5862 break;
5863
5864 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5865 T = Context.ARCUnbridgedCastTy;
5866 break;
5867
5868 case PREDEF_TYPE_VA_LIST_TAG:
5869 T = Context.getVaListTagType();
5870 break;
5871
5872 case PREDEF_TYPE_BUILTIN_FN:
5873 T = Context.BuiltinFnTy;
5874 break;
5875 }
5876
5877 assert(!T.isNull() && "Unknown predefined type");
5878 return T.withFastQualifiers(FastQuals);
5879 }
5880
5881 Index -= NUM_PREDEF_TYPE_IDS;
5882 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5883 if (TypesLoaded[Index].isNull()) {
5884 TypesLoaded[Index] = readTypeRecord(Index);
5885 if (TypesLoaded[Index].isNull())
5886 return QualType();
5887
5888 TypesLoaded[Index]->setFromAST();
5889 if (DeserializationListener)
5890 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5891 TypesLoaded[Index]);
5892 }
5893
5894 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5895}
5896
5897QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5898 return GetType(getGlobalTypeID(F, LocalID));
5899}
5900
5901serialization::TypeID
5902ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5903 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5904 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5905
5906 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5907 return LocalID;
5908
5909 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5910 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5911 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5912
5913 unsigned GlobalIndex = LocalIndex + I->second;
5914 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5915}
5916
5917TemplateArgumentLocInfo
5918ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5919 TemplateArgument::ArgKind Kind,
5920 const RecordData &Record,
5921 unsigned &Index) {
5922 switch (Kind) {
5923 case TemplateArgument::Expression:
5924 return ReadExpr(F);
5925 case TemplateArgument::Type:
5926 return GetTypeSourceInfo(F, Record, Index);
5927 case TemplateArgument::Template: {
5928 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5929 Index);
5930 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5931 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5932 SourceLocation());
5933 }
5934 case TemplateArgument::TemplateExpansion: {
5935 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5936 Index);
5937 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5938 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5939 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5940 EllipsisLoc);
5941 }
5942 case TemplateArgument::Null:
5943 case TemplateArgument::Integral:
5944 case TemplateArgument::Declaration:
5945 case TemplateArgument::NullPtr:
5946 case TemplateArgument::Pack:
5947 // FIXME: Is this right?
5948 return TemplateArgumentLocInfo();
5949 }
5950 llvm_unreachable("unexpected template argument loc");
5951}
5952
5953TemplateArgumentLoc
5954ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5955 const RecordData &Record, unsigned &Index) {
5956 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5957
5958 if (Arg.getKind() == TemplateArgument::Expression) {
5959 if (Record[Index++]) // bool InfoHasSameExpr.
5960 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5961 }
5962 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5963 Record, Index));
5964}
5965
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005966const ASTTemplateArgumentListInfo*
5967ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5968 const RecordData &Record,
5969 unsigned &Index) {
5970 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5971 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5972 unsigned NumArgsAsWritten = Record[Index++];
5973 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5974 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5975 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5976 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5977}
5978
Guy Benyei11169dd2012-12-18 14:30:41 +00005979Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5980 return GetDecl(ID);
5981}
5982
Richard Smithcd45dbc2014-04-19 03:48:30 +00005983uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5984 const RecordData &Record,
5985 unsigned &Idx) {
5986 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5987 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005989 }
5990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 unsigned LocalID = Record[Idx++];
5992 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5993}
5994
5995CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5996 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005997 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 SavedStreamPosition SavedPosition(Cursor);
5999 Cursor.JumpToBit(Loc.Offset);
6000 ReadingKindTracker ReadingKind(Read_Decl, *this);
6001 RecordData Record;
6002 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006003 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006004 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006005 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 return 0;
6007 }
6008
6009 unsigned Idx = 0;
6010 unsigned NumBases = Record[Idx++];
6011 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6012 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6013 for (unsigned I = 0; I != NumBases; ++I)
6014 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6015 return Bases;
6016}
6017
6018serialization::DeclID
6019ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6020 if (LocalID < NUM_PREDEF_DECL_IDS)
6021 return LocalID;
6022
6023 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6024 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6025 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6026
6027 return LocalID + I->second;
6028}
6029
6030bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6031 ModuleFile &M) const {
6032 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6033 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6034 return &M == I->second;
6035}
6036
Douglas Gregor9f782892013-01-21 15:25:38 +00006037ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 if (!D->isFromASTFile())
6039 return 0;
6040 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6041 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6042 return I->second;
6043}
6044
6045SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6046 if (ID < NUM_PREDEF_DECL_IDS)
6047 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006048
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6050
6051 if (Index > DeclsLoaded.size()) {
6052 Error("declaration ID out-of-range for AST file");
6053 return SourceLocation();
6054 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006055
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 if (Decl *D = DeclsLoaded[Index])
6057 return D->getLocation();
6058
6059 unsigned RawLocation = 0;
6060 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6061 return ReadSourceLocation(*Rec.F, RawLocation);
6062}
6063
Richard Smithcd45dbc2014-04-19 03:48:30 +00006064Decl *ASTReader::GetExistingDecl(DeclID ID) {
6065 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 switch ((PredefinedDeclIDs)ID) {
6067 case PREDEF_DECL_NULL_ID:
6068 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006069
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6071 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006072
Guy Benyei11169dd2012-12-18 14:30:41 +00006073 case PREDEF_DECL_OBJC_ID_ID:
6074 return Context.getObjCIdDecl();
6075
6076 case PREDEF_DECL_OBJC_SEL_ID:
6077 return Context.getObjCSelDecl();
6078
6079 case PREDEF_DECL_OBJC_CLASS_ID:
6080 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6083 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006084
Guy Benyei11169dd2012-12-18 14:30:41 +00006085 case PREDEF_DECL_INT_128_ID:
6086 return Context.getInt128Decl();
6087
6088 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6089 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006090
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6092 return Context.getObjCInstanceTypeDecl();
6093
6094 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6095 return Context.getBuiltinVaListDecl();
6096 }
6097 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6100
6101 if (Index >= DeclsLoaded.size()) {
6102 assert(0 && "declaration ID out-of-range for AST file");
6103 Error("declaration ID out-of-range for AST file");
6104 return 0;
6105 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006106
6107 return DeclsLoaded[Index];
6108}
6109
6110Decl *ASTReader::GetDecl(DeclID ID) {
6111 if (ID < NUM_PREDEF_DECL_IDS)
6112 return GetExistingDecl(ID);
6113
6114 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6115
6116 if (Index >= DeclsLoaded.size()) {
6117 assert(0 && "declaration ID out-of-range for AST file");
6118 Error("declaration ID out-of-range for AST file");
6119 return 0;
6120 }
6121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (!DeclsLoaded[Index]) {
6123 ReadDeclRecord(ID);
6124 if (DeserializationListener)
6125 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6126 }
6127
6128 return DeclsLoaded[Index];
6129}
6130
6131DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6132 DeclID GlobalID) {
6133 if (GlobalID < NUM_PREDEF_DECL_IDS)
6134 return GlobalID;
6135
6136 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6137 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6138 ModuleFile *Owner = I->second;
6139
6140 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6141 = M.GlobalToLocalDeclIDs.find(Owner);
6142 if (Pos == M.GlobalToLocalDeclIDs.end())
6143 return 0;
6144
6145 return GlobalID - Owner->BaseDeclID + Pos->second;
6146}
6147
6148serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6149 const RecordData &Record,
6150 unsigned &Idx) {
6151 if (Idx >= Record.size()) {
6152 Error("Corrupted AST file");
6153 return 0;
6154 }
6155
6156 return getGlobalDeclID(F, Record[Idx++]);
6157}
6158
6159/// \brief Resolve the offset of a statement into a statement.
6160///
6161/// This operation will read a new statement from the external
6162/// source each time it is called, and is meant to be used via a
6163/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6164Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6165 // Switch case IDs are per Decl.
6166 ClearSwitchCaseIDs();
6167
6168 // Offset here is a global offset across the entire chain.
6169 RecordLocation Loc = getLocalBitOffset(Offset);
6170 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6171 return ReadStmtFromStream(*Loc.F);
6172}
6173
6174namespace {
6175 class FindExternalLexicalDeclsVisitor {
6176 ASTReader &Reader;
6177 const DeclContext *DC;
6178 bool (*isKindWeWant)(Decl::Kind);
6179
6180 SmallVectorImpl<Decl*> &Decls;
6181 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6182
6183 public:
6184 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6185 bool (*isKindWeWant)(Decl::Kind),
6186 SmallVectorImpl<Decl*> &Decls)
6187 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6188 {
6189 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6190 PredefsVisited[I] = false;
6191 }
6192
6193 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6194 if (Preorder)
6195 return false;
6196
6197 FindExternalLexicalDeclsVisitor *This
6198 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6199
6200 ModuleFile::DeclContextInfosMap::iterator Info
6201 = M.DeclContextInfos.find(This->DC);
6202 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6203 return false;
6204
6205 // Load all of the declaration IDs
6206 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6207 *IDE = ID + Info->second.NumLexicalDecls;
6208 ID != IDE; ++ID) {
6209 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6210 continue;
6211
6212 // Don't add predefined declarations to the lexical context more
6213 // than once.
6214 if (ID->second < NUM_PREDEF_DECL_IDS) {
6215 if (This->PredefsVisited[ID->second])
6216 continue;
6217
6218 This->PredefsVisited[ID->second] = true;
6219 }
6220
6221 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6222 if (!This->DC->isDeclInLexicalTraversal(D))
6223 This->Decls.push_back(D);
6224 }
6225 }
6226
6227 return false;
6228 }
6229 };
6230}
6231
6232ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6233 bool (*isKindWeWant)(Decl::Kind),
6234 SmallVectorImpl<Decl*> &Decls) {
6235 // There might be lexical decls in multiple modules, for the TU at
6236 // least. Walk all of the modules in the order they were loaded.
6237 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6238 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6239 ++NumLexicalDeclContextsRead;
6240 return ELR_Success;
6241}
6242
6243namespace {
6244
6245class DeclIDComp {
6246 ASTReader &Reader;
6247 ModuleFile &Mod;
6248
6249public:
6250 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6251
6252 bool operator()(LocalDeclID L, LocalDeclID R) const {
6253 SourceLocation LHS = getLocation(L);
6254 SourceLocation RHS = getLocation(R);
6255 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6256 }
6257
6258 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6259 SourceLocation RHS = getLocation(R);
6260 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6261 }
6262
6263 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6264 SourceLocation LHS = getLocation(L);
6265 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6266 }
6267
6268 SourceLocation getLocation(LocalDeclID ID) const {
6269 return Reader.getSourceManager().getFileLoc(
6270 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6271 }
6272};
6273
6274}
6275
6276void ASTReader::FindFileRegionDecls(FileID File,
6277 unsigned Offset, unsigned Length,
6278 SmallVectorImpl<Decl *> &Decls) {
6279 SourceManager &SM = getSourceManager();
6280
6281 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6282 if (I == FileDeclIDs.end())
6283 return;
6284
6285 FileDeclsInfo &DInfo = I->second;
6286 if (DInfo.Decls.empty())
6287 return;
6288
6289 SourceLocation
6290 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6291 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6292
6293 DeclIDComp DIDComp(*this, *DInfo.Mod);
6294 ArrayRef<serialization::LocalDeclID>::iterator
6295 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6296 BeginLoc, DIDComp);
6297 if (BeginIt != DInfo.Decls.begin())
6298 --BeginIt;
6299
6300 // If we are pointing at a top-level decl inside an objc container, we need
6301 // to backtrack until we find it otherwise we will fail to report that the
6302 // region overlaps with an objc container.
6303 while (BeginIt != DInfo.Decls.begin() &&
6304 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6305 ->isTopLevelDeclInObjCContainer())
6306 --BeginIt;
6307
6308 ArrayRef<serialization::LocalDeclID>::iterator
6309 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6310 EndLoc, DIDComp);
6311 if (EndIt != DInfo.Decls.end())
6312 ++EndIt;
6313
6314 for (ArrayRef<serialization::LocalDeclID>::iterator
6315 DIt = BeginIt; DIt != EndIt; ++DIt)
6316 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6317}
6318
6319namespace {
6320 /// \brief ModuleFile visitor used to perform name lookup into a
6321 /// declaration context.
6322 class DeclContextNameLookupVisitor {
6323 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006324 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 DeclarationName Name;
6326 SmallVectorImpl<NamedDecl *> &Decls;
6327
6328 public:
6329 DeclContextNameLookupVisitor(ASTReader &Reader,
6330 SmallVectorImpl<const DeclContext *> &Contexts,
6331 DeclarationName Name,
6332 SmallVectorImpl<NamedDecl *> &Decls)
6333 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6334
6335 static bool visit(ModuleFile &M, void *UserData) {
6336 DeclContextNameLookupVisitor *This
6337 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6338
6339 // Check whether we have any visible declaration information for
6340 // this context in this module.
6341 ModuleFile::DeclContextInfosMap::iterator Info;
6342 bool FoundInfo = false;
6343 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6344 Info = M.DeclContextInfos.find(This->Contexts[I]);
6345 if (Info != M.DeclContextInfos.end() &&
6346 Info->second.NameLookupTableData) {
6347 FoundInfo = true;
6348 break;
6349 }
6350 }
6351
6352 if (!FoundInfo)
6353 return false;
6354
6355 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006356 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006357 Info->second.NameLookupTableData;
6358 ASTDeclContextNameLookupTable::iterator Pos
6359 = LookupTable->find(This->Name);
6360 if (Pos == LookupTable->end())
6361 return false;
6362
6363 bool FoundAnything = false;
6364 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6365 for (; Data.first != Data.second; ++Data.first) {
6366 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6367 if (!ND)
6368 continue;
6369
6370 if (ND->getDeclName() != This->Name) {
6371 // A name might be null because the decl's redeclarable part is
6372 // currently read before reading its name. The lookup is triggered by
6373 // building that decl (likely indirectly), and so it is later in the
6374 // sense of "already existing" and can be ignored here.
6375 continue;
6376 }
6377
6378 // Record this declaration.
6379 FoundAnything = true;
6380 This->Decls.push_back(ND);
6381 }
6382
6383 return FoundAnything;
6384 }
6385 };
6386}
6387
Douglas Gregor9f782892013-01-21 15:25:38 +00006388/// \brief Retrieve the "definitive" module file for the definition of the
6389/// given declaration context, if there is one.
6390///
6391/// The "definitive" module file is the only place where we need to look to
6392/// find information about the declarations within the given declaration
6393/// context. For example, C++ and Objective-C classes, C structs/unions, and
6394/// Objective-C protocols, categories, and extensions are all defined in a
6395/// single place in the source code, so they have definitive module files
6396/// associated with them. C++ namespaces, on the other hand, can have
6397/// definitions in multiple different module files.
6398///
6399/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6400/// NDEBUG checking.
6401static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6402 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006403 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6404 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006405
6406 return 0;
6407}
6408
Richard Smith9ce12e32013-02-07 03:30:24 +00006409bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006410ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6411 DeclarationName Name) {
6412 assert(DC->hasExternalVisibleStorage() &&
6413 "DeclContext has no visible decls in storage");
6414 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006415 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006416
6417 SmallVector<NamedDecl *, 64> Decls;
6418
6419 // Compute the declaration contexts we need to look into. Multiple such
6420 // declaration contexts occur when two declaration contexts from disjoint
6421 // modules get merged, e.g., when two namespaces with the same name are
6422 // independently defined in separate modules.
6423 SmallVector<const DeclContext *, 2> Contexts;
6424 Contexts.push_back(DC);
6425
6426 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006427 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 if (Merged != MergedDecls.end()) {
6429 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6430 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6431 }
6432 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006433 if (isa<CXXRecordDecl>(DC)) {
6434 auto Merged = MergedLookups.find(DC);
6435 if (Merged != MergedLookups.end())
6436 Contexts.insert(Contexts.end(), Merged->second.begin(),
6437 Merged->second.end());
6438 }
6439
Guy Benyei11169dd2012-12-18 14:30:41 +00006440 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006441
6442 // If we can definitively determine which module file to look into,
6443 // only look there. Otherwise, look in all module files.
6444 ModuleFile *Definitive;
6445 if (Contexts.size() == 1 &&
6446 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6447 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6448 } else {
6449 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6450 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 ++NumVisibleDeclContextsRead;
6452 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006453 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006454}
6455
6456namespace {
6457 /// \brief ModuleFile visitor used to retrieve all visible names in a
6458 /// declaration context.
6459 class DeclContextAllNamesVisitor {
6460 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006461 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006462 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006463 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006464
6465 public:
6466 DeclContextAllNamesVisitor(ASTReader &Reader,
6467 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006468 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006469 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006470
6471 static bool visit(ModuleFile &M, void *UserData) {
6472 DeclContextAllNamesVisitor *This
6473 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6474
6475 // Check whether we have any visible declaration information for
6476 // this context in this module.
6477 ModuleFile::DeclContextInfosMap::iterator Info;
6478 bool FoundInfo = false;
6479 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6480 Info = M.DeclContextInfos.find(This->Contexts[I]);
6481 if (Info != M.DeclContextInfos.end() &&
6482 Info->second.NameLookupTableData) {
6483 FoundInfo = true;
6484 break;
6485 }
6486 }
6487
6488 if (!FoundInfo)
6489 return false;
6490
Richard Smith52e3fba2014-03-11 07:17:35 +00006491 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 Info->second.NameLookupTableData;
6493 bool FoundAnything = false;
6494 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006495 I = LookupTable->data_begin(), E = LookupTable->data_end();
6496 I != E;
6497 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006498 ASTDeclContextNameLookupTrait::data_type Data = *I;
6499 for (; Data.first != Data.second; ++Data.first) {
6500 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6501 *Data.first);
6502 if (!ND)
6503 continue;
6504
6505 // Record this declaration.
6506 FoundAnything = true;
6507 This->Decls[ND->getDeclName()].push_back(ND);
6508 }
6509 }
6510
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006511 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 }
6513 };
6514}
6515
6516void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6517 if (!DC->hasExternalVisibleStorage())
6518 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006519 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
6521 // Compute the declaration contexts we need to look into. Multiple such
6522 // declaration contexts occur when two declaration contexts from disjoint
6523 // modules get merged, e.g., when two namespaces with the same name are
6524 // independently defined in separate modules.
6525 SmallVector<const DeclContext *, 2> Contexts;
6526 Contexts.push_back(DC);
6527
6528 if (DC->isNamespace()) {
6529 MergedDeclsMap::iterator Merged
6530 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6531 if (Merged != MergedDecls.end()) {
6532 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6533 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6534 }
6535 }
6536
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006537 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6538 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6540 ++NumVisibleDeclContextsRead;
6541
Craig Topper79be4cd2013-07-05 04:33:53 +00006542 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6544 }
6545 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6546}
6547
6548/// \brief Under non-PCH compilation the consumer receives the objc methods
6549/// before receiving the implementation, and codegen depends on this.
6550/// We simulate this by deserializing and passing to consumer the methods of the
6551/// implementation before passing the deserialized implementation decl.
6552static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6553 ASTConsumer *Consumer) {
6554 assert(ImplD && Consumer);
6555
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006556 for (auto *I : ImplD->methods())
6557 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006558
6559 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6560}
6561
6562void ASTReader::PassInterestingDeclsToConsumer() {
6563 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006564
6565 if (PassingDeclsToConsumer)
6566 return;
6567
6568 // Guard variable to avoid recursively redoing the process of passing
6569 // decls to consumer.
6570 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6571 true);
6572
Guy Benyei11169dd2012-12-18 14:30:41 +00006573 while (!InterestingDecls.empty()) {
6574 Decl *D = InterestingDecls.front();
6575 InterestingDecls.pop_front();
6576
6577 PassInterestingDeclToConsumer(D);
6578 }
6579}
6580
6581void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6582 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6583 PassObjCImplDeclToConsumer(ImplD, Consumer);
6584 else
6585 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6586}
6587
6588void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6589 this->Consumer = Consumer;
6590
6591 if (!Consumer)
6592 return;
6593
Ben Langmuir332aafe2014-01-31 01:06:56 +00006594 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 // Force deserialization of this decl, which will cause it to be queued for
6596 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006597 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006599 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006600
6601 PassInterestingDeclsToConsumer();
6602}
6603
6604void ASTReader::PrintStats() {
6605 std::fprintf(stderr, "*** AST File Statistics:\n");
6606
6607 unsigned NumTypesLoaded
6608 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6609 QualType());
6610 unsigned NumDeclsLoaded
6611 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6612 (Decl *)0);
6613 unsigned NumIdentifiersLoaded
6614 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6615 IdentifiersLoaded.end(),
6616 (IdentifierInfo *)0);
6617 unsigned NumMacrosLoaded
6618 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6619 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006620 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 unsigned NumSelectorsLoaded
6622 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6623 SelectorsLoaded.end(),
6624 Selector());
6625
6626 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6627 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6628 NumSLocEntriesRead, TotalNumSLocEntries,
6629 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6630 if (!TypesLoaded.empty())
6631 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6632 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6633 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6634 if (!DeclsLoaded.empty())
6635 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6636 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6637 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6638 if (!IdentifiersLoaded.empty())
6639 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6640 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6641 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6642 if (!MacrosLoaded.empty())
6643 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6644 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6645 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6646 if (!SelectorsLoaded.empty())
6647 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6648 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6649 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6650 if (TotalNumStatements)
6651 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6652 NumStatementsRead, TotalNumStatements,
6653 ((float)NumStatementsRead/TotalNumStatements * 100));
6654 if (TotalNumMacros)
6655 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6656 NumMacrosRead, TotalNumMacros,
6657 ((float)NumMacrosRead/TotalNumMacros * 100));
6658 if (TotalLexicalDeclContexts)
6659 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6660 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6661 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6662 * 100));
6663 if (TotalVisibleDeclContexts)
6664 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6665 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6666 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6667 * 100));
6668 if (TotalNumMethodPoolEntries) {
6669 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6670 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6671 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6672 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006674 if (NumMethodPoolLookups) {
6675 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6676 NumMethodPoolHits, NumMethodPoolLookups,
6677 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6678 }
6679 if (NumMethodPoolTableLookups) {
6680 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6681 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6682 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6683 * 100.0));
6684 }
6685
Douglas Gregor00a50f72013-01-25 00:38:33 +00006686 if (NumIdentifierLookupHits) {
6687 std::fprintf(stderr,
6688 " %u / %u identifier table lookups succeeded (%f%%)\n",
6689 NumIdentifierLookupHits, NumIdentifierLookups,
6690 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6691 }
6692
Douglas Gregore060e572013-01-25 01:03:03 +00006693 if (GlobalIndex) {
6694 std::fprintf(stderr, "\n");
6695 GlobalIndex->printStats();
6696 }
6697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 std::fprintf(stderr, "\n");
6699 dump();
6700 std::fprintf(stderr, "\n");
6701}
6702
6703template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6704static void
6705dumpModuleIDMap(StringRef Name,
6706 const ContinuousRangeMap<Key, ModuleFile *,
6707 InitialCapacity> &Map) {
6708 if (Map.begin() == Map.end())
6709 return;
6710
6711 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6712 llvm::errs() << Name << ":\n";
6713 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6714 I != IEnd; ++I) {
6715 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6716 << "\n";
6717 }
6718}
6719
6720void ASTReader::dump() {
6721 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6722 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6723 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6724 dumpModuleIDMap("Global type map", GlobalTypeMap);
6725 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6726 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6727 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6728 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6729 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6730 dumpModuleIDMap("Global preprocessed entity map",
6731 GlobalPreprocessedEntityMap);
6732
6733 llvm::errs() << "\n*** PCH/Modules Loaded:";
6734 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6735 MEnd = ModuleMgr.end();
6736 M != MEnd; ++M)
6737 (*M)->dump();
6738}
6739
6740/// Return the amount of memory used by memory buffers, breaking down
6741/// by heap-backed versus mmap'ed memory.
6742void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6743 for (ModuleConstIterator I = ModuleMgr.begin(),
6744 E = ModuleMgr.end(); I != E; ++I) {
6745 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6746 size_t bytes = buf->getBufferSize();
6747 switch (buf->getBufferKind()) {
6748 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6749 sizes.malloc_bytes += bytes;
6750 break;
6751 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6752 sizes.mmap_bytes += bytes;
6753 break;
6754 }
6755 }
6756 }
6757}
6758
6759void ASTReader::InitializeSema(Sema &S) {
6760 SemaObj = &S;
6761 S.addExternalSource(this);
6762
6763 // Makes sure any declarations that were deserialized "too early"
6764 // still get added to the identifier's declaration chains.
6765 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006766 pushExternalDeclIntoScope(PreloadedDecls[I],
6767 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 }
6769 PreloadedDecls.clear();
6770
Richard Smith3d8e97e2013-10-18 06:54:39 +00006771 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006772 if (!FPPragmaOptions.empty()) {
6773 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6774 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6775 }
6776
Richard Smith3d8e97e2013-10-18 06:54:39 +00006777 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 if (!OpenCLExtensions.empty()) {
6779 unsigned I = 0;
6780#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6781#include "clang/Basic/OpenCLExtensions.def"
6782
6783 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6784 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006785
6786 UpdateSema();
6787}
6788
6789void ASTReader::UpdateSema() {
6790 assert(SemaObj && "no Sema to update");
6791
6792 // Load the offsets of the declarations that Sema references.
6793 // They will be lazily deserialized when needed.
6794 if (!SemaDeclRefs.empty()) {
6795 assert(SemaDeclRefs.size() % 2 == 0);
6796 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6797 if (!SemaObj->StdNamespace)
6798 SemaObj->StdNamespace = SemaDeclRefs[I];
6799 if (!SemaObj->StdBadAlloc)
6800 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6801 }
6802 SemaDeclRefs.clear();
6803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006804}
6805
6806IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6807 // Note that we are loading an identifier.
6808 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006809 StringRef Name(NameStart, NameEnd - NameStart);
6810
6811 // If there is a global index, look there first to determine which modules
6812 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006813 GlobalModuleIndex::HitSet Hits;
6814 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006815 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006816 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6817 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006818 }
6819 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006820 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006821 NumIdentifierLookups,
6822 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006823 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 IdentifierInfo *II = Visitor.getIdentifierInfo();
6825 markIdentifierUpToDate(II);
6826 return II;
6827}
6828
6829namespace clang {
6830 /// \brief An identifier-lookup iterator that enumerates all of the
6831 /// identifiers stored within a set of AST files.
6832 class ASTIdentifierIterator : public IdentifierIterator {
6833 /// \brief The AST reader whose identifiers are being enumerated.
6834 const ASTReader &Reader;
6835
6836 /// \brief The current index into the chain of AST files stored in
6837 /// the AST reader.
6838 unsigned Index;
6839
6840 /// \brief The current position within the identifier lookup table
6841 /// of the current AST file.
6842 ASTIdentifierLookupTable::key_iterator Current;
6843
6844 /// \brief The end position within the identifier lookup table of
6845 /// the current AST file.
6846 ASTIdentifierLookupTable::key_iterator End;
6847
6848 public:
6849 explicit ASTIdentifierIterator(const ASTReader &Reader);
6850
Craig Topper3e89dfe2014-03-13 02:13:41 +00006851 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 };
6853}
6854
6855ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6856 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6857 ASTIdentifierLookupTable *IdTable
6858 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6859 Current = IdTable->key_begin();
6860 End = IdTable->key_end();
6861}
6862
6863StringRef ASTIdentifierIterator::Next() {
6864 while (Current == End) {
6865 // If we have exhausted all of our AST files, we're done.
6866 if (Index == 0)
6867 return StringRef();
6868
6869 --Index;
6870 ASTIdentifierLookupTable *IdTable
6871 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6872 IdentifierLookupTable;
6873 Current = IdTable->key_begin();
6874 End = IdTable->key_end();
6875 }
6876
6877 // We have any identifiers remaining in the current AST file; return
6878 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006879 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006881 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006882}
6883
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006884IdentifierIterator *ASTReader::getIdentifiers() {
6885 if (!loadGlobalIndex())
6886 return GlobalIndex->createIdentifierIterator();
6887
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 return new ASTIdentifierIterator(*this);
6889}
6890
6891namespace clang { namespace serialization {
6892 class ReadMethodPoolVisitor {
6893 ASTReader &Reader;
6894 Selector Sel;
6895 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006896 unsigned InstanceBits;
6897 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006898 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6899 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006900
6901 public:
6902 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6903 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006904 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6905 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006906
6907 static bool visit(ModuleFile &M, void *UserData) {
6908 ReadMethodPoolVisitor *This
6909 = static_cast<ReadMethodPoolVisitor *>(UserData);
6910
6911 if (!M.SelectorLookupTable)
6912 return false;
6913
6914 // If we've already searched this module file, skip it now.
6915 if (M.Generation <= This->PriorGeneration)
6916 return true;
6917
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006918 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 ASTSelectorLookupTable *PoolTable
6920 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6921 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6922 if (Pos == PoolTable->end())
6923 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006924
6925 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 ++This->Reader.NumSelectorsRead;
6927 // FIXME: Not quite happy with the statistics here. We probably should
6928 // disable this tracking when called via LoadSelector.
6929 // Also, should entries without methods count as misses?
6930 ++This->Reader.NumMethodPoolEntriesRead;
6931 ASTSelectorLookupTrait::data_type Data = *Pos;
6932 if (This->Reader.DeserializationListener)
6933 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6934 This->Sel);
6935
6936 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6937 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006938 This->InstanceBits = Data.InstanceBits;
6939 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 return true;
6941 }
6942
6943 /// \brief Retrieve the instance methods found by this visitor.
6944 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6945 return InstanceMethods;
6946 }
6947
6948 /// \brief Retrieve the instance methods found by this visitor.
6949 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6950 return FactoryMethods;
6951 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006952
6953 unsigned getInstanceBits() const { return InstanceBits; }
6954 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 };
6956} } // end namespace clang::serialization
6957
6958/// \brief Add the given set of methods to the method list.
6959static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6960 ObjCMethodList &List) {
6961 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6962 S.addMethodToGlobalList(&List, Methods[I]);
6963 }
6964}
6965
6966void ASTReader::ReadMethodPool(Selector Sel) {
6967 // Get the selector generation and update it to the current generation.
6968 unsigned &Generation = SelectorGeneration[Sel];
6969 unsigned PriorGeneration = Generation;
6970 Generation = CurrentGeneration;
6971
6972 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006973 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6975 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6976
6977 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006978 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006979 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006980
6981 ++NumMethodPoolHits;
6982
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 if (!getSema())
6984 return;
6985
6986 Sema &S = *getSema();
6987 Sema::GlobalMethodPool::iterator Pos
6988 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6989
6990 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6991 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006992 Pos->second.first.setBits(Visitor.getInstanceBits());
6993 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006994}
6995
6996void ASTReader::ReadKnownNamespaces(
6997 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6998 Namespaces.clear();
6999
7000 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7001 if (NamespaceDecl *Namespace
7002 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7003 Namespaces.push_back(Namespace);
7004 }
7005}
7006
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007007void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007008 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007009 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7010 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007011 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007012 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007013 Undefined.insert(std::make_pair(D, Loc));
7014 }
7015}
Nick Lewycky8334af82013-01-26 00:35:08 +00007016
Guy Benyei11169dd2012-12-18 14:30:41 +00007017void ASTReader::ReadTentativeDefinitions(
7018 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7019 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7020 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7021 if (Var)
7022 TentativeDefs.push_back(Var);
7023 }
7024 TentativeDefinitions.clear();
7025}
7026
7027void ASTReader::ReadUnusedFileScopedDecls(
7028 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7029 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7030 DeclaratorDecl *D
7031 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7032 if (D)
7033 Decls.push_back(D);
7034 }
7035 UnusedFileScopedDecls.clear();
7036}
7037
7038void ASTReader::ReadDelegatingConstructors(
7039 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7040 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7041 CXXConstructorDecl *D
7042 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7043 if (D)
7044 Decls.push_back(D);
7045 }
7046 DelegatingCtorDecls.clear();
7047}
7048
7049void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7050 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7051 TypedefNameDecl *D
7052 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7053 if (D)
7054 Decls.push_back(D);
7055 }
7056 ExtVectorDecls.clear();
7057}
7058
7059void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7060 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7061 CXXRecordDecl *D
7062 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7063 if (D)
7064 Decls.push_back(D);
7065 }
7066 DynamicClasses.clear();
7067}
7068
7069void
Richard Smith78165b52013-01-10 23:43:47 +00007070ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7071 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7072 NamedDecl *D
7073 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007074 if (D)
7075 Decls.push_back(D);
7076 }
Richard Smith78165b52013-01-10 23:43:47 +00007077 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007078}
7079
7080void ASTReader::ReadReferencedSelectors(
7081 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7082 if (ReferencedSelectorsData.empty())
7083 return;
7084
7085 // If there are @selector references added them to its pool. This is for
7086 // implementation of -Wselector.
7087 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7088 unsigned I = 0;
7089 while (I < DataSize) {
7090 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7091 SourceLocation SelLoc
7092 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7093 Sels.push_back(std::make_pair(Sel, SelLoc));
7094 }
7095 ReferencedSelectorsData.clear();
7096}
7097
7098void ASTReader::ReadWeakUndeclaredIdentifiers(
7099 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7100 if (WeakUndeclaredIdentifiers.empty())
7101 return;
7102
7103 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7104 IdentifierInfo *WeakId
7105 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7106 IdentifierInfo *AliasId
7107 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7108 SourceLocation Loc
7109 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7110 bool Used = WeakUndeclaredIdentifiers[I++];
7111 WeakInfo WI(AliasId, Loc);
7112 WI.setUsed(Used);
7113 WeakIDs.push_back(std::make_pair(WeakId, WI));
7114 }
7115 WeakUndeclaredIdentifiers.clear();
7116}
7117
7118void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7119 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7120 ExternalVTableUse VT;
7121 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7122 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7123 VT.DefinitionRequired = VTableUses[Idx++];
7124 VTables.push_back(VT);
7125 }
7126
7127 VTableUses.clear();
7128}
7129
7130void ASTReader::ReadPendingInstantiations(
7131 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7132 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7133 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7134 SourceLocation Loc
7135 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7136
7137 Pending.push_back(std::make_pair(D, Loc));
7138 }
7139 PendingInstantiations.clear();
7140}
7141
Richard Smithe40f2ba2013-08-07 21:41:30 +00007142void ASTReader::ReadLateParsedTemplates(
7143 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7144 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7145 /* In loop */) {
7146 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7147
7148 LateParsedTemplate *LT = new LateParsedTemplate;
7149 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7150
7151 ModuleFile *F = getOwningModuleFile(LT->D);
7152 assert(F && "No module");
7153
7154 unsigned TokN = LateParsedTemplates[Idx++];
7155 LT->Toks.reserve(TokN);
7156 for (unsigned T = 0; T < TokN; ++T)
7157 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7158
7159 LPTMap[FD] = LT;
7160 }
7161
7162 LateParsedTemplates.clear();
7163}
7164
Guy Benyei11169dd2012-12-18 14:30:41 +00007165void ASTReader::LoadSelector(Selector Sel) {
7166 // It would be complicated to avoid reading the methods anyway. So don't.
7167 ReadMethodPool(Sel);
7168}
7169
7170void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7171 assert(ID && "Non-zero identifier ID required");
7172 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7173 IdentifiersLoaded[ID - 1] = II;
7174 if (DeserializationListener)
7175 DeserializationListener->IdentifierRead(ID, II);
7176}
7177
7178/// \brief Set the globally-visible declarations associated with the given
7179/// identifier.
7180///
7181/// If the AST reader is currently in a state where the given declaration IDs
7182/// cannot safely be resolved, they are queued until it is safe to resolve
7183/// them.
7184///
7185/// \param II an IdentifierInfo that refers to one or more globally-visible
7186/// declarations.
7187///
7188/// \param DeclIDs the set of declaration IDs with the name @p II that are
7189/// visible at global scope.
7190///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007191/// \param Decls if non-null, this vector will be populated with the set of
7192/// deserialized declarations. These declarations will not be pushed into
7193/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007194void
7195ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7196 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007197 SmallVectorImpl<Decl *> *Decls) {
7198 if (NumCurrentElementsDeserializing && !Decls) {
7199 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 return;
7201 }
7202
7203 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7204 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7205 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007206 // If we're simply supposed to record the declarations, do so now.
7207 if (Decls) {
7208 Decls->push_back(D);
7209 continue;
7210 }
7211
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 // Introduce this declaration into the translation-unit scope
7213 // and add it to the declaration chain for this identifier, so
7214 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007215 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 } else {
7217 // Queue this declaration so that it will be added to the
7218 // translation unit scope and identifier's declaration chain
7219 // once a Sema object is known.
7220 PreloadedDecls.push_back(D);
7221 }
7222 }
7223}
7224
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007225IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 if (ID == 0)
7227 return 0;
7228
7229 if (IdentifiersLoaded.empty()) {
7230 Error("no identifier table in AST file");
7231 return 0;
7232 }
7233
7234 ID -= 1;
7235 if (!IdentifiersLoaded[ID]) {
7236 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7237 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7238 ModuleFile *M = I->second;
7239 unsigned Index = ID - M->BaseIdentifierID;
7240 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7241
7242 // All of the strings in the AST file are preceded by a 16-bit length.
7243 // Extract that 16-bit length to avoid having to execute strlen().
7244 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7245 // unsigned integers. This is important to avoid integer overflow when
7246 // we cast them to 'unsigned'.
7247 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7248 unsigned StrLen = (((unsigned) StrLenPtr[0])
7249 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007250 IdentifiersLoaded[ID]
7251 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 if (DeserializationListener)
7253 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7254 }
7255
7256 return IdentifiersLoaded[ID];
7257}
7258
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007259IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7260 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007261}
7262
7263IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7264 if (LocalID < NUM_PREDEF_IDENT_IDS)
7265 return LocalID;
7266
7267 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7268 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7269 assert(I != M.IdentifierRemap.end()
7270 && "Invalid index into identifier index remap");
7271
7272 return LocalID + I->second;
7273}
7274
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007275MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 if (ID == 0)
7277 return 0;
7278
7279 if (MacrosLoaded.empty()) {
7280 Error("no macro table in AST file");
7281 return 0;
7282 }
7283
7284 ID -= NUM_PREDEF_MACRO_IDS;
7285 if (!MacrosLoaded[ID]) {
7286 GlobalMacroMapType::iterator I
7287 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7288 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7289 ModuleFile *M = I->second;
7290 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007291 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7292
7293 if (DeserializationListener)
7294 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7295 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007296 }
7297
7298 return MacrosLoaded[ID];
7299}
7300
7301MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7302 if (LocalID < NUM_PREDEF_MACRO_IDS)
7303 return LocalID;
7304
7305 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7306 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7307 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7308
7309 return LocalID + I->second;
7310}
7311
7312serialization::SubmoduleID
7313ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7314 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7315 return LocalID;
7316
7317 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7318 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7319 assert(I != M.SubmoduleRemap.end()
7320 && "Invalid index into submodule index remap");
7321
7322 return LocalID + I->second;
7323}
7324
7325Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7326 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7327 assert(GlobalID == 0 && "Unhandled global submodule ID");
7328 return 0;
7329 }
7330
7331 if (GlobalID > SubmodulesLoaded.size()) {
7332 Error("submodule ID out of range in AST file");
7333 return 0;
7334 }
7335
7336 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7337}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007338
7339Module *ASTReader::getModule(unsigned ID) {
7340 return getSubmodule(ID);
7341}
7342
Guy Benyei11169dd2012-12-18 14:30:41 +00007343Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7344 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7345}
7346
7347Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7348 if (ID == 0)
7349 return Selector();
7350
7351 if (ID > SelectorsLoaded.size()) {
7352 Error("selector ID out of range in AST file");
7353 return Selector();
7354 }
7355
7356 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7357 // Load this selector from the selector table.
7358 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7359 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7360 ModuleFile &M = *I->second;
7361 ASTSelectorLookupTrait Trait(*this, M);
7362 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7363 SelectorsLoaded[ID - 1] =
7364 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7365 if (DeserializationListener)
7366 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7367 }
7368
7369 return SelectorsLoaded[ID - 1];
7370}
7371
7372Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7373 return DecodeSelector(ID);
7374}
7375
7376uint32_t ASTReader::GetNumExternalSelectors() {
7377 // ID 0 (the null selector) is considered an external selector.
7378 return getTotalNumSelectors() + 1;
7379}
7380
7381serialization::SelectorID
7382ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7383 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7384 return LocalID;
7385
7386 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7387 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7388 assert(I != M.SelectorRemap.end()
7389 && "Invalid index into selector index remap");
7390
7391 return LocalID + I->second;
7392}
7393
7394DeclarationName
7395ASTReader::ReadDeclarationName(ModuleFile &F,
7396 const RecordData &Record, unsigned &Idx) {
7397 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7398 switch (Kind) {
7399 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007400 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007401
7402 case DeclarationName::ObjCZeroArgSelector:
7403 case DeclarationName::ObjCOneArgSelector:
7404 case DeclarationName::ObjCMultiArgSelector:
7405 return DeclarationName(ReadSelector(F, Record, Idx));
7406
7407 case DeclarationName::CXXConstructorName:
7408 return Context.DeclarationNames.getCXXConstructorName(
7409 Context.getCanonicalType(readType(F, Record, Idx)));
7410
7411 case DeclarationName::CXXDestructorName:
7412 return Context.DeclarationNames.getCXXDestructorName(
7413 Context.getCanonicalType(readType(F, Record, Idx)));
7414
7415 case DeclarationName::CXXConversionFunctionName:
7416 return Context.DeclarationNames.getCXXConversionFunctionName(
7417 Context.getCanonicalType(readType(F, Record, Idx)));
7418
7419 case DeclarationName::CXXOperatorName:
7420 return Context.DeclarationNames.getCXXOperatorName(
7421 (OverloadedOperatorKind)Record[Idx++]);
7422
7423 case DeclarationName::CXXLiteralOperatorName:
7424 return Context.DeclarationNames.getCXXLiteralOperatorName(
7425 GetIdentifierInfo(F, Record, Idx));
7426
7427 case DeclarationName::CXXUsingDirective:
7428 return DeclarationName::getUsingDirectiveName();
7429 }
7430
7431 llvm_unreachable("Invalid NameKind!");
7432}
7433
7434void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7435 DeclarationNameLoc &DNLoc,
7436 DeclarationName Name,
7437 const RecordData &Record, unsigned &Idx) {
7438 switch (Name.getNameKind()) {
7439 case DeclarationName::CXXConstructorName:
7440 case DeclarationName::CXXDestructorName:
7441 case DeclarationName::CXXConversionFunctionName:
7442 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7443 break;
7444
7445 case DeclarationName::CXXOperatorName:
7446 DNLoc.CXXOperatorName.BeginOpNameLoc
7447 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7448 DNLoc.CXXOperatorName.EndOpNameLoc
7449 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7450 break;
7451
7452 case DeclarationName::CXXLiteralOperatorName:
7453 DNLoc.CXXLiteralOperatorName.OpNameLoc
7454 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7455 break;
7456
7457 case DeclarationName::Identifier:
7458 case DeclarationName::ObjCZeroArgSelector:
7459 case DeclarationName::ObjCOneArgSelector:
7460 case DeclarationName::ObjCMultiArgSelector:
7461 case DeclarationName::CXXUsingDirective:
7462 break;
7463 }
7464}
7465
7466void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7467 DeclarationNameInfo &NameInfo,
7468 const RecordData &Record, unsigned &Idx) {
7469 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7470 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7471 DeclarationNameLoc DNLoc;
7472 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7473 NameInfo.setInfo(DNLoc);
7474}
7475
7476void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7477 const RecordData &Record, unsigned &Idx) {
7478 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7479 unsigned NumTPLists = Record[Idx++];
7480 Info.NumTemplParamLists = NumTPLists;
7481 if (NumTPLists) {
7482 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7483 for (unsigned i=0; i != NumTPLists; ++i)
7484 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7485 }
7486}
7487
7488TemplateName
7489ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7490 unsigned &Idx) {
7491 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7492 switch (Kind) {
7493 case TemplateName::Template:
7494 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7495
7496 case TemplateName::OverloadedTemplate: {
7497 unsigned size = Record[Idx++];
7498 UnresolvedSet<8> Decls;
7499 while (size--)
7500 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7501
7502 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7503 }
7504
7505 case TemplateName::QualifiedTemplate: {
7506 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7507 bool hasTemplKeyword = Record[Idx++];
7508 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7509 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7510 }
7511
7512 case TemplateName::DependentTemplate: {
7513 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7514 if (Record[Idx++]) // isIdentifier
7515 return Context.getDependentTemplateName(NNS,
7516 GetIdentifierInfo(F, Record,
7517 Idx));
7518 return Context.getDependentTemplateName(NNS,
7519 (OverloadedOperatorKind)Record[Idx++]);
7520 }
7521
7522 case TemplateName::SubstTemplateTemplateParm: {
7523 TemplateTemplateParmDecl *param
7524 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7525 if (!param) return TemplateName();
7526 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7527 return Context.getSubstTemplateTemplateParm(param, replacement);
7528 }
7529
7530 case TemplateName::SubstTemplateTemplateParmPack: {
7531 TemplateTemplateParmDecl *Param
7532 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7533 if (!Param)
7534 return TemplateName();
7535
7536 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7537 if (ArgPack.getKind() != TemplateArgument::Pack)
7538 return TemplateName();
7539
7540 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7541 }
7542 }
7543
7544 llvm_unreachable("Unhandled template name kind!");
7545}
7546
7547TemplateArgument
7548ASTReader::ReadTemplateArgument(ModuleFile &F,
7549 const RecordData &Record, unsigned &Idx) {
7550 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7551 switch (Kind) {
7552 case TemplateArgument::Null:
7553 return TemplateArgument();
7554 case TemplateArgument::Type:
7555 return TemplateArgument(readType(F, Record, Idx));
7556 case TemplateArgument::Declaration: {
7557 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7558 bool ForReferenceParam = Record[Idx++];
7559 return TemplateArgument(D, ForReferenceParam);
7560 }
7561 case TemplateArgument::NullPtr:
7562 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7563 case TemplateArgument::Integral: {
7564 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7565 QualType T = readType(F, Record, Idx);
7566 return TemplateArgument(Context, Value, T);
7567 }
7568 case TemplateArgument::Template:
7569 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7570 case TemplateArgument::TemplateExpansion: {
7571 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007572 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007573 if (unsigned NumExpansions = Record[Idx++])
7574 NumTemplateExpansions = NumExpansions - 1;
7575 return TemplateArgument(Name, NumTemplateExpansions);
7576 }
7577 case TemplateArgument::Expression:
7578 return TemplateArgument(ReadExpr(F));
7579 case TemplateArgument::Pack: {
7580 unsigned NumArgs = Record[Idx++];
7581 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7582 for (unsigned I = 0; I != NumArgs; ++I)
7583 Args[I] = ReadTemplateArgument(F, Record, Idx);
7584 return TemplateArgument(Args, NumArgs);
7585 }
7586 }
7587
7588 llvm_unreachable("Unhandled template argument kind!");
7589}
7590
7591TemplateParameterList *
7592ASTReader::ReadTemplateParameterList(ModuleFile &F,
7593 const RecordData &Record, unsigned &Idx) {
7594 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7595 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7596 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7597
7598 unsigned NumParams = Record[Idx++];
7599 SmallVector<NamedDecl *, 16> Params;
7600 Params.reserve(NumParams);
7601 while (NumParams--)
7602 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7603
7604 TemplateParameterList* TemplateParams =
7605 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7606 Params.data(), Params.size(), RAngleLoc);
7607 return TemplateParams;
7608}
7609
7610void
7611ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007612ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 ModuleFile &F, const RecordData &Record,
7614 unsigned &Idx) {
7615 unsigned NumTemplateArgs = Record[Idx++];
7616 TemplArgs.reserve(NumTemplateArgs);
7617 while (NumTemplateArgs--)
7618 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7619}
7620
7621/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007622void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 const RecordData &Record, unsigned &Idx) {
7624 unsigned NumDecls = Record[Idx++];
7625 Set.reserve(Context, NumDecls);
7626 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007627 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007628 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007629 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 }
7631}
7632
7633CXXBaseSpecifier
7634ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7635 const RecordData &Record, unsigned &Idx) {
7636 bool isVirtual = static_cast<bool>(Record[Idx++]);
7637 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7638 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7639 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7640 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7641 SourceRange Range = ReadSourceRange(F, Record, Idx);
7642 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7643 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7644 EllipsisLoc);
7645 Result.setInheritConstructors(inheritConstructors);
7646 return Result;
7647}
7648
7649std::pair<CXXCtorInitializer **, unsigned>
7650ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7651 unsigned &Idx) {
7652 CXXCtorInitializer **CtorInitializers = 0;
7653 unsigned NumInitializers = Record[Idx++];
7654 if (NumInitializers) {
7655 CtorInitializers
7656 = new (Context) CXXCtorInitializer*[NumInitializers];
7657 for (unsigned i=0; i != NumInitializers; ++i) {
7658 TypeSourceInfo *TInfo = 0;
7659 bool IsBaseVirtual = false;
7660 FieldDecl *Member = 0;
7661 IndirectFieldDecl *IndirectMember = 0;
7662
7663 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7664 switch (Type) {
7665 case CTOR_INITIALIZER_BASE:
7666 TInfo = GetTypeSourceInfo(F, Record, Idx);
7667 IsBaseVirtual = Record[Idx++];
7668 break;
7669
7670 case CTOR_INITIALIZER_DELEGATING:
7671 TInfo = GetTypeSourceInfo(F, Record, Idx);
7672 break;
7673
7674 case CTOR_INITIALIZER_MEMBER:
7675 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7676 break;
7677
7678 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7679 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7680 break;
7681 }
7682
7683 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7684 Expr *Init = ReadExpr(F);
7685 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7686 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7687 bool IsWritten = Record[Idx++];
7688 unsigned SourceOrderOrNumArrayIndices;
7689 SmallVector<VarDecl *, 8> Indices;
7690 if (IsWritten) {
7691 SourceOrderOrNumArrayIndices = Record[Idx++];
7692 } else {
7693 SourceOrderOrNumArrayIndices = Record[Idx++];
7694 Indices.reserve(SourceOrderOrNumArrayIndices);
7695 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7696 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7697 }
7698
7699 CXXCtorInitializer *BOMInit;
7700 if (Type == CTOR_INITIALIZER_BASE) {
7701 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7702 LParenLoc, Init, RParenLoc,
7703 MemberOrEllipsisLoc);
7704 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7705 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7706 Init, RParenLoc);
7707 } else if (IsWritten) {
7708 if (Member)
7709 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7710 LParenLoc, Init, RParenLoc);
7711 else
7712 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7713 MemberOrEllipsisLoc, LParenLoc,
7714 Init, RParenLoc);
7715 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007716 if (IndirectMember) {
7717 assert(Indices.empty() && "Indirect field improperly initialized");
7718 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7719 MemberOrEllipsisLoc, LParenLoc,
7720 Init, RParenLoc);
7721 } else {
7722 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7723 LParenLoc, Init, RParenLoc,
7724 Indices.data(), Indices.size());
7725 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 }
7727
7728 if (IsWritten)
7729 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7730 CtorInitializers[i] = BOMInit;
7731 }
7732 }
7733
7734 return std::make_pair(CtorInitializers, NumInitializers);
7735}
7736
7737NestedNameSpecifier *
7738ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7739 const RecordData &Record, unsigned &Idx) {
7740 unsigned N = Record[Idx++];
7741 NestedNameSpecifier *NNS = 0, *Prev = 0;
7742 for (unsigned I = 0; I != N; ++I) {
7743 NestedNameSpecifier::SpecifierKind Kind
7744 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7745 switch (Kind) {
7746 case NestedNameSpecifier::Identifier: {
7747 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7748 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7749 break;
7750 }
7751
7752 case NestedNameSpecifier::Namespace: {
7753 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7754 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7755 break;
7756 }
7757
7758 case NestedNameSpecifier::NamespaceAlias: {
7759 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7760 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7761 break;
7762 }
7763
7764 case NestedNameSpecifier::TypeSpec:
7765 case NestedNameSpecifier::TypeSpecWithTemplate: {
7766 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7767 if (!T)
7768 return 0;
7769
7770 bool Template = Record[Idx++];
7771 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7772 break;
7773 }
7774
7775 case NestedNameSpecifier::Global: {
7776 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7777 // No associated value, and there can't be a prefix.
7778 break;
7779 }
7780 }
7781 Prev = NNS;
7782 }
7783 return NNS;
7784}
7785
7786NestedNameSpecifierLoc
7787ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7788 unsigned &Idx) {
7789 unsigned N = Record[Idx++];
7790 NestedNameSpecifierLocBuilder Builder;
7791 for (unsigned I = 0; I != N; ++I) {
7792 NestedNameSpecifier::SpecifierKind Kind
7793 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7794 switch (Kind) {
7795 case NestedNameSpecifier::Identifier: {
7796 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7797 SourceRange Range = ReadSourceRange(F, Record, Idx);
7798 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7799 break;
7800 }
7801
7802 case NestedNameSpecifier::Namespace: {
7803 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7804 SourceRange Range = ReadSourceRange(F, Record, Idx);
7805 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7806 break;
7807 }
7808
7809 case NestedNameSpecifier::NamespaceAlias: {
7810 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7811 SourceRange Range = ReadSourceRange(F, Record, Idx);
7812 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7813 break;
7814 }
7815
7816 case NestedNameSpecifier::TypeSpec:
7817 case NestedNameSpecifier::TypeSpecWithTemplate: {
7818 bool Template = Record[Idx++];
7819 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7820 if (!T)
7821 return NestedNameSpecifierLoc();
7822 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7823
7824 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7825 Builder.Extend(Context,
7826 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7827 T->getTypeLoc(), ColonColonLoc);
7828 break;
7829 }
7830
7831 case NestedNameSpecifier::Global: {
7832 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7833 Builder.MakeGlobal(Context, ColonColonLoc);
7834 break;
7835 }
7836 }
7837 }
7838
7839 return Builder.getWithLocInContext(Context);
7840}
7841
7842SourceRange
7843ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7844 unsigned &Idx) {
7845 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7846 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7847 return SourceRange(beg, end);
7848}
7849
7850/// \brief Read an integral value
7851llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7852 unsigned BitWidth = Record[Idx++];
7853 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7854 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7855 Idx += NumWords;
7856 return Result;
7857}
7858
7859/// \brief Read a signed integral value
7860llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7861 bool isUnsigned = Record[Idx++];
7862 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7863}
7864
7865/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007866llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7867 const llvm::fltSemantics &Sem,
7868 unsigned &Idx) {
7869 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007870}
7871
7872// \brief Read a string
7873std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7874 unsigned Len = Record[Idx++];
7875 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7876 Idx += Len;
7877 return Result;
7878}
7879
7880VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7881 unsigned &Idx) {
7882 unsigned Major = Record[Idx++];
7883 unsigned Minor = Record[Idx++];
7884 unsigned Subminor = Record[Idx++];
7885 if (Minor == 0)
7886 return VersionTuple(Major);
7887 if (Subminor == 0)
7888 return VersionTuple(Major, Minor - 1);
7889 return VersionTuple(Major, Minor - 1, Subminor - 1);
7890}
7891
7892CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7893 const RecordData &Record,
7894 unsigned &Idx) {
7895 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7896 return CXXTemporary::Create(Context, Decl);
7897}
7898
7899DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007900 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007901}
7902
7903DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7904 return Diags.Report(Loc, DiagID);
7905}
7906
7907/// \brief Retrieve the identifier table associated with the
7908/// preprocessor.
7909IdentifierTable &ASTReader::getIdentifierTable() {
7910 return PP.getIdentifierTable();
7911}
7912
7913/// \brief Record that the given ID maps to the given switch-case
7914/// statement.
7915void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7916 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7917 "Already have a SwitchCase with this ID");
7918 (*CurrSwitchCaseStmts)[ID] = SC;
7919}
7920
7921/// \brief Retrieve the switch-case statement with the given ID.
7922SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7923 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7924 return (*CurrSwitchCaseStmts)[ID];
7925}
7926
7927void ASTReader::ClearSwitchCaseIDs() {
7928 CurrSwitchCaseStmts->clear();
7929}
7930
7931void ASTReader::ReadComments() {
7932 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007933 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 serialization::ModuleFile *> >::iterator
7935 I = CommentsCursors.begin(),
7936 E = CommentsCursors.end();
7937 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007938 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007939 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 serialization::ModuleFile &F = *I->second;
7941 SavedStreamPosition SavedPosition(Cursor);
7942
7943 RecordData Record;
7944 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007945 llvm::BitstreamEntry Entry =
7946 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007947
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007948 switch (Entry.Kind) {
7949 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7950 case llvm::BitstreamEntry::Error:
7951 Error("malformed block record in AST file");
7952 return;
7953 case llvm::BitstreamEntry::EndBlock:
7954 goto NextCursor;
7955 case llvm::BitstreamEntry::Record:
7956 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007957 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 }
7959
7960 // Read a record.
7961 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007962 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 case COMMENTS_RAW_COMMENT: {
7964 unsigned Idx = 0;
7965 SourceRange SR = ReadSourceRange(F, Record, Idx);
7966 RawComment::CommentKind Kind =
7967 (RawComment::CommentKind) Record[Idx++];
7968 bool IsTrailingComment = Record[Idx++];
7969 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007970 Comments.push_back(new (Context) RawComment(
7971 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7972 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007973 break;
7974 }
7975 }
7976 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007977 NextCursor:
7978 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007980}
7981
Richard Smithcd45dbc2014-04-19 03:48:30 +00007982std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7983 // If we know the owning module, use it.
7984 if (Module *M = D->getOwningModule())
7985 return M->getFullModuleName();
7986
7987 // Otherwise, use the name of the top-level module the decl is within.
7988 if (ModuleFile *M = getOwningModuleFile(D))
7989 return M->ModuleName;
7990
7991 // Not from a module.
7992 return "";
7993}
7994
Guy Benyei11169dd2012-12-18 14:30:41 +00007995void ASTReader::finishPendingActions() {
7996 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007997 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7998 !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007999 // If any identifiers with corresponding top-level declarations have
8000 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008001 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8002 TopLevelDeclsMap;
8003 TopLevelDeclsMap TopLevelDecls;
8004
Guy Benyei11169dd2012-12-18 14:30:41 +00008005 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008006 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008007 SmallVector<uint32_t, 4> DeclIDs =
8008 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008009 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008010
8011 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008013
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 // Load pending declaration chains.
8015 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8016 loadPendingDeclChain(PendingDeclChains[I]);
8017 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8018 }
8019 PendingDeclChains.clear();
8020
Douglas Gregor6168bd22013-02-18 15:53:43 +00008021 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008022 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8023 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008024 IdentifierInfo *II = TLD->first;
8025 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008026 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008027 }
8028 }
8029
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 // Load any pending macro definitions.
8031 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008032 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8033 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8034 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8035 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008036 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008037 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008038 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8039 if (Info.M->Kind != MK_Module)
8040 resolvePendingMacro(II, Info);
8041 }
8042 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008043 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008044 ++IDIdx) {
8045 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8046 if (Info.M->Kind == MK_Module)
8047 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 }
8049 }
8050 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008051
8052 // Wire up the DeclContexts for Decls that we delayed setting until
8053 // recursive loading is completed.
8054 while (!PendingDeclContextInfos.empty()) {
8055 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8056 PendingDeclContextInfos.pop_front();
8057 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8058 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8059 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8060 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008061
Richard Smithcd45dbc2014-04-19 03:48:30 +00008062 // Trigger the import of the full definition of each class that had any
8063 // odr-merging problems, so we can produce better diagnostics for them.
8064 for (auto &Merge : PendingOdrMergeFailures) {
8065 Merge.first->buildLookup();
8066 Merge.first->decls_begin();
8067 Merge.first->bases_begin();
8068 Merge.first->vbases_begin();
8069 for (auto *RD : Merge.second) {
8070 RD->decls_begin();
8071 RD->bases_begin();
8072 RD->vbases_begin();
8073 }
8074 }
8075
Richard Smith2b9e3e32013-10-18 06:05:18 +00008076 // For each declaration from a merged context, check that the canonical
8077 // definition of that context also contains a declaration of the same
8078 // entity.
8079 while (!PendingOdrMergeChecks.empty()) {
8080 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8081
8082 // FIXME: Skip over implicit declarations for now. This matters for things
8083 // like implicitly-declared special member functions. This isn't entirely
8084 // correct; we can end up with multiple unmerged declarations of the same
8085 // implicit entity.
8086 if (D->isImplicit())
8087 continue;
8088
8089 DeclContext *CanonDef = D->getDeclContext();
8090 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8091
8092 bool Found = false;
8093 const Decl *DCanon = D->getCanonicalDecl();
8094
8095 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8096 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8097 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008098 for (auto RI : (*I)->redecls()) {
8099 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008100 // This declaration is present in the canonical definition. If it's
8101 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008102 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008103 Found = true;
8104 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008105 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008106 break;
8107 }
8108 }
8109 }
8110
8111 if (!Found) {
8112 D->setInvalidDecl();
8113
Richard Smithcd45dbc2014-04-19 03:48:30 +00008114 std::string CanonDefModule =
8115 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008116 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008117 << D << getOwningModuleNameForDiagnostic(D)
8118 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008119
8120 if (Candidates.empty())
8121 Diag(cast<Decl>(CanonDef)->getLocation(),
8122 diag::note_module_odr_violation_no_possible_decls) << D;
8123 else {
8124 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8125 Diag(Candidates[I]->getLocation(),
8126 diag::note_module_odr_violation_possible_decl)
8127 << Candidates[I];
8128 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008129
8130 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008131 }
8132 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 }
8134
8135 // If we deserialized any C++ or Objective-C class definitions, any
8136 // Objective-C protocol definitions, or any redeclarable templates, make sure
8137 // that all redeclarations point to the definitions. Note that this can only
8138 // happen now, after the redeclaration chains have been fully wired.
8139 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8140 DEnd = PendingDefinitions.end();
8141 D != DEnd; ++D) {
8142 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008143 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 // Make sure that the TagType points at the definition.
8145 const_cast<TagType*>(TagT)->decl = TD;
8146 }
8147
Aaron Ballman86c93902014-03-06 23:45:36 +00008148 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8149 for (auto R : RD->redecls())
8150 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008151
8152 }
8153
8154 continue;
8155 }
8156
Aaron Ballman86c93902014-03-06 23:45:36 +00008157 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008158 // Make sure that the ObjCInterfaceType points at the definition.
8159 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8160 ->Decl = ID;
8161
Aaron Ballman86c93902014-03-06 23:45:36 +00008162 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 R->Data = ID->Data;
8164
8165 continue;
8166 }
8167
Aaron Ballman86c93902014-03-06 23:45:36 +00008168 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8169 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 R->Data = PD->Data;
8171
8172 continue;
8173 }
8174
Aaron Ballman86c93902014-03-06 23:45:36 +00008175 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8176 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 R->Common = RTD->Common;
8178 }
8179 PendingDefinitions.clear();
8180
8181 // Load the bodies of any functions or methods we've encountered. We do
8182 // this now (delayed) so that we can be sure that the declaration chains
8183 // have been fully wired up.
8184 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8185 PBEnd = PendingBodies.end();
8186 PB != PBEnd; ++PB) {
8187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8188 // FIXME: Check for =delete/=default?
8189 // FIXME: Complain about ODR violations here?
8190 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8191 FD->setLazyBody(PB->second);
8192 continue;
8193 }
8194
8195 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8196 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8197 MD->setLazyBody(PB->second);
8198 }
8199 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008200
8201 // Issue any pending ODR-failure diagnostics.
8202 for (auto &Merge : PendingOdrMergeFailures) {
8203 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8204 continue;
8205
8206 bool Diagnosed = false;
8207 for (auto *RD : Merge.second) {
8208 // Multiple different declarations got merged together; tell the user
8209 // where they came from.
8210 if (Merge.first != RD) {
8211 // FIXME: Walk the definition, figure out what's different,
8212 // and diagnose that.
8213 if (!Diagnosed) {
8214 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8215 Diag(Merge.first->getLocation(),
8216 diag::err_module_odr_violation_different_definitions)
8217 << Merge.first << Module.empty() << Module;
8218 Diagnosed = true;
8219 }
8220
8221 Diag(RD->getLocation(),
8222 diag::note_module_odr_violation_different_definitions)
8223 << getOwningModuleNameForDiagnostic(RD);
8224 }
8225 }
8226
8227 if (!Diagnosed) {
8228 // All definitions are updates to the same declaration. This happens if a
8229 // module instantiates the declaration of a class template specialization
8230 // and two or more other modules instantiate its definition.
8231 //
8232 // FIXME: Indicate which modules had instantiations of this definition.
8233 // FIXME: How can this even happen?
8234 Diag(Merge.first->getLocation(),
8235 diag::err_module_odr_violation_different_instantiations)
8236 << Merge.first;
8237 }
8238 }
8239 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008240}
8241
8242void ASTReader::FinishedDeserializing() {
8243 assert(NumCurrentElementsDeserializing &&
8244 "FinishedDeserializing not paired with StartedDeserializing");
8245 if (NumCurrentElementsDeserializing == 1) {
8246 // We decrease NumCurrentElementsDeserializing only after pending actions
8247 // are finished, to avoid recursively re-calling finishPendingActions().
8248 finishPendingActions();
8249 }
8250 --NumCurrentElementsDeserializing;
8251
Richard Smith04d05b52014-03-23 00:27:18 +00008252 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8253 // We are not in recursive loading, so it's safe to pass the "interesting"
8254 // decls to the consumer.
8255 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 }
8257}
8258
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008259void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008260 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008261
8262 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8263 SemaObj->TUScope->AddDecl(D);
8264 } else if (SemaObj->TUScope) {
8265 // Adding the decl to IdResolver may have failed because it was already in
8266 // (even though it was not added in scope). If it is already in, make sure
8267 // it gets in the scope as well.
8268 if (std::find(SemaObj->IdResolver.begin(Name),
8269 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8270 SemaObj->TUScope->AddDecl(D);
8271 }
8272}
8273
Guy Benyei11169dd2012-12-18 14:30:41 +00008274ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8275 StringRef isysroot, bool DisableValidation,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008276 bool AllowASTWithCompilerErrors,
8277 bool AllowConfigurationMismatch,
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008278 bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008279 bool UseGlobalIndex)
Guy Benyei11169dd2012-12-18 14:30:41 +00008280 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8281 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
8282 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
8283 Consumer(0), ModuleMgr(PP.getFileManager()),
8284 isysroot(isysroot), DisableValidation(DisableValidation),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008285 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008286 AllowConfigurationMismatch(AllowConfigurationMismatch),
Ben Langmuir3d4417c2014-02-07 17:31:11 +00008287 ValidateSystemInputs(ValidateSystemInputs),
Douglas Gregorc1bbec82013-01-25 00:45:27 +00008288 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8290 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor00a50f72013-01-25 00:38:33 +00008291 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
8292 TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
8293 NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008294 NumMethodPoolLookups(0), NumMethodPoolHits(0),
8295 NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
8296 TotalNumMethodPoolEntries(0),
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8298 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8299 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8300 PassingDeclsToConsumer(false),
Richard Smith629ff362013-07-31 00:26:46 +00008301 NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
Guy Benyei11169dd2012-12-18 14:30:41 +00008302{
8303 SourceMgr.setExternalSLocEntrySource(this);
8304}
8305
8306ASTReader::~ASTReader() {
8307 for (DeclContextVisibleUpdatesPending::iterator
8308 I = PendingVisibleUpdates.begin(),
8309 E = PendingVisibleUpdates.end();
8310 I != E; ++I) {
8311 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8312 F = I->second.end();
8313 J != F; ++J)
8314 delete J->first;
8315 }
8316}