blob: eb151ef16f69eb62a613f998fdef051ca750b36d [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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "llvm/Support/system_error.h"
56#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
59
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Ben Langmuircb69b572014-03-07 06:40:32 +000083bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
84 bool Complain) {
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
87}
88bool
89ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
90 bool Complain) {
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
93}
94bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000096 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
98}
99bool
100ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
101 bool Complain) {
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
104}
105
106bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
110}
111bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
117}
118void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
119 unsigned Value) {
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
122}
123bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
126}
127bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
130}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000131void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
134}
Ben Langmuircb69b572014-03-07 06:40:32 +0000135bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000136 bool isSystem,
137 bool isOverridden) {
138 return First->visitInputFile(Filename, isSystem, isOverridden) ||
139 Second->visitInputFile(Filename, isSystem, isOverridden);
Ben Langmuircb69b572014-03-07 06:40:32 +0000140}
141
Guy Benyei11169dd2012-12-18 14:30:41 +0000142//===----------------------------------------------------------------------===//
143// PCH validator implementation
144//===----------------------------------------------------------------------===//
145
146ASTReaderListener::~ASTReaderListener() {}
147
148/// \brief Compare the given set of language options against an existing set of
149/// language options.
150///
151/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
152///
153/// \returns true if the languagae options mis-match, false otherwise.
154static bool checkLanguageOptions(const LangOptions &LangOpts,
155 const LangOptions &ExistingLangOpts,
156 DiagnosticsEngine *Diags) {
157#define LANGOPT(Name, Bits, Default, Description) \
158 if (ExistingLangOpts.Name != LangOpts.Name) { \
159 if (Diags) \
160 Diags->Report(diag::err_pch_langopt_mismatch) \
161 << Description << LangOpts.Name << ExistingLangOpts.Name; \
162 return true; \
163 }
164
165#define VALUE_LANGOPT(Name, Bits, Default, Description) \
166 if (ExistingLangOpts.Name != LangOpts.Name) { \
167 if (Diags) \
168 Diags->Report(diag::err_pch_langopt_value_mismatch) \
169 << Description; \
170 return true; \
171 }
172
173#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
174 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
175 if (Diags) \
176 Diags->Report(diag::err_pch_langopt_value_mismatch) \
177 << Description; \
178 return true; \
179 }
180
181#define BENIGN_LANGOPT(Name, Bits, Default, Description)
182#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
183#include "clang/Basic/LangOptions.def"
184
185 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
186 if (Diags)
187 Diags->Report(diag::err_pch_langopt_value_mismatch)
188 << "target Objective-C runtime";
189 return true;
190 }
191
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000192 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
193 LangOpts.CommentOpts.BlockCommandNames) {
194 if (Diags)
195 Diags->Report(diag::err_pch_langopt_value_mismatch)
196 << "block command names";
197 return true;
198 }
199
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 return false;
201}
202
203/// \brief Compare the given set of target options against an existing set of
204/// target options.
205///
206/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
207///
208/// \returns true if the target options mis-match, false otherwise.
209static bool checkTargetOptions(const TargetOptions &TargetOpts,
210 const TargetOptions &ExistingTargetOpts,
211 DiagnosticsEngine *Diags) {
212#define CHECK_TARGET_OPT(Field, Name) \
213 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
214 if (Diags) \
215 Diags->Report(diag::err_pch_targetopt_mismatch) \
216 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
217 return true; \
218 }
219
220 CHECK_TARGET_OPT(Triple, "target");
221 CHECK_TARGET_OPT(CPU, "target CPU");
222 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000223#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
Nico Weber824285e2014-05-08 04:26:47 +0000582void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
583 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000584 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000585 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586}
587
588
589
590unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
591 return serialization::ComputeHash(Sel);
592}
593
594
595std::pair<unsigned, unsigned>
596ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000597 using namespace llvm::support;
598 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
599 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000600 return std::make_pair(KeyLen, DataLen);
601}
602
603ASTSelectorLookupTrait::internal_key_type
604ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000605 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000607 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
608 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
609 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 if (N == 0)
611 return SelTable.getNullarySelector(FirstII);
612 else if (N == 1)
613 return SelTable.getUnarySelector(FirstII);
614
615 SmallVector<IdentifierInfo *, 16> Args;
616 Args.push_back(FirstII);
617 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000618 Args.push_back(Reader.getLocalIdentifier(
619 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000620
621 return SelTable.getSelector(N, Args.data());
622}
623
624ASTSelectorLookupTrait::data_type
625ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
626 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000627 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000628
629 data_type Result;
630
Justin Bogner57ba0b22014-03-28 22:03:24 +0000631 Result.ID = Reader.getGlobalSelectorID(
632 F, endian::readNext<uint32_t, little, unaligned>(d));
633 unsigned NumInstanceMethodsAndBits =
634 endian::readNext<uint16_t, little, unaligned>(d);
635 unsigned NumFactoryMethodsAndBits =
636 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000637 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
638 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
639 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
640 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000641
642 // Load instance methods
643 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000644 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
645 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 Result.Instance.push_back(Method);
647 }
648
649 // Load factory methods
650 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
652 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 Result.Factory.push_back(Method);
654 }
655
656 return Result;
657}
658
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000659unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
660 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661}
662
663std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000664ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
666 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
667 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000668 return std::make_pair(KeyLen, DataLen);
669}
670
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000671ASTIdentifierLookupTraitBase::internal_key_type
672ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000674 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000675}
676
Douglas Gregordcf25082013-02-11 18:16:18 +0000677/// \brief Whether the given identifier is "interesting".
678static bool isInterestingIdentifier(IdentifierInfo &II) {
679 return II.isPoisoned() ||
680 II.isExtensionToken() ||
681 II.getObjCOrBuiltinID() ||
682 II.hasRevertedTokenIDToIdentifier() ||
683 II.hadMacroDefinition() ||
684 II.getFETokenInfo<void>();
685}
686
Guy Benyei11169dd2012-12-18 14:30:41 +0000687IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
688 const unsigned char* d,
689 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000690 using namespace llvm::support;
691 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000692 bool IsInteresting = RawID & 0x01;
693
694 // Wipe out the "is interesting" bit.
695 RawID = RawID >> 1;
696
697 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
698 if (!IsInteresting) {
699 // For uninteresting identifiers, just build the IdentifierInfo
700 // and associate it with the persistent ID.
701 IdentifierInfo *II = KnownII;
702 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000703 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 KnownII = II;
705 }
706 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000707 if (!II->isFromAST()) {
708 bool WasInteresting = isInterestingIdentifier(*II);
709 II->setIsFromAST();
710 if (WasInteresting)
711 II->setChangedSinceDeserialization();
712 }
713 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714 return II;
715 }
716
Justin Bogner57ba0b22014-03-28 22:03:24 +0000717 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
718 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 bool CPlusPlusOperatorKeyword = Bits & 0x01;
720 Bits >>= 1;
721 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
722 Bits >>= 1;
723 bool Poisoned = Bits & 0x01;
724 Bits >>= 1;
725 bool ExtensionToken = Bits & 0x01;
726 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000727 bool hasSubmoduleMacros = Bits & 0x01;
728 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 bool hadMacroDefinition = Bits & 0x01;
730 Bits >>= 1;
731
732 assert(Bits == 0 && "Extra bits in the identifier?");
733 DataLen -= 8;
734
735 // Build the IdentifierInfo itself and link the identifier ID with
736 // the new IdentifierInfo.
737 IdentifierInfo *II = KnownII;
738 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000739 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000740 KnownII = II;
741 }
742 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 if (!II->isFromAST()) {
744 bool WasInteresting = isInterestingIdentifier(*II);
745 II->setIsFromAST();
746 if (WasInteresting)
747 II->setChangedSinceDeserialization();
748 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000749
750 // Set or check the various bits in the IdentifierInfo structure.
751 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000752 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000753 II->RevertTokenIDToIdentifier();
754 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
755 assert(II->isExtensionToken() == ExtensionToken &&
756 "Incorrect extension token flag");
757 (void)ExtensionToken;
758 if (Poisoned)
759 II->setIsPoisoned(true);
760 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
761 "Incorrect C++ operator keyword flag");
762 (void)CPlusPlusOperatorKeyword;
763
764 // If this identifier is a macro, deserialize the macro
765 // definition.
766 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 uint32_t MacroDirectivesOffset =
768 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000769 DataLen -= 4;
770 SmallVector<uint32_t, 8> LocalMacroIDs;
771 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000772 while (uint32_t LocalMacroID =
773 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000774 DataLen -= 4;
775 LocalMacroIDs.push_back(LocalMacroID);
776 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000777 DataLen -= 4;
778 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000779
780 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000781 // Macro definitions are stored from newest to oldest, so reverse them
782 // before registering them.
783 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000784 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000785 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
786 unsigned Size = 1;
787
788 static const uint32_t HasOverridesFlag = 0x80000000U;
789 if (I + 1 != E && (I[1] & HasOverridesFlag))
790 Size += 1 + (I[1] & ~HasOverridesFlag);
791
792 MacroSizes.push_back(Size);
793 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000794 }
Richard Smith49f906a2014-03-01 00:08:04 +0000795
796 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
797 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
798 SE = MacroSizes.rend();
799 SI != SE; ++SI) {
800 I -= *SI;
801
802 uint32_t LocalMacroID = *I;
803 llvm::ArrayRef<uint32_t> Overrides;
804 if (*SI != 1)
805 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
806 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
807 }
808 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000809 } else {
810 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
811 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 }
813
814 Reader.SetIdentifierInfo(ID, II);
815
816 // Read all of the declarations visible at global scope with this
817 // name.
818 if (DataLen > 0) {
819 SmallVector<uint32_t, 4> DeclIDs;
820 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 DeclIDs.push_back(Reader.getGlobalDeclID(
822 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 Reader.SetGloballyVisibleDecls(II, DeclIDs);
824 }
825
826 return II;
827}
828
829unsigned
830ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
831 llvm::FoldingSetNodeID ID;
832 ID.AddInteger(Key.Kind);
833
834 switch (Key.Kind) {
835 case DeclarationName::Identifier:
836 case DeclarationName::CXXLiteralOperatorName:
837 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
838 break;
839 case DeclarationName::ObjCZeroArgSelector:
840 case DeclarationName::ObjCOneArgSelector:
841 case DeclarationName::ObjCMultiArgSelector:
842 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
843 break;
844 case DeclarationName::CXXOperatorName:
845 ID.AddInteger((OverloadedOperatorKind)Key.Data);
846 break;
847 case DeclarationName::CXXConstructorName:
848 case DeclarationName::CXXDestructorName:
849 case DeclarationName::CXXConversionFunctionName:
850 case DeclarationName::CXXUsingDirective:
851 break;
852 }
853
854 return ID.ComputeHash();
855}
856
857ASTDeclContextNameLookupTrait::internal_key_type
858ASTDeclContextNameLookupTrait::GetInternalKey(
859 const external_key_type& Name) const {
860 DeclNameKey Key;
861 Key.Kind = Name.getNameKind();
862 switch (Name.getNameKind()) {
863 case DeclarationName::Identifier:
864 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
865 break;
866 case DeclarationName::ObjCZeroArgSelector:
867 case DeclarationName::ObjCOneArgSelector:
868 case DeclarationName::ObjCMultiArgSelector:
869 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
870 break;
871 case DeclarationName::CXXOperatorName:
872 Key.Data = Name.getCXXOverloadedOperator();
873 break;
874 case DeclarationName::CXXLiteralOperatorName:
875 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
876 break;
877 case DeclarationName::CXXConstructorName:
878 case DeclarationName::CXXDestructorName:
879 case DeclarationName::CXXConversionFunctionName:
880 case DeclarationName::CXXUsingDirective:
881 Key.Data = 0;
882 break;
883 }
884
885 return Key;
886}
887
888std::pair<unsigned, unsigned>
889ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000890 using namespace llvm::support;
891 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
892 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 return std::make_pair(KeyLen, DataLen);
894}
895
896ASTDeclContextNameLookupTrait::internal_key_type
897ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000898 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000899
900 DeclNameKey Key;
901 Key.Kind = (DeclarationName::NameKind)*d++;
902 switch (Key.Kind) {
903 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 Key.Data = (uint64_t)Reader.getLocalIdentifier(
905 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000906 break;
907 case DeclarationName::ObjCZeroArgSelector:
908 case DeclarationName::ObjCOneArgSelector:
909 case DeclarationName::ObjCMultiArgSelector:
910 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 (uint64_t)Reader.getLocalSelector(
912 F, endian::readNext<uint32_t, little, unaligned>(
913 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 break;
915 case DeclarationName::CXXOperatorName:
916 Key.Data = *d++; // OverloadedOperatorKind
917 break;
918 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000919 Key.Data = (uint64_t)Reader.getLocalIdentifier(
920 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000921 break;
922 case DeclarationName::CXXConstructorName:
923 case DeclarationName::CXXDestructorName:
924 case DeclarationName::CXXConversionFunctionName:
925 case DeclarationName::CXXUsingDirective:
926 Key.Data = 0;
927 break;
928 }
929
930 return Key;
931}
932
933ASTDeclContextNameLookupTrait::data_type
934ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
935 const unsigned char* d,
936 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 using namespace llvm::support;
938 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000939 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
940 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 return std::make_pair(Start, Start + NumDecls);
942}
943
944bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000945 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 const std::pair<uint64_t, uint64_t> &Offsets,
947 DeclContextInfo &Info) {
948 SavedStreamPosition SavedPosition(Cursor);
949 // First the lexical decls.
950 if (Offsets.first != 0) {
951 Cursor.JumpToBit(Offsets.first);
952
953 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000954 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000956 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 if (RecCode != DECL_CONTEXT_LEXICAL) {
958 Error("Expected lexical block");
959 return true;
960 }
961
Chris Lattner0e6c9402013-01-20 02:38:54 +0000962 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
963 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 }
965
966 // Now the lookup table.
967 if (Offsets.second != 0) {
968 Cursor.JumpToBit(Offsets.second);
969
970 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000971 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000973 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 if (RecCode != DECL_CONTEXT_VISIBLE) {
975 Error("Expected visible lookup table block");
976 return true;
977 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000978 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
979 (const unsigned char *)Blob.data() + Record[0],
980 (const unsigned char *)Blob.data() + sizeof(uint32_t),
981 (const unsigned char *)Blob.data(),
982 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 }
984
985 return false;
986}
987
988void ASTReader::Error(StringRef Msg) {
989 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000990 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
991 Diag(diag::note_module_cache_path)
992 << PP.getHeaderSearchInfo().getModuleCachePath();
993 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000994}
995
996void ASTReader::Error(unsigned DiagID,
997 StringRef Arg1, StringRef Arg2) {
998 if (Diags.isDiagnosticInFlight())
999 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1000 else
1001 Diag(DiagID) << Arg1 << Arg2;
1002}
1003
1004//===----------------------------------------------------------------------===//
1005// Source Manager Deserialization
1006//===----------------------------------------------------------------------===//
1007
1008/// \brief Read the line table in the source manager block.
1009/// \returns true if there was an error.
1010bool ASTReader::ParseLineTable(ModuleFile &F,
1011 SmallVectorImpl<uint64_t> &Record) {
1012 unsigned Idx = 0;
1013 LineTableInfo &LineTable = SourceMgr.getLineTable();
1014
1015 // Parse the file names
1016 std::map<int, int> FileIDs;
1017 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1018 // Extract the file name
1019 unsigned FilenameLen = Record[Idx++];
1020 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1021 Idx += FilenameLen;
1022 MaybeAddSystemRootToFilename(F, Filename);
1023 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1024 }
1025
1026 // Parse the line entries
1027 std::vector<LineEntry> Entries;
1028 while (Idx < Record.size()) {
1029 int FID = Record[Idx++];
1030 assert(FID >= 0 && "Serialized line entries for non-local file.");
1031 // Remap FileID from 1-based old view.
1032 FID += F.SLocEntryBaseID - 1;
1033
1034 // Extract the line entries
1035 unsigned NumEntries = Record[Idx++];
1036 assert(NumEntries && "Numentries is 00000");
1037 Entries.clear();
1038 Entries.reserve(NumEntries);
1039 for (unsigned I = 0; I != NumEntries; ++I) {
1040 unsigned FileOffset = Record[Idx++];
1041 unsigned LineNo = Record[Idx++];
1042 int FilenameID = FileIDs[Record[Idx++]];
1043 SrcMgr::CharacteristicKind FileKind
1044 = (SrcMgr::CharacteristicKind)Record[Idx++];
1045 unsigned IncludeOffset = Record[Idx++];
1046 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1047 FileKind, IncludeOffset));
1048 }
1049 LineTable.AddEntry(FileID::get(FID), Entries);
1050 }
1051
1052 return false;
1053}
1054
1055/// \brief Read a source manager block
1056bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1057 using namespace SrcMgr;
1058
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001059 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001060
1061 // Set the source-location entry cursor to the current position in
1062 // the stream. This cursor will be used to read the contents of the
1063 // source manager block initially, and then lazily read
1064 // source-location entries as needed.
1065 SLocEntryCursor = F.Stream;
1066
1067 // The stream itself is going to skip over the source manager block.
1068 if (F.Stream.SkipBlock()) {
1069 Error("malformed block record in AST file");
1070 return true;
1071 }
1072
1073 // Enter the source manager block.
1074 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1075 Error("malformed source manager block record in AST file");
1076 return true;
1077 }
1078
1079 RecordData Record;
1080 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001081 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1082
1083 switch (E.Kind) {
1084 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1085 case llvm::BitstreamEntry::Error:
1086 Error("malformed block record in AST file");
1087 return true;
1088 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001090 case llvm::BitstreamEntry::Record:
1091 // The interesting case.
1092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001094
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001097 StringRef Blob;
1098 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 default: // Default behavior: ignore.
1100 break;
1101
1102 case SM_SLOC_FILE_ENTRY:
1103 case SM_SLOC_BUFFER_ENTRY:
1104 case SM_SLOC_EXPANSION_ENTRY:
1105 // Once we hit one of the source location entries, we're done.
1106 return false;
1107 }
1108 }
1109}
1110
1111/// \brief If a header file is not found at the path that we expect it to be
1112/// and the PCH file was moved from its original location, try to resolve the
1113/// file by assuming that header+PCH were moved together and the header is in
1114/// the same place relative to the PCH.
1115static std::string
1116resolveFileRelativeToOriginalDir(const std::string &Filename,
1117 const std::string &OriginalDir,
1118 const std::string &CurrDir) {
1119 assert(OriginalDir != CurrDir &&
1120 "No point trying to resolve the file if the PCH dir didn't change");
1121 using namespace llvm::sys;
1122 SmallString<128> filePath(Filename);
1123 fs::make_absolute(filePath);
1124 assert(path::is_absolute(OriginalDir));
1125 SmallString<128> currPCHPath(CurrDir);
1126
1127 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1128 fileDirE = path::end(path::parent_path(filePath));
1129 path::const_iterator origDirI = path::begin(OriginalDir),
1130 origDirE = path::end(OriginalDir);
1131 // Skip the common path components from filePath and OriginalDir.
1132 while (fileDirI != fileDirE && origDirI != origDirE &&
1133 *fileDirI == *origDirI) {
1134 ++fileDirI;
1135 ++origDirI;
1136 }
1137 for (; origDirI != origDirE; ++origDirI)
1138 path::append(currPCHPath, "..");
1139 path::append(currPCHPath, fileDirI, fileDirE);
1140 path::append(currPCHPath, path::filename(Filename));
1141 return currPCHPath.str();
1142}
1143
1144bool ASTReader::ReadSLocEntry(int ID) {
1145 if (ID == 0)
1146 return false;
1147
1148 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1149 Error("source location entry ID out-of-range for AST file");
1150 return true;
1151 }
1152
1153 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1154 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001155 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001156 unsigned BaseOffset = F->SLocEntryBaseOffset;
1157
1158 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001159 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1160 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 Error("incorrectly-formatted source location entry in AST file");
1162 return true;
1163 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001164
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001166 StringRef Blob;
1167 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 default:
1169 Error("incorrectly-formatted source location entry in AST file");
1170 return true;
1171
1172 case SM_SLOC_FILE_ENTRY: {
1173 // We will detect whether a file changed and return 'Failure' for it, but
1174 // we will also try to fail gracefully by setting up the SLocEntry.
1175 unsigned InputID = Record[4];
1176 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001177 const FileEntry *File = IF.getFile();
1178 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001179
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001180 // Note that we only check if a File was returned. If it was out-of-date
1181 // we have complained but we will continue creating a FileID to recover
1182 // gracefully.
1183 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 return true;
1185
1186 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1187 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1188 // This is the module's main file.
1189 IncludeLoc = getImportLocation(F);
1190 }
1191 SrcMgr::CharacteristicKind
1192 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1193 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1194 ID, BaseOffset + Record[0]);
1195 SrcMgr::FileInfo &FileInfo =
1196 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1197 FileInfo.NumCreatedFIDs = Record[5];
1198 if (Record[3])
1199 FileInfo.setHasLineDirectives();
1200
1201 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1202 unsigned NumFileDecls = Record[7];
1203 if (NumFileDecls) {
1204 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1205 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1206 NumFileDecls));
1207 }
1208
1209 const SrcMgr::ContentCache *ContentCache
1210 = SourceMgr.getOrCreateContentCache(File,
1211 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1212 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1213 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1214 unsigned Code = SLocEntryCursor.ReadCode();
1215 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001216 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001217
1218 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1219 Error("AST record has invalid code");
1220 return true;
1221 }
1222
1223 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001224 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 SourceMgr.overrideFileContents(File, Buffer);
1226 }
1227
1228 break;
1229 }
1230
1231 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001232 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 unsigned Offset = Record[0];
1234 SrcMgr::CharacteristicKind
1235 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1236 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1237 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1238 IncludeLoc = getImportLocation(F);
1239 }
1240 unsigned Code = SLocEntryCursor.ReadCode();
1241 Record.clear();
1242 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001243 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001244
1245 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1246 Error("AST record has invalid code");
1247 return true;
1248 }
1249
1250 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001251 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001252 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1253 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 break;
1255 }
1256
1257 case SM_SLOC_EXPANSION_ENTRY: {
1258 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1259 SourceMgr.createExpansionLoc(SpellingLoc,
1260 ReadSourceLocation(*F, Record[2]),
1261 ReadSourceLocation(*F, Record[3]),
1262 Record[4],
1263 ID,
1264 BaseOffset + Record[0]);
1265 break;
1266 }
1267 }
1268
1269 return false;
1270}
1271
1272std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1273 if (ID == 0)
1274 return std::make_pair(SourceLocation(), "");
1275
1276 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1277 Error("source location entry ID out-of-range for AST file");
1278 return std::make_pair(SourceLocation(), "");
1279 }
1280
1281 // Find which module file this entry lands in.
1282 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1283 if (M->Kind != MK_Module)
1284 return std::make_pair(SourceLocation(), "");
1285
1286 // FIXME: Can we map this down to a particular submodule? That would be
1287 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001288 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001289}
1290
1291/// \brief Find the location where the module F is imported.
1292SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1293 if (F->ImportLoc.isValid())
1294 return F->ImportLoc;
1295
1296 // Otherwise we have a PCH. It's considered to be "imported" at the first
1297 // location of its includer.
1298 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001299 // Main file is the importer.
1300 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1301 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 return F->ImportedBy[0]->FirstLoc;
1304}
1305
1306/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1307/// specified cursor. Read the abbreviations that are at the top of the block
1308/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001309bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 if (Cursor.EnterSubBlock(BlockID)) {
1311 Error("malformed block record in AST file");
1312 return Failure;
1313 }
1314
1315 while (true) {
1316 uint64_t Offset = Cursor.GetCurrentBitNo();
1317 unsigned Code = Cursor.ReadCode();
1318
1319 // We expect all abbrevs to be at the start of the block.
1320 if (Code != llvm::bitc::DEFINE_ABBREV) {
1321 Cursor.JumpToBit(Offset);
1322 return false;
1323 }
1324 Cursor.ReadAbbrevRecord();
1325 }
1326}
1327
Richard Smithe40f2ba2013-08-07 21:41:30 +00001328Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001329 unsigned &Idx) {
1330 Token Tok;
1331 Tok.startToken();
1332 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1333 Tok.setLength(Record[Idx++]);
1334 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1335 Tok.setIdentifierInfo(II);
1336 Tok.setKind((tok::TokenKind)Record[Idx++]);
1337 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1338 return Tok;
1339}
1340
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001341MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001342 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001343
1344 // Keep track of where we are in the stream, then jump back there
1345 // after reading this macro.
1346 SavedStreamPosition SavedPosition(Stream);
1347
1348 Stream.JumpToBit(Offset);
1349 RecordData Record;
1350 SmallVector<IdentifierInfo*, 16> MacroArgs;
1351 MacroInfo *Macro = 0;
1352
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001354 // Advance to the next record, but if we get to the end of the block, don't
1355 // pop it (removing all the abbreviations from the cursor) since we want to
1356 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001357 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001358 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1359
1360 switch (Entry.Kind) {
1361 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1362 case llvm::BitstreamEntry::Error:
1363 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001364 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001365 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001366 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 case llvm::BitstreamEntry::Record:
1368 // The interesting case.
1369 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 }
1371
1372 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 Record.clear();
1374 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001375 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001377 case PP_MACRO_DIRECTIVE_HISTORY:
1378 return Macro;
1379
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 case PP_MACRO_OBJECT_LIKE:
1381 case PP_MACRO_FUNCTION_LIKE: {
1382 // If we already have a macro, that means that we've hit the end
1383 // of the definition of the macro we were looking for. We're
1384 // done.
1385 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001386 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001387
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001388 unsigned NextIndex = 1; // Skip identifier ID.
1389 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001391 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001392 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001394 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1397 // Decode function-like macro info.
1398 bool isC99VarArgs = Record[NextIndex++];
1399 bool isGNUVarArgs = Record[NextIndex++];
1400 bool hasCommaPasting = Record[NextIndex++];
1401 MacroArgs.clear();
1402 unsigned NumArgs = Record[NextIndex++];
1403 for (unsigned i = 0; i != NumArgs; ++i)
1404 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1405
1406 // Install function-like macro info.
1407 MI->setIsFunctionLike();
1408 if (isC99VarArgs) MI->setIsC99Varargs();
1409 if (isGNUVarArgs) MI->setIsGNUVarargs();
1410 if (hasCommaPasting) MI->setHasCommaPasting();
1411 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1412 PP.getPreprocessorAllocator());
1413 }
1414
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 // Remember that we saw this macro last so that we add the tokens that
1416 // form its body to it.
1417 Macro = MI;
1418
1419 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1420 Record[NextIndex]) {
1421 // We have a macro definition. Register the association
1422 PreprocessedEntityID
1423 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1424 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001425 PreprocessingRecord::PPEntityID
1426 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1427 MacroDefinition *PPDef =
1428 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1429 if (PPDef)
1430 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 }
1432
1433 ++NumMacrosRead;
1434 break;
1435 }
1436
1437 case PP_TOKEN: {
1438 // If we see a TOKEN before a PP_MACRO_*, then the file is
1439 // erroneous, just pretend we didn't see this.
1440 if (Macro == 0) break;
1441
John McCallf413f5e2013-05-03 00:10:13 +00001442 unsigned Idx = 0;
1443 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001444 Macro->AddTokenToBody(Tok);
1445 break;
1446 }
1447 }
1448 }
1449}
1450
1451PreprocessedEntityID
1452ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1453 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1454 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1455 assert(I != M.PreprocessedEntityRemap.end()
1456 && "Invalid index into preprocessed entity index remap");
1457
1458 return LocalID + I->second;
1459}
1460
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001461unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1462 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001463}
1464
1465HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001466HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1467 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1468 FE->getName() };
1469 return ikey;
1470}
Guy Benyei11169dd2012-12-18 14:30:41 +00001471
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001472bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1473 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 return false;
1475
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476 if (strcmp(a.Filename, b.Filename) == 0)
1477 return true;
1478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001480 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001481 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1482 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001483 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001484}
1485
1486std::pair<unsigned, unsigned>
1487HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001488 using namespace llvm::support;
1489 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001491 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001492}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001493
1494HeaderFileInfoTrait::internal_key_type
1495HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001496 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001498 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1499 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001500 ikey.Filename = (const char *)d;
1501 return ikey;
1502}
1503
Guy Benyei11169dd2012-12-18 14:30:41 +00001504HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001505HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 unsigned DataLen) {
1507 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001508 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 HeaderFileInfo HFI;
1510 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001511 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1512 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 HFI.isImport = (Flags >> 5) & 0x01;
1514 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1515 HFI.DirInfo = (Flags >> 2) & 0x03;
1516 HFI.Resolved = (Flags >> 1) & 0x01;
1517 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1519 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1520 M, endian::readNext<uint32_t, little, unaligned>(d));
1521 if (unsigned FrameworkOffset =
1522 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 // The framework offset is 1 greater than the actual offset,
1524 // since 0 is used as an indicator for "no framework name".
1525 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1526 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1527 }
1528
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001529 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001531 if (LocalSMID) {
1532 // This header is part of a module. Associate it with the module to enable
1533 // implicit module import.
1534 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1535 Module *Mod = Reader.getSubmodule(GlobalSMID);
1536 HFI.isModuleHeader = true;
1537 FileManager &FileMgr = Reader.getFileManager();
1538 ModuleMap &ModMap =
1539 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001540 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001541 }
1542 }
1543
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1545 (void)End;
1546
1547 // This HeaderFileInfo was externally loaded.
1548 HFI.External = true;
1549 return HFI;
1550}
1551
Richard Smith49f906a2014-03-01 00:08:04 +00001552void
1553ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1554 GlobalMacroID GMacID,
1555 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001556 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Richard Smith49f906a2014-03-01 00:08:04 +00001557 SubmoduleID *OverrideData = 0;
1558 if (!Overrides.empty()) {
1559 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1560 OverrideData[0] = Overrides.size();
1561 for (unsigned I = 0; I != Overrides.size(); ++I)
1562 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1563 }
1564 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001565}
1566
1567void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1568 ModuleFile *M,
1569 uint64_t MacroDirectivesOffset) {
1570 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1571 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001572}
1573
1574void ASTReader::ReadDefinedMacros() {
1575 // Note that we are loading defined macros.
1576 Deserializing Macros(this);
1577
1578 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1579 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001580 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001581
1582 // If there was no preprocessor block, skip this file.
1583 if (!MacroCursor.getBitStreamReader())
1584 continue;
1585
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001586 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 Cursor.JumpToBit((*I)->MacroStartOffset);
1588
1589 RecordData Record;
1590 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001591 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1592
1593 switch (E.Kind) {
1594 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1595 case llvm::BitstreamEntry::Error:
1596 Error("malformed block record in AST file");
1597 return;
1598 case llvm::BitstreamEntry::EndBlock:
1599 goto NextCursor;
1600
1601 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001602 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001603 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001604 default: // Default behavior: ignore.
1605 break;
1606
1607 case PP_MACRO_OBJECT_LIKE:
1608 case PP_MACRO_FUNCTION_LIKE:
1609 getLocalIdentifier(**I, Record[0]);
1610 break;
1611
1612 case PP_TOKEN:
1613 // Ignore tokens.
1614 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 break;
1617 }
1618 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001619 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 }
1621}
1622
1623namespace {
1624 /// \brief Visitor class used to look up identifirs in an AST file.
1625 class IdentifierLookupVisitor {
1626 StringRef Name;
1627 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001628 unsigned &NumIdentifierLookups;
1629 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001630 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001631
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001633 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1634 unsigned &NumIdentifierLookups,
1635 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001636 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001637 NumIdentifierLookups(NumIdentifierLookups),
1638 NumIdentifierLookupHits(NumIdentifierLookupHits),
1639 Found()
1640 {
1641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001642
1643 static bool visit(ModuleFile &M, void *UserData) {
1644 IdentifierLookupVisitor *This
1645 = static_cast<IdentifierLookupVisitor *>(UserData);
1646
1647 // If we've already searched this module file, skip it now.
1648 if (M.Generation <= This->PriorGeneration)
1649 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001650
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 ASTIdentifierLookupTable *IdTable
1652 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1653 if (!IdTable)
1654 return false;
1655
1656 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1657 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001658 ++This->NumIdentifierLookups;
1659 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 if (Pos == IdTable->end())
1661 return false;
1662
1663 // Dereferencing the iterator has the effect of building the
1664 // IdentifierInfo node and populating it with the various
1665 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001666 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 This->Found = *Pos;
1668 return true;
1669 }
1670
1671 // \brief Retrieve the identifier info found within the module
1672 // files.
1673 IdentifierInfo *getIdentifierInfo() const { return Found; }
1674 };
1675}
1676
1677void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1678 // Note that we are loading an identifier.
1679 Deserializing AnIdentifier(this);
1680
1681 unsigned PriorGeneration = 0;
1682 if (getContext().getLangOpts().Modules)
1683 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001684
1685 // If there is a global index, look there first to determine which modules
1686 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001687 GlobalModuleIndex::HitSet Hits;
1688 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00001689 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001690 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1691 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001692 }
1693 }
1694
Douglas Gregor7211ac12013-01-25 23:32:03 +00001695 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001696 NumIdentifierLookups,
1697 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001698 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001699 markIdentifierUpToDate(&II);
1700}
1701
1702void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1703 if (!II)
1704 return;
1705
1706 II->setOutOfDate(false);
1707
1708 // Update the generation for this identifier.
1709 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001710 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001711}
1712
Richard Smith49f906a2014-03-01 00:08:04 +00001713struct ASTReader::ModuleMacroInfo {
1714 SubmoduleID SubModID;
1715 MacroInfo *MI;
1716 SubmoduleID *Overrides;
1717 // FIXME: Remove this.
1718 ModuleFile *F;
1719
1720 bool isDefine() const { return MI; }
1721
1722 SubmoduleID getSubmoduleID() const { return SubModID; }
1723
1724 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1725 if (!Overrides)
1726 return llvm::ArrayRef<SubmoduleID>();
1727 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1728 }
1729
1730 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1731 if (!MI)
1732 return 0;
1733 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1734 }
1735};
1736
1737ASTReader::ModuleMacroInfo *
1738ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1739 ModuleMacroInfo Info;
1740
1741 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1742 if (ID & 1) {
1743 // Macro undefinition.
1744 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1745 Info.MI = 0;
1746 } else {
1747 // Macro definition.
1748 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1749 assert(GMacID);
1750
1751 // If this macro has already been loaded, don't do so again.
1752 // FIXME: This is highly dubious. Multiple macro definitions can have the
1753 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1754 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1755 return 0;
1756
1757 Info.MI = getMacro(GMacID);
1758 Info.SubModID = Info.MI->getOwningModuleID();
1759 }
1760 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1761 Info.F = PMInfo.M;
1762
1763 return new (Context) ModuleMacroInfo(Info);
1764}
1765
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001766void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1767 const PendingMacroInfo &PMInfo) {
1768 assert(II);
1769
1770 if (PMInfo.M->Kind != MK_Module) {
1771 installPCHMacroDirectives(II, *PMInfo.M,
1772 PMInfo.PCHMacroData.MacroDirectivesOffset);
1773 return;
1774 }
Richard Smith49f906a2014-03-01 00:08:04 +00001775
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001776 // Module Macro.
1777
Richard Smith49f906a2014-03-01 00:08:04 +00001778 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1779 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001780 return;
1781
Richard Smith49f906a2014-03-01 00:08:04 +00001782 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1783 if (Owner && Owner->NameVisibility == Module::Hidden) {
1784 // Macros in the owning module are hidden. Just remember this macro to
1785 // install if we make this module visible.
1786 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1787 } else {
1788 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001789 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001790}
1791
1792void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1793 ModuleFile &M, uint64_t Offset) {
1794 assert(M.Kind != MK_Module);
1795
1796 BitstreamCursor &Cursor = M.MacroCursor;
1797 SavedStreamPosition SavedPosition(Cursor);
1798 Cursor.JumpToBit(Offset);
1799
1800 llvm::BitstreamEntry Entry =
1801 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1802 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1803 Error("malformed block record in AST file");
1804 return;
1805 }
1806
1807 RecordData Record;
1808 PreprocessorRecordTypes RecType =
1809 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1810 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 // Deserialize the macro directives history in reverse source-order.
1816 MacroDirective *Latest = 0, *Earliest = 0;
1817 unsigned Idx = 0, N = Record.size();
1818 while (Idx < N) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001819 MacroDirective *MD = 0;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1822 switch (K) {
1823 case MacroDirective::MD_Define: {
1824 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1825 MacroInfo *MI = getMacro(GMacID);
1826 bool isImported = Record[Idx++];
1827 bool isAmbiguous = Record[Idx++];
1828 DefMacroDirective *DefMD =
1829 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1830 DefMD->setAmbiguous(isAmbiguous);
1831 MD = DefMD;
1832 break;
1833 }
1834 case MacroDirective::MD_Undefine:
1835 MD = PP.AllocateUndefMacroDirective(Loc);
1836 break;
1837 case MacroDirective::MD_Visibility: {
1838 bool isPublic = Record[Idx++];
1839 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1840 break;
1841 }
1842 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001843
1844 if (!Latest)
1845 Latest = MD;
1846 if (Earliest)
1847 Earliest->setPrevious(MD);
1848 Earliest = MD;
1849 }
1850
1851 PP.setLoadedMacroDirective(II, Latest);
1852}
1853
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001854/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001855/// modules.
1856static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001857 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001858 assert(PrevMI && NewMI);
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001859 Module *PrevOwner = 0;
1860 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1861 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001862 SourceManager &SrcMgr = Reader.getSourceManager();
1863 bool PrevInSystem
1864 = PrevOwner? PrevOwner->IsSystem
1865 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1866 bool NewInSystem
1867 = NewOwner? NewOwner->IsSystem
1868 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1869 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001870 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001871 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001872}
1873
Richard Smith49f906a2014-03-01 00:08:04 +00001874void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1875 AmbiguousMacros &Ambig,
1876 llvm::ArrayRef<SubmoduleID> Overrides) {
1877 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1878 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001879
Richard Smith49f906a2014-03-01 00:08:04 +00001880 // If this macro is not yet visible, remove it from the hidden names list.
1881 Module *Owner = getSubmodule(OwnerID);
1882 HiddenNames &Hidden = HiddenNamesMap[Owner];
1883 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1884 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001885 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001886 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001887 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001888 }
1889
1890 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001891 Ambig.erase(
1892 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1893 return MD->getInfo()->getOwningModuleID() == OwnerID;
1894 }),
1895 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001896 }
1897}
1898
1899ASTReader::AmbiguousMacros *
1900ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1901 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001902 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001903 if (!Prev && Overrides.empty())
1904 return 0;
1905
1906 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1907 if (PrevDef && PrevDef->isAmbiguous()) {
1908 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1909 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1910 Ambig.push_back(PrevDef);
1911
1912 removeOverriddenMacros(II, Ambig, Overrides);
1913
1914 if (!Ambig.empty())
1915 return &Ambig;
1916
1917 AmbiguousMacroDefs.erase(II);
1918 } else {
1919 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001920 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001921 if (PrevDef)
1922 Ambig.push_back(PrevDef);
1923
1924 removeOverriddenMacros(II, Ambig, Overrides);
1925
1926 if (!Ambig.empty()) {
1927 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001928 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001929 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001930 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001931 }
Richard Smith49f906a2014-03-01 00:08:04 +00001932
1933 // We ended up with no ambiguity.
1934 return 0;
1935}
1936
1937void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1938 Module *Owner) {
1939 assert(II && Owner);
1940
1941 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1942 if (ImportLoc.isInvalid()) {
1943 // FIXME: If we made macros from this module visible but didn't provide a
1944 // source location for the import, we don't have a location for the macro.
1945 // Use the location at which the containing module file was first imported
1946 // for now.
1947 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001948 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001949 }
1950
Benjamin Kramer834652a2014-05-03 18:44:26 +00001951 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001952 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1953
Richard Smith49f906a2014-03-01 00:08:04 +00001954 // 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
Richard Smithd1c46742014-04-30 02:24:17 +00003434 // Defer any pending actions until we get to the end of reading the AST file.
3435 Deserializing AnASTFile(this);
3436
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003438 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003439
3440 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003441 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3443 /*ImportedBy=*/0, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003444 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 ClientLoadCapabilities)) {
3446 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003447 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 case OutOfDate:
3449 case VersionMismatch:
3450 case ConfigurationMismatch:
3451 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003452 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3453 Context.getLangOpts().Modules
3454 ? &PP.getHeaderSearchInfo().getModuleMap()
3455 : 0);
Douglas Gregore060e572013-01-25 01:03:03 +00003456
3457 // If we find that any modules are unusable, the global index is going
3458 // to be out-of-date. Just remove it.
3459 GlobalIndex.reset();
Douglas Gregor7211ac12013-01-25 23:32:03 +00003460 ModuleMgr.setGlobalIndex(0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 return ReadResult;
3462
3463 case Success:
3464 break;
3465 }
3466
3467 // Here comes stuff that we only do once the entire chain is loaded.
3468
3469 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003470 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3471 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 M != MEnd; ++M) {
3473 ModuleFile &F = *M->Mod;
3474
3475 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003476 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3477 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003478
3479 // Once read, set the ModuleFile bit base offset and update the size in
3480 // bits of all files we've seen.
3481 F.GlobalBitOffset = TotalModulesSizeInBits;
3482 TotalModulesSizeInBits += F.SizeInBits;
3483 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3484
3485 // Preload SLocEntries.
3486 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3487 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3488 // Load it through the SourceManager and don't call ReadSLocEntry()
3489 // directly because the entry may have already been loaded in which case
3490 // calling ReadSLocEntry() directly would trigger an assertion in
3491 // SourceManager.
3492 SourceMgr.getLoadedSLocEntryByID(Index);
3493 }
3494 }
3495
Douglas Gregor603cd862013-03-22 18:50:14 +00003496 // Setup the import locations and notify the module manager that we've
3497 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003498 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3499 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 M != MEnd; ++M) {
3501 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003502
3503 ModuleMgr.moduleFileAccepted(&F);
3504
3505 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003506 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 if (!M->ImportedBy)
3508 F.ImportLoc = M->ImportLoc;
3509 else
3510 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3511 M->ImportLoc.getRawEncoding());
3512 }
3513
3514 // Mark all of the identifiers in the identifier table as being out of date,
3515 // so that various accessors know to check the loaded modules when the
3516 // identifier is used.
3517 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3518 IdEnd = PP.getIdentifierTable().end();
3519 Id != IdEnd; ++Id)
3520 Id->second->setOutOfDate(true);
3521
3522 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003523 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3524 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3526 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003527
3528 switch (Unresolved.Kind) {
3529 case UnresolvedModuleRef::Conflict:
3530 if (ResolvedMod) {
3531 Module::Conflict Conflict;
3532 Conflict.Other = ResolvedMod;
3533 Conflict.Message = Unresolved.String.str();
3534 Unresolved.Mod->Conflicts.push_back(Conflict);
3535 }
3536 continue;
3537
3538 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 if (ResolvedMod)
3540 Unresolved.Mod->Imports.push_back(ResolvedMod);
3541 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003542
Douglas Gregorfb912652013-03-20 21:10:35 +00003543 case UnresolvedModuleRef::Export:
3544 if (ResolvedMod || Unresolved.IsWildcard)
3545 Unresolved.Mod->Exports.push_back(
3546 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3547 continue;
3548 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003550 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003551
3552 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3553 // Might be unnecessary as use declarations are only used to build the
3554 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003555
3556 InitializeContext();
3557
Richard Smith3d8e97e2013-10-18 06:54:39 +00003558 if (SemaObj)
3559 UpdateSema();
3560
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 if (DeserializationListener)
3562 DeserializationListener->ReaderInitialized(this);
3563
3564 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3565 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3566 PrimaryModule.OriginalSourceFileID
3567 = FileID::get(PrimaryModule.SLocEntryBaseID
3568 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3569
3570 // If this AST file is a precompiled preamble, then set the
3571 // preamble file ID of the source manager to the file source file
3572 // from which the preamble was built.
3573 if (Type == MK_Preamble) {
3574 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3575 } else if (Type == MK_MainFile) {
3576 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3577 }
3578 }
3579
3580 // For any Objective-C class definitions we have already loaded, make sure
3581 // that we load any additional categories.
3582 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3583 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3584 ObjCClassesLoaded[I],
3585 PreviousGeneration);
3586 }
Douglas Gregore060e572013-01-25 01:03:03 +00003587
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003588 if (PP.getHeaderSearchInfo()
3589 .getHeaderSearchOpts()
3590 .ModulesValidateOncePerBuildSession) {
3591 // Now we are certain that the module and all modules it depends on are
3592 // up to date. Create or update timestamp files for modules that are
3593 // located in the module cache (not for PCH files that could be anywhere
3594 // in the filesystem).
3595 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3596 ImportedModule &M = Loaded[I];
3597 if (M.Mod->Kind == MK_Module) {
3598 updateModuleTimestamp(*M.Mod);
3599 }
3600 }
3601 }
3602
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 return Success;
3604}
3605
3606ASTReader::ASTReadResult
3607ASTReader::ReadASTCore(StringRef FileName,
3608 ModuleKind Type,
3609 SourceLocation ImportLoc,
3610 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003611 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003612 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 unsigned ClientLoadCapabilities) {
3614 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003616 ModuleManager::AddModuleResult AddResult
3617 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003618 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003619 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003620
Douglas Gregor7029ce12013-03-19 00:28:20 +00003621 switch (AddResult) {
3622 case ModuleManager::AlreadyLoaded:
3623 return Success;
3624
3625 case ModuleManager::NewlyLoaded:
3626 // Load module file below.
3627 break;
3628
3629 case ModuleManager::Missing:
3630 // The module file was missing; if the client handle handle, that, return
3631 // it.
3632 if (ClientLoadCapabilities & ARR_Missing)
3633 return Missing;
3634
3635 // Otherwise, return an error.
3636 {
3637 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3638 + ErrorStr;
3639 Error(Msg);
3640 }
3641 return Failure;
3642
3643 case ModuleManager::OutOfDate:
3644 // We couldn't load the module file because it is out-of-date. If the
3645 // client can handle out-of-date, return it.
3646 if (ClientLoadCapabilities & ARR_OutOfDate)
3647 return OutOfDate;
3648
3649 // Otherwise, return an error.
3650 {
3651 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3652 + ErrorStr;
3653 Error(Msg);
3654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 return Failure;
3656 }
3657
Douglas Gregor7029ce12013-03-19 00:28:20 +00003658 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003659
3660 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3661 // module?
3662 if (FileName != "-") {
3663 CurrentDir = llvm::sys::path::parent_path(FileName);
3664 if (CurrentDir.empty()) CurrentDir = ".";
3665 }
3666
3667 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003668 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 Stream.init(F.StreamFile);
3670 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3671
3672 // Sniff for the signature.
3673 if (Stream.Read(8) != 'C' ||
3674 Stream.Read(8) != 'P' ||
3675 Stream.Read(8) != 'C' ||
3676 Stream.Read(8) != 'H') {
3677 Diag(diag::err_not_a_pch_file) << FileName;
3678 return Failure;
3679 }
3680
3681 // This is used for compatibility with older PCH formats.
3682 bool HaveReadControlBlock = false;
3683
Chris Lattnerefa77172013-01-20 00:00:22 +00003684 while (1) {
3685 llvm::BitstreamEntry Entry = Stream.advance();
3686
3687 switch (Entry.Kind) {
3688 case llvm::BitstreamEntry::Error:
3689 case llvm::BitstreamEntry::EndBlock:
3690 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 Error("invalid record at top-level of AST file");
3692 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003693
3694 case llvm::BitstreamEntry::SubBlock:
3695 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003696 }
3697
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003699 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3701 if (Stream.ReadBlockInfoBlock()) {
3702 Error("malformed BlockInfoBlock in AST file");
3703 return Failure;
3704 }
3705 break;
3706 case CONTROL_BLOCK_ID:
3707 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003708 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 case Success:
3710 break;
3711
3712 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003713 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 case OutOfDate: return OutOfDate;
3715 case VersionMismatch: return VersionMismatch;
3716 case ConfigurationMismatch: return ConfigurationMismatch;
3717 case HadErrors: return HadErrors;
3718 }
3719 break;
3720 case AST_BLOCK_ID:
3721 if (!HaveReadControlBlock) {
3722 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003723 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 return VersionMismatch;
3725 }
3726
3727 // Record that we've loaded this module.
3728 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3729 return Success;
3730
3731 default:
3732 if (Stream.SkipBlock()) {
3733 Error("malformed block record in AST file");
3734 return Failure;
3735 }
3736 break;
3737 }
3738 }
3739
3740 return Success;
3741}
3742
3743void ASTReader::InitializeContext() {
3744 // If there's a listener, notify them that we "read" the translation unit.
3745 if (DeserializationListener)
3746 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3747 Context.getTranslationUnitDecl());
3748
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 // FIXME: Find a better way to deal with collisions between these
3750 // built-in types. Right now, we just ignore the problem.
3751
3752 // Load the special types.
3753 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3754 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3755 if (!Context.CFConstantStringTypeDecl)
3756 Context.setCFConstantStringType(GetType(String));
3757 }
3758
3759 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3760 QualType FileType = GetType(File);
3761 if (FileType.isNull()) {
3762 Error("FILE type is NULL");
3763 return;
3764 }
3765
3766 if (!Context.FILEDecl) {
3767 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3768 Context.setFILEDecl(Typedef->getDecl());
3769 else {
3770 const TagType *Tag = FileType->getAs<TagType>();
3771 if (!Tag) {
3772 Error("Invalid FILE type in AST file");
3773 return;
3774 }
3775 Context.setFILEDecl(Tag->getDecl());
3776 }
3777 }
3778 }
3779
3780 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3781 QualType Jmp_bufType = GetType(Jmp_buf);
3782 if (Jmp_bufType.isNull()) {
3783 Error("jmp_buf type is NULL");
3784 return;
3785 }
3786
3787 if (!Context.jmp_bufDecl) {
3788 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3789 Context.setjmp_bufDecl(Typedef->getDecl());
3790 else {
3791 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3792 if (!Tag) {
3793 Error("Invalid jmp_buf type in AST file");
3794 return;
3795 }
3796 Context.setjmp_bufDecl(Tag->getDecl());
3797 }
3798 }
3799 }
3800
3801 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3802 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3803 if (Sigjmp_bufType.isNull()) {
3804 Error("sigjmp_buf type is NULL");
3805 return;
3806 }
3807
3808 if (!Context.sigjmp_bufDecl) {
3809 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3810 Context.setsigjmp_bufDecl(Typedef->getDecl());
3811 else {
3812 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3813 assert(Tag && "Invalid sigjmp_buf type in AST file");
3814 Context.setsigjmp_bufDecl(Tag->getDecl());
3815 }
3816 }
3817 }
3818
3819 if (unsigned ObjCIdRedef
3820 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3821 if (Context.ObjCIdRedefinitionType.isNull())
3822 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3823 }
3824
3825 if (unsigned ObjCClassRedef
3826 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3827 if (Context.ObjCClassRedefinitionType.isNull())
3828 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3829 }
3830
3831 if (unsigned ObjCSelRedef
3832 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3833 if (Context.ObjCSelRedefinitionType.isNull())
3834 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3835 }
3836
3837 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3838 QualType Ucontext_tType = GetType(Ucontext_t);
3839 if (Ucontext_tType.isNull()) {
3840 Error("ucontext_t type is NULL");
3841 return;
3842 }
3843
3844 if (!Context.ucontext_tDecl) {
3845 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3846 Context.setucontext_tDecl(Typedef->getDecl());
3847 else {
3848 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3849 assert(Tag && "Invalid ucontext_t type in AST file");
3850 Context.setucontext_tDecl(Tag->getDecl());
3851 }
3852 }
3853 }
3854 }
3855
3856 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3857
3858 // If there were any CUDA special declarations, deserialize them.
3859 if (!CUDASpecialDeclRefs.empty()) {
3860 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3861 Context.setcudaConfigureCallDecl(
3862 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3863 }
Richard Smith56be7542014-03-21 00:33:59 +00003864
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003866 // FIXME: This does not make macro-only imports visible again. It also doesn't
3867 // make #includes mapped to module imports visible.
3868 for (auto &Import : ImportedModules) {
3869 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003870 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003871 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003872 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 }
3874 ImportedModules.clear();
3875}
3876
3877void ASTReader::finalizeForWriting() {
3878 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3879 HiddenEnd = HiddenNamesMap.end();
3880 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003881 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 }
3883 HiddenNamesMap.clear();
3884}
3885
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003886/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3887/// cursor into the start of the given block ID, returning false on success and
3888/// true on failure.
3889static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003890 while (1) {
3891 llvm::BitstreamEntry Entry = Cursor.advance();
3892 switch (Entry.Kind) {
3893 case llvm::BitstreamEntry::Error:
3894 case llvm::BitstreamEntry::EndBlock:
3895 return true;
3896
3897 case llvm::BitstreamEntry::Record:
3898 // Ignore top-level records.
3899 Cursor.skipRecord(Entry.ID);
3900 break;
3901
3902 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003903 if (Entry.ID == BlockID) {
3904 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003905 return true;
3906 // Found it!
3907 return false;
3908 }
3909
3910 if (Cursor.SkipBlock())
3911 return true;
3912 }
3913 }
3914}
3915
Guy Benyei11169dd2012-12-18 14:30:41 +00003916/// \brief Retrieve the name of the original source file name
3917/// directly from the AST file, without actually loading the AST
3918/// file.
3919std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3920 FileManager &FileMgr,
3921 DiagnosticsEngine &Diags) {
3922 // Open the AST file.
3923 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003924 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3926 if (!Buffer) {
3927 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3928 return std::string();
3929 }
3930
3931 // Initialize the stream
3932 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003933 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3935 (const unsigned char *)Buffer->getBufferEnd());
3936 Stream.init(StreamFile);
3937
3938 // Sniff for the signature.
3939 if (Stream.Read(8) != 'C' ||
3940 Stream.Read(8) != 'P' ||
3941 Stream.Read(8) != 'C' ||
3942 Stream.Read(8) != 'H') {
3943 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3944 return std::string();
3945 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003946
Chris Lattnere7b154b2013-01-19 21:39:22 +00003947 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003948 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003949 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3950 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003951 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003952
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003953 // Scan for ORIGINAL_FILE inside the control block.
3954 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003955 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003956 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003957 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3958 return std::string();
3959
3960 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3961 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3962 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003964
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003966 StringRef Blob;
3967 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3968 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003970}
3971
3972namespace {
3973 class SimplePCHValidator : public ASTReaderListener {
3974 const LangOptions &ExistingLangOpts;
3975 const TargetOptions &ExistingTargetOpts;
3976 const PreprocessorOptions &ExistingPPOpts;
3977 FileManager &FileMgr;
3978
3979 public:
3980 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3981 const TargetOptions &ExistingTargetOpts,
3982 const PreprocessorOptions &ExistingPPOpts,
3983 FileManager &FileMgr)
3984 : ExistingLangOpts(ExistingLangOpts),
3985 ExistingTargetOpts(ExistingTargetOpts),
3986 ExistingPPOpts(ExistingPPOpts),
3987 FileMgr(FileMgr)
3988 {
3989 }
3990
Craig Topper3e89dfe2014-03-13 02:13:41 +00003991 bool ReadLanguageOptions(const LangOptions &LangOpts,
3992 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3994 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003995 bool ReadTargetOptions(const TargetOptions &TargetOpts,
3996 bool Complain) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3998 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003999 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4000 bool Complain,
4001 std::string &SuggestedPredefines) override {
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004003 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 }
4005 };
4006}
4007
4008bool ASTReader::readASTFileControlBlock(StringRef Filename,
4009 FileManager &FileMgr,
4010 ASTReaderListener &Listener) {
4011 // Open the AST file.
4012 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004013 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4015 if (!Buffer) {
4016 return true;
4017 }
4018
4019 // Initialize the stream
4020 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004021 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4023 (const unsigned char *)Buffer->getBufferEnd());
4024 Stream.init(StreamFile);
4025
4026 // Sniff for the signature.
4027 if (Stream.Read(8) != 'C' ||
4028 Stream.Read(8) != 'P' ||
4029 Stream.Read(8) != 'C' ||
4030 Stream.Read(8) != 'H') {
4031 return true;
4032 }
4033
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004034 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004035 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004037
4038 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004039 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004040 BitstreamCursor InputFilesCursor;
4041 if (NeedsInputFiles) {
4042 InputFilesCursor = Stream;
4043 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4044 return true;
4045
4046 // Read the abbreviations
4047 while (true) {
4048 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4049 unsigned Code = InputFilesCursor.ReadCode();
4050
4051 // We expect all abbrevs to be at the start of the block.
4052 if (Code != llvm::bitc::DEFINE_ABBREV) {
4053 InputFilesCursor.JumpToBit(Offset);
4054 break;
4055 }
4056 InputFilesCursor.ReadAbbrevRecord();
4057 }
4058 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004059
4060 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004062 while (1) {
4063 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4064 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4065 return false;
4066
4067 if (Entry.Kind != llvm::BitstreamEntry::Record)
4068 return true;
4069
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004071 StringRef Blob;
4072 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004073 switch ((ControlRecordTypes)RecCode) {
4074 case METADATA: {
4075 if (Record[0] != VERSION_MAJOR)
4076 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004077
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004078 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004080
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 break;
4082 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004083 case MODULE_NAME:
4084 Listener.ReadModuleName(Blob);
4085 break;
4086 case MODULE_MAP_FILE:
4087 Listener.ReadModuleMapFile(Blob);
4088 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004089 case LANGUAGE_OPTIONS:
4090 if (ParseLanguageOptions(Record, false, Listener))
4091 return true;
4092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004093
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004094 case TARGET_OPTIONS:
4095 if (ParseTargetOptions(Record, false, Listener))
4096 return true;
4097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004098
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004099 case DIAGNOSTIC_OPTIONS:
4100 if (ParseDiagnosticOptions(Record, false, Listener))
4101 return true;
4102 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004104 case FILE_SYSTEM_OPTIONS:
4105 if (ParseFileSystemOptions(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 HEADER_SEARCH_OPTIONS:
4110 if (ParseHeaderSearchOptions(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 PREPROCESSOR_OPTIONS: {
4115 std::string IgnoredSuggestedPredefines;
4116 if (ParsePreprocessorOptions(Record, false, Listener,
4117 IgnoredSuggestedPredefines))
4118 return true;
4119 break;
4120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004121
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004122 case INPUT_FILE_OFFSETS: {
4123 if (!NeedsInputFiles)
4124 break;
4125
4126 unsigned NumInputFiles = Record[0];
4127 unsigned NumUserFiles = Record[1];
4128 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4129 for (unsigned I = 0; I != NumInputFiles; ++I) {
4130 // Go find this input file.
4131 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004132
4133 if (isSystemFile && !NeedsSystemInputFiles)
4134 break; // the rest are system input files
4135
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004136 BitstreamCursor &Cursor = InputFilesCursor;
4137 SavedStreamPosition SavedPosition(Cursor);
4138 Cursor.JumpToBit(InputFileOffs[I]);
4139
4140 unsigned Code = Cursor.ReadCode();
4141 RecordData Record;
4142 StringRef Blob;
4143 bool shouldContinue = false;
4144 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4145 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004146 bool Overridden = static_cast<bool>(Record[3]);
4147 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004148 break;
4149 }
4150 if (!shouldContinue)
4151 break;
4152 }
4153 break;
4154 }
4155
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004156 default:
4157 // No other validation to perform.
4158 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004159 }
4160 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004161}
4162
4163
4164bool ASTReader::isAcceptableASTFile(StringRef Filename,
4165 FileManager &FileMgr,
4166 const LangOptions &LangOpts,
4167 const TargetOptions &TargetOpts,
4168 const PreprocessorOptions &PPOpts) {
4169 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4170 return !readASTFileControlBlock(Filename, FileMgr, validator);
4171}
4172
Ben Langmuir2c9af442014-04-10 17:57:43 +00004173ASTReader::ASTReadResult
4174ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 // Enter the submodule block.
4176 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4177 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004178 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 }
4180
4181 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4182 bool First = true;
4183 Module *CurrentModule = 0;
4184 RecordData Record;
4185 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004186 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4187
4188 switch (Entry.Kind) {
4189 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4190 case llvm::BitstreamEntry::Error:
4191 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004192 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004193 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004194 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004195 case llvm::BitstreamEntry::Record:
4196 // The interesting case.
4197 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004199
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004201 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004203 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 default: // Default behavior: ignore.
4205 break;
4206
4207 case SUBMODULE_DEFINITION: {
4208 if (First) {
4209 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004210 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 }
4212
Douglas Gregor8d932422013-03-20 03:59:18 +00004213 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004215 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
4217
Chris Lattner0e6c9402013-01-20 02:38:54 +00004218 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004219 unsigned Idx = 0;
4220 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4221 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4222 bool IsFramework = Record[Idx++];
4223 bool IsExplicit = Record[Idx++];
4224 bool IsSystem = Record[Idx++];
4225 bool IsExternC = Record[Idx++];
4226 bool InferSubmodules = Record[Idx++];
4227 bool InferExplicitSubmodules = Record[Idx++];
4228 bool InferExportWildcard = Record[Idx++];
4229 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004230
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004231 Module *ParentModule = nullptr;
4232 const FileEntry *ModuleMap = nullptr;
4233 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004235 ModuleMap = ParentModule->ModuleMap;
4236 }
4237
4238 if (!F.ModuleMapPath.empty())
4239 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4240
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 // Retrieve this (sub)module from the module map, creating it if
4242 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004243 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 IsFramework,
4245 IsExplicit).first;
4246 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4247 if (GlobalIndex >= SubmodulesLoaded.size() ||
4248 SubmodulesLoaded[GlobalIndex]) {
4249 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004250 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004252
Douglas Gregor7029ce12013-03-19 00:28:20 +00004253 if (!ParentModule) {
4254 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4255 if (CurFile != F.File) {
4256 if (!Diags.isDiagnosticInFlight()) {
4257 Diag(diag::err_module_file_conflict)
4258 << CurrentModule->getTopLevelModuleName()
4259 << CurFile->getName()
4260 << F.File->getName();
4261 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004262 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004263 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004264 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004265
4266 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004267 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004268
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 CurrentModule->IsFromModuleFile = true;
4270 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004271 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 CurrentModule->InferSubmodules = InferSubmodules;
4273 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4274 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004275 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 if (DeserializationListener)
4277 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4278
4279 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004280
Douglas Gregorfb912652013-03-20 21:10:35 +00004281 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004282 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004283 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004284 CurrentModule->UnresolvedConflicts.clear();
4285 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 break;
4287 }
4288
4289 case SUBMODULE_UMBRELLA_HEADER: {
4290 if (First) {
4291 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004292 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 }
4294
4295 if (!CurrentModule)
4296 break;
4297
Chris Lattner0e6c9402013-01-20 02:38:54 +00004298 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 if (!CurrentModule->getUmbrellaHeader())
4300 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4301 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004302 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4303 Error("mismatched umbrella headers in submodule");
4304 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 }
4306 }
4307 break;
4308 }
4309
4310 case SUBMODULE_HEADER: {
4311 if (First) {
4312 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004313 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 }
4315
4316 if (!CurrentModule)
4317 break;
4318
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004319 // We lazily associate headers with their modules via the HeaderInfoTable.
4320 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4321 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 break;
4323 }
4324
4325 case SUBMODULE_EXCLUDED_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
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004340 case SUBMODULE_PRIVATE_HEADER: {
4341 if (First) {
4342 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004343 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004344 }
4345
4346 if (!CurrentModule)
4347 break;
4348
4349 // 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.
4352 break;
4353 }
4354
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 case SUBMODULE_TOPHEADER: {
4356 if (First) {
4357 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004358 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 }
4360
4361 if (!CurrentModule)
4362 break;
4363
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004364 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 break;
4366 }
4367
4368 case SUBMODULE_UMBRELLA_DIR: {
4369 if (First) {
4370 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004371 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 }
4373
4374 if (!CurrentModule)
4375 break;
4376
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004378 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 if (!CurrentModule->getUmbrellaDir())
4380 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4381 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004382 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4383 Error("mismatched umbrella directories in submodule");
4384 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 }
4386 }
4387 break;
4388 }
4389
4390 case SUBMODULE_METADATA: {
4391 if (!First) {
4392 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395 First = false;
4396
4397 F.BaseSubmoduleID = getTotalNumSubmodules();
4398 F.LocalNumSubmodules = Record[0];
4399 unsigned LocalBaseSubmoduleID = Record[1];
4400 if (F.LocalNumSubmodules > 0) {
4401 // Introduce the global -> local mapping for submodules within this
4402 // module.
4403 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4404
4405 // Introduce the local -> global mapping for submodules within this
4406 // module.
4407 F.SubmoduleRemap.insertOrReplace(
4408 std::make_pair(LocalBaseSubmoduleID,
4409 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4410
4411 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4412 }
4413 break;
4414 }
4415
4416 case SUBMODULE_IMPORTS: {
4417 if (First) {
4418 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004419 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 }
4421
4422 if (!CurrentModule)
4423 break;
4424
4425 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004426 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 Unresolved.File = &F;
4428 Unresolved.Mod = CurrentModule;
4429 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004430 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004432 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 }
4434 break;
4435 }
4436
4437 case SUBMODULE_EXPORTS: {
4438 if (First) {
4439 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004440 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442
4443 if (!CurrentModule)
4444 break;
4445
4446 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004447 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 Unresolved.File = &F;
4449 Unresolved.Mod = CurrentModule;
4450 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004451 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004453 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455
4456 // Once we've loaded the set of exports, there's no reason to keep
4457 // the parsed, unresolved exports around.
4458 CurrentModule->UnresolvedExports.clear();
4459 break;
4460 }
4461 case SUBMODULE_REQUIRES: {
4462 if (First) {
4463 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004464 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
4466
4467 if (!CurrentModule)
4468 break;
4469
Richard Smitha3feee22013-10-28 22:18:19 +00004470 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 Context.getTargetInfo());
4472 break;
4473 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004474
4475 case SUBMODULE_LINK_LIBRARY:
4476 if (First) {
4477 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004478 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004479 }
4480
4481 if (!CurrentModule)
4482 break;
4483
4484 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004485 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004486 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004487
4488 case SUBMODULE_CONFIG_MACRO:
4489 if (First) {
4490 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004491 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004492 }
4493
4494 if (!CurrentModule)
4495 break;
4496
4497 CurrentModule->ConfigMacros.push_back(Blob.str());
4498 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004499
4500 case SUBMODULE_CONFLICT: {
4501 if (First) {
4502 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004503 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004504 }
4505
4506 if (!CurrentModule)
4507 break;
4508
4509 UnresolvedModuleRef Unresolved;
4510 Unresolved.File = &F;
4511 Unresolved.Mod = CurrentModule;
4512 Unresolved.ID = Record[0];
4513 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4514 Unresolved.IsWildcard = false;
4515 Unresolved.String = Blob;
4516 UnresolvedModuleRefs.push_back(Unresolved);
4517 break;
4518 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 }
4520 }
4521}
4522
4523/// \brief Parse the record that corresponds to a LangOptions data
4524/// structure.
4525///
4526/// This routine parses the language options from the AST file and then gives
4527/// them to the AST listener if one is set.
4528///
4529/// \returns true if the listener deems the file unacceptable, false otherwise.
4530bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4531 bool Complain,
4532 ASTReaderListener &Listener) {
4533 LangOptions LangOpts;
4534 unsigned Idx = 0;
4535#define LANGOPT(Name, Bits, Default, Description) \
4536 LangOpts.Name = Record[Idx++];
4537#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4538 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4539#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004540#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4541#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004542
4543 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4544 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4545 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4546
4547 unsigned Length = Record[Idx++];
4548 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4549 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004550
4551 Idx += Length;
4552
4553 // Comment options.
4554 for (unsigned N = Record[Idx++]; N; --N) {
4555 LangOpts.CommentOpts.BlockCommandNames.push_back(
4556 ReadString(Record, Idx));
4557 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004558 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004559
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 return Listener.ReadLanguageOptions(LangOpts, Complain);
4561}
4562
4563bool ASTReader::ParseTargetOptions(const RecordData &Record,
4564 bool Complain,
4565 ASTReaderListener &Listener) {
4566 unsigned Idx = 0;
4567 TargetOptions TargetOpts;
4568 TargetOpts.Triple = ReadString(Record, Idx);
4569 TargetOpts.CPU = ReadString(Record, Idx);
4570 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 for (unsigned N = Record[Idx++]; N; --N) {
4572 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4573 }
4574 for (unsigned N = Record[Idx++]; N; --N) {
4575 TargetOpts.Features.push_back(ReadString(Record, Idx));
4576 }
4577
4578 return Listener.ReadTargetOptions(TargetOpts, Complain);
4579}
4580
4581bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4582 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004583 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004585#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004586#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004587 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004588#include "clang/Basic/DiagnosticOptions.def"
4589
4590 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004591 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 }
4593
4594 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4595}
4596
4597bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4598 ASTReaderListener &Listener) {
4599 FileSystemOptions FSOpts;
4600 unsigned Idx = 0;
4601 FSOpts.WorkingDir = ReadString(Record, Idx);
4602 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4603}
4604
4605bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4606 bool Complain,
4607 ASTReaderListener &Listener) {
4608 HeaderSearchOptions HSOpts;
4609 unsigned Idx = 0;
4610 HSOpts.Sysroot = ReadString(Record, Idx);
4611
4612 // Include entries.
4613 for (unsigned N = Record[Idx++]; N; --N) {
4614 std::string Path = ReadString(Record, Idx);
4615 frontend::IncludeDirGroup Group
4616 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 bool IsFramework = Record[Idx++];
4618 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004620 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 }
4622
4623 // System header prefixes.
4624 for (unsigned N = Record[Idx++]; N; --N) {
4625 std::string Prefix = ReadString(Record, Idx);
4626 bool IsSystemHeader = Record[Idx++];
4627 HSOpts.SystemHeaderPrefixes.push_back(
4628 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4629 }
4630
4631 HSOpts.ResourceDir = ReadString(Record, Idx);
4632 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004633 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004634 HSOpts.DisableModuleHash = Record[Idx++];
4635 HSOpts.UseBuiltinIncludes = Record[Idx++];
4636 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4637 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4638 HSOpts.UseLibcxx = Record[Idx++];
4639
4640 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4641}
4642
4643bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4644 bool Complain,
4645 ASTReaderListener &Listener,
4646 std::string &SuggestedPredefines) {
4647 PreprocessorOptions PPOpts;
4648 unsigned Idx = 0;
4649
4650 // Macro definitions/undefs
4651 for (unsigned N = Record[Idx++]; N; --N) {
4652 std::string Macro = ReadString(Record, Idx);
4653 bool IsUndef = Record[Idx++];
4654 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4655 }
4656
4657 // Includes
4658 for (unsigned N = Record[Idx++]; N; --N) {
4659 PPOpts.Includes.push_back(ReadString(Record, Idx));
4660 }
4661
4662 // Macro Includes
4663 for (unsigned N = Record[Idx++]; N; --N) {
4664 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4665 }
4666
4667 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004668 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4670 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4671 PPOpts.ObjCXXARCStandardLibrary =
4672 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4673 SuggestedPredefines.clear();
4674 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4675 SuggestedPredefines);
4676}
4677
4678std::pair<ModuleFile *, unsigned>
4679ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4680 GlobalPreprocessedEntityMapType::iterator
4681 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4682 assert(I != GlobalPreprocessedEntityMap.end() &&
4683 "Corrupted global preprocessed entity map");
4684 ModuleFile *M = I->second;
4685 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4686 return std::make_pair(M, LocalIndex);
4687}
4688
4689std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4690ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4691 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4692 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4693 Mod.NumPreprocessedEntities);
4694
4695 return std::make_pair(PreprocessingRecord::iterator(),
4696 PreprocessingRecord::iterator());
4697}
4698
4699std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4700ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4701 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4702 ModuleDeclIterator(this, &Mod,
4703 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4704}
4705
4706PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4707 PreprocessedEntityID PPID = Index+1;
4708 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4709 ModuleFile &M = *PPInfo.first;
4710 unsigned LocalIndex = PPInfo.second;
4711 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4712
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 if (!PP.getPreprocessingRecord()) {
4714 Error("no preprocessing record");
4715 return 0;
4716 }
4717
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004718 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4719 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4720
4721 llvm::BitstreamEntry Entry =
4722 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4723 if (Entry.Kind != llvm::BitstreamEntry::Record)
4724 return 0;
4725
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 // Read the record.
4727 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4728 ReadSourceLocation(M, PPOffs.End));
4729 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004730 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 RecordData Record;
4732 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004733 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4734 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 switch (RecType) {
4736 case PPD_MACRO_EXPANSION: {
4737 bool isBuiltin = Record[0];
4738 IdentifierInfo *Name = 0;
4739 MacroDefinition *Def = 0;
4740 if (isBuiltin)
4741 Name = getLocalIdentifier(M, Record[1]);
4742 else {
4743 PreprocessedEntityID
4744 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4745 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4746 }
4747
4748 MacroExpansion *ME;
4749 if (isBuiltin)
4750 ME = new (PPRec) MacroExpansion(Name, Range);
4751 else
4752 ME = new (PPRec) MacroExpansion(Def, Range);
4753
4754 return ME;
4755 }
4756
4757 case PPD_MACRO_DEFINITION: {
4758 // Decode the identifier info and then check again; if the macro is
4759 // still defined and associated with the identifier,
4760 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4761 MacroDefinition *MD
4762 = new (PPRec) MacroDefinition(II, Range);
4763
4764 if (DeserializationListener)
4765 DeserializationListener->MacroDefinitionRead(PPID, MD);
4766
4767 return MD;
4768 }
4769
4770 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004771 const char *FullFileNameStart = Blob.data() + Record[0];
4772 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004773 const FileEntry *File = 0;
4774 if (!FullFileName.empty())
4775 File = PP.getFileManager().getFile(FullFileName);
4776
4777 // FIXME: Stable encoding
4778 InclusionDirective::InclusionKind Kind
4779 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4780 InclusionDirective *ID
4781 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004782 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 Record[1], Record[3],
4784 File,
4785 Range);
4786 return ID;
4787 }
4788 }
4789
4790 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4791}
4792
4793/// \brief \arg SLocMapI points at a chunk of a module that contains no
4794/// preprocessed entities or the entities it contains are not the ones we are
4795/// looking for. Find the next module that contains entities and return the ID
4796/// of the first entry.
4797PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4798 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4799 ++SLocMapI;
4800 for (GlobalSLocOffsetMapType::const_iterator
4801 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4802 ModuleFile &M = *SLocMapI->second;
4803 if (M.NumPreprocessedEntities)
4804 return M.BasePreprocessedEntityID;
4805 }
4806
4807 return getTotalNumPreprocessedEntities();
4808}
4809
4810namespace {
4811
4812template <unsigned PPEntityOffset::*PPLoc>
4813struct PPEntityComp {
4814 const ASTReader &Reader;
4815 ModuleFile &M;
4816
4817 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4818
4819 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4820 SourceLocation LHS = getLoc(L);
4821 SourceLocation RHS = getLoc(R);
4822 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4823 }
4824
4825 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4826 SourceLocation LHS = getLoc(L);
4827 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4828 }
4829
4830 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4831 SourceLocation RHS = getLoc(R);
4832 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4833 }
4834
4835 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4836 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4837 }
4838};
4839
4840}
4841
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004842PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4843 bool EndsAfter) const {
4844 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 return getTotalNumPreprocessedEntities();
4846
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004847 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4848 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4850 "Corrupted global sloc offset map");
4851
4852 if (SLocMapI->second->NumPreprocessedEntities == 0)
4853 return findNextPreprocessedEntity(SLocMapI);
4854
4855 ModuleFile &M = *SLocMapI->second;
4856 typedef const PPEntityOffset *pp_iterator;
4857 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4858 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4859
4860 size_t Count = M.NumPreprocessedEntities;
4861 size_t Half;
4862 pp_iterator First = pp_begin;
4863 pp_iterator PPI;
4864
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004865 if (EndsAfter) {
4866 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4867 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4868 } else {
4869 // Do a binary search manually instead of using std::lower_bound because
4870 // The end locations of entities may be unordered (when a macro expansion
4871 // is inside another macro argument), but for this case it is not important
4872 // whether we get the first macro expansion or its containing macro.
4873 while (Count > 0) {
4874 Half = Count / 2;
4875 PPI = First;
4876 std::advance(PPI, Half);
4877 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4878 Loc)) {
4879 First = PPI;
4880 ++First;
4881 Count = Count - Half - 1;
4882 } else
4883 Count = Half;
4884 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 }
4886
4887 if (PPI == pp_end)
4888 return findNextPreprocessedEntity(SLocMapI);
4889
4890 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4891}
4892
Guy Benyei11169dd2012-12-18 14:30:41 +00004893/// \brief Returns a pair of [Begin, End) indices of preallocated
4894/// preprocessed entities that \arg Range encompasses.
4895std::pair<unsigned, unsigned>
4896 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4897 if (Range.isInvalid())
4898 return std::make_pair(0,0);
4899 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4900
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004901 PreprocessedEntityID BeginID =
4902 findPreprocessedEntity(Range.getBegin(), false);
4903 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 return std::make_pair(BeginID, EndID);
4905}
4906
4907/// \brief Optionally returns true or false if the preallocated preprocessed
4908/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004909Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004910 FileID FID) {
4911 if (FID.isInvalid())
4912 return false;
4913
4914 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4915 ModuleFile &M = *PPInfo.first;
4916 unsigned LocalIndex = PPInfo.second;
4917 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4918
4919 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4920 if (Loc.isInvalid())
4921 return false;
4922
4923 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4924 return true;
4925 else
4926 return false;
4927}
4928
4929namespace {
4930 /// \brief Visitor used to search for information about a header file.
4931 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 const FileEntry *FE;
4933
David Blaikie05785d12013-02-20 22:23:23 +00004934 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004935
4936 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004937 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4938 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004939
4940 static bool visit(ModuleFile &M, void *UserData) {
4941 HeaderFileInfoVisitor *This
4942 = static_cast<HeaderFileInfoVisitor *>(UserData);
4943
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 HeaderFileInfoLookupTable *Table
4945 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4946 if (!Table)
4947 return false;
4948
4949 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004950 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 if (Pos == Table->end())
4952 return false;
4953
4954 This->HFI = *Pos;
4955 return true;
4956 }
4957
David Blaikie05785d12013-02-20 22:23:23 +00004958 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 };
4960}
4961
4962HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004963 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004965 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004967
4968 return HeaderFileInfo();
4969}
4970
4971void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4972 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004973 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4975 ModuleFile &F = *(*I);
4976 unsigned Idx = 0;
4977 DiagStates.clear();
4978 assert(!Diag.DiagStates.empty());
4979 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4980 while (Idx < F.PragmaDiagMappings.size()) {
4981 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4982 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4983 if (DiagStateID != 0) {
4984 Diag.DiagStatePoints.push_back(
4985 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4986 FullSourceLoc(Loc, SourceMgr)));
4987 continue;
4988 }
4989
4990 assert(DiagStateID == 0);
4991 // A new DiagState was created here.
4992 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4993 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4994 DiagStates.push_back(NewState);
4995 Diag.DiagStatePoints.push_back(
4996 DiagnosticsEngine::DiagStatePoint(NewState,
4997 FullSourceLoc(Loc, SourceMgr)));
4998 while (1) {
4999 assert(Idx < F.PragmaDiagMappings.size() &&
5000 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5001 if (Idx >= F.PragmaDiagMappings.size()) {
5002 break; // Something is messed up but at least avoid infinite loop in
5003 // release build.
5004 }
5005 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5006 if (DiagID == (unsigned)-1) {
5007 break; // no more diag/map pairs for this location.
5008 }
5009 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5010 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5011 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5012 }
5013 }
5014 }
5015}
5016
5017/// \brief Get the correct cursor and offset for loading a type.
5018ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5019 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5020 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5021 ModuleFile *M = I->second;
5022 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5023}
5024
5025/// \brief Read and return the type with the given index..
5026///
5027/// The index is the type ID, shifted and minus the number of predefs. This
5028/// routine actually reads the record corresponding to the type at the given
5029/// location. It is a helper routine for GetType, which deals with reading type
5030/// IDs.
5031QualType ASTReader::readTypeRecord(unsigned Index) {
5032 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005033 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005034
5035 // Keep track of where we are in the stream, then jump back there
5036 // after reading this type.
5037 SavedStreamPosition SavedPosition(DeclsCursor);
5038
5039 ReadingKindTracker ReadingKind(Read_Type, *this);
5040
5041 // Note that we are loading a type record.
5042 Deserializing AType(this);
5043
5044 unsigned Idx = 0;
5045 DeclsCursor.JumpToBit(Loc.Offset);
5046 RecordData Record;
5047 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005048 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 case TYPE_EXT_QUAL: {
5050 if (Record.size() != 2) {
5051 Error("Incorrect encoding of extended qualifier type");
5052 return QualType();
5053 }
5054 QualType Base = readType(*Loc.F, Record, Idx);
5055 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5056 return Context.getQualifiedType(Base, Quals);
5057 }
5058
5059 case TYPE_COMPLEX: {
5060 if (Record.size() != 1) {
5061 Error("Incorrect encoding of complex type");
5062 return QualType();
5063 }
5064 QualType ElemType = readType(*Loc.F, Record, Idx);
5065 return Context.getComplexType(ElemType);
5066 }
5067
5068 case TYPE_POINTER: {
5069 if (Record.size() != 1) {
5070 Error("Incorrect encoding of pointer type");
5071 return QualType();
5072 }
5073 QualType PointeeType = readType(*Loc.F, Record, Idx);
5074 return Context.getPointerType(PointeeType);
5075 }
5076
Reid Kleckner8a365022013-06-24 17:51:48 +00005077 case TYPE_DECAYED: {
5078 if (Record.size() != 1) {
5079 Error("Incorrect encoding of decayed type");
5080 return QualType();
5081 }
5082 QualType OriginalType = readType(*Loc.F, Record, Idx);
5083 QualType DT = Context.getAdjustedParameterType(OriginalType);
5084 if (!isa<DecayedType>(DT))
5085 Error("Decayed type does not decay");
5086 return DT;
5087 }
5088
Reid Kleckner0503a872013-12-05 01:23:43 +00005089 case TYPE_ADJUSTED: {
5090 if (Record.size() != 2) {
5091 Error("Incorrect encoding of adjusted type");
5092 return QualType();
5093 }
5094 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5095 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5096 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5097 }
5098
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case TYPE_BLOCK_POINTER: {
5100 if (Record.size() != 1) {
5101 Error("Incorrect encoding of block pointer type");
5102 return QualType();
5103 }
5104 QualType PointeeType = readType(*Loc.F, Record, Idx);
5105 return Context.getBlockPointerType(PointeeType);
5106 }
5107
5108 case TYPE_LVALUE_REFERENCE: {
5109 if (Record.size() != 2) {
5110 Error("Incorrect encoding of lvalue reference type");
5111 return QualType();
5112 }
5113 QualType PointeeType = readType(*Loc.F, Record, Idx);
5114 return Context.getLValueReferenceType(PointeeType, Record[1]);
5115 }
5116
5117 case TYPE_RVALUE_REFERENCE: {
5118 if (Record.size() != 1) {
5119 Error("Incorrect encoding of rvalue reference type");
5120 return QualType();
5121 }
5122 QualType PointeeType = readType(*Loc.F, Record, Idx);
5123 return Context.getRValueReferenceType(PointeeType);
5124 }
5125
5126 case TYPE_MEMBER_POINTER: {
5127 if (Record.size() != 2) {
5128 Error("Incorrect encoding of member pointer type");
5129 return QualType();
5130 }
5131 QualType PointeeType = readType(*Loc.F, Record, Idx);
5132 QualType ClassType = readType(*Loc.F, Record, Idx);
5133 if (PointeeType.isNull() || ClassType.isNull())
5134 return QualType();
5135
5136 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5137 }
5138
5139 case TYPE_CONSTANT_ARRAY: {
5140 QualType ElementType = readType(*Loc.F, Record, Idx);
5141 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5142 unsigned IndexTypeQuals = Record[2];
5143 unsigned Idx = 3;
5144 llvm::APInt Size = ReadAPInt(Record, Idx);
5145 return Context.getConstantArrayType(ElementType, Size,
5146 ASM, IndexTypeQuals);
5147 }
5148
5149 case TYPE_INCOMPLETE_ARRAY: {
5150 QualType ElementType = readType(*Loc.F, Record, Idx);
5151 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5152 unsigned IndexTypeQuals = Record[2];
5153 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5154 }
5155
5156 case TYPE_VARIABLE_ARRAY: {
5157 QualType ElementType = readType(*Loc.F, Record, Idx);
5158 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5159 unsigned IndexTypeQuals = Record[2];
5160 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5161 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5162 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5163 ASM, IndexTypeQuals,
5164 SourceRange(LBLoc, RBLoc));
5165 }
5166
5167 case TYPE_VECTOR: {
5168 if (Record.size() != 3) {
5169 Error("incorrect encoding of vector type in AST file");
5170 return QualType();
5171 }
5172
5173 QualType ElementType = readType(*Loc.F, Record, Idx);
5174 unsigned NumElements = Record[1];
5175 unsigned VecKind = Record[2];
5176 return Context.getVectorType(ElementType, NumElements,
5177 (VectorType::VectorKind)VecKind);
5178 }
5179
5180 case TYPE_EXT_VECTOR: {
5181 if (Record.size() != 3) {
5182 Error("incorrect encoding of extended vector type in AST file");
5183 return QualType();
5184 }
5185
5186 QualType ElementType = readType(*Loc.F, Record, Idx);
5187 unsigned NumElements = Record[1];
5188 return Context.getExtVectorType(ElementType, NumElements);
5189 }
5190
5191 case TYPE_FUNCTION_NO_PROTO: {
5192 if (Record.size() != 6) {
5193 Error("incorrect encoding of no-proto function type");
5194 return QualType();
5195 }
5196 QualType ResultType = readType(*Loc.F, Record, Idx);
5197 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5198 (CallingConv)Record[4], Record[5]);
5199 return Context.getFunctionNoProtoType(ResultType, Info);
5200 }
5201
5202 case TYPE_FUNCTION_PROTO: {
5203 QualType ResultType = readType(*Loc.F, Record, Idx);
5204
5205 FunctionProtoType::ExtProtoInfo EPI;
5206 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5207 /*hasregparm*/ Record[2],
5208 /*regparm*/ Record[3],
5209 static_cast<CallingConv>(Record[4]),
5210 /*produces*/ Record[5]);
5211
5212 unsigned Idx = 6;
5213 unsigned NumParams = Record[Idx++];
5214 SmallVector<QualType, 16> ParamTypes;
5215 for (unsigned I = 0; I != NumParams; ++I)
5216 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5217
5218 EPI.Variadic = Record[Idx++];
5219 EPI.HasTrailingReturn = Record[Idx++];
5220 EPI.TypeQuals = Record[Idx++];
5221 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005222 SmallVector<QualType, 8> ExceptionStorage;
5223 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005224 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 }
5226
5227 case TYPE_UNRESOLVED_USING: {
5228 unsigned Idx = 0;
5229 return Context.getTypeDeclType(
5230 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5231 }
5232
5233 case TYPE_TYPEDEF: {
5234 if (Record.size() != 2) {
5235 Error("incorrect encoding of typedef type");
5236 return QualType();
5237 }
5238 unsigned Idx = 0;
5239 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5240 QualType Canonical = readType(*Loc.F, Record, Idx);
5241 if (!Canonical.isNull())
5242 Canonical = Context.getCanonicalType(Canonical);
5243 return Context.getTypedefType(Decl, Canonical);
5244 }
5245
5246 case TYPE_TYPEOF_EXPR:
5247 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5248
5249 case TYPE_TYPEOF: {
5250 if (Record.size() != 1) {
5251 Error("incorrect encoding of typeof(type) in AST file");
5252 return QualType();
5253 }
5254 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5255 return Context.getTypeOfType(UnderlyingType);
5256 }
5257
5258 case TYPE_DECLTYPE: {
5259 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5260 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5261 }
5262
5263 case TYPE_UNARY_TRANSFORM: {
5264 QualType BaseType = readType(*Loc.F, Record, Idx);
5265 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5266 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5267 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5268 }
5269
Richard Smith74aeef52013-04-26 16:15:35 +00005270 case TYPE_AUTO: {
5271 QualType Deduced = readType(*Loc.F, Record, Idx);
5272 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005273 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005274 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005275 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005276
5277 case TYPE_RECORD: {
5278 if (Record.size() != 2) {
5279 Error("incorrect encoding of record type");
5280 return QualType();
5281 }
5282 unsigned Idx = 0;
5283 bool IsDependent = Record[Idx++];
5284 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5285 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5286 QualType T = Context.getRecordType(RD);
5287 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5288 return T;
5289 }
5290
5291 case TYPE_ENUM: {
5292 if (Record.size() != 2) {
5293 Error("incorrect encoding of enum type");
5294 return QualType();
5295 }
5296 unsigned Idx = 0;
5297 bool IsDependent = Record[Idx++];
5298 QualType T
5299 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5300 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5301 return T;
5302 }
5303
5304 case TYPE_ATTRIBUTED: {
5305 if (Record.size() != 3) {
5306 Error("incorrect encoding of attributed type");
5307 return QualType();
5308 }
5309 QualType modifiedType = readType(*Loc.F, Record, Idx);
5310 QualType equivalentType = readType(*Loc.F, Record, Idx);
5311 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5312 return Context.getAttributedType(kind, modifiedType, equivalentType);
5313 }
5314
5315 case TYPE_PAREN: {
5316 if (Record.size() != 1) {
5317 Error("incorrect encoding of paren type");
5318 return QualType();
5319 }
5320 QualType InnerType = readType(*Loc.F, Record, Idx);
5321 return Context.getParenType(InnerType);
5322 }
5323
5324 case TYPE_PACK_EXPANSION: {
5325 if (Record.size() != 2) {
5326 Error("incorrect encoding of pack expansion type");
5327 return QualType();
5328 }
5329 QualType Pattern = readType(*Loc.F, Record, Idx);
5330 if (Pattern.isNull())
5331 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005332 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 if (Record[1])
5334 NumExpansions = Record[1] - 1;
5335 return Context.getPackExpansionType(Pattern, NumExpansions);
5336 }
5337
5338 case TYPE_ELABORATED: {
5339 unsigned Idx = 0;
5340 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5341 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5342 QualType NamedType = readType(*Loc.F, Record, Idx);
5343 return Context.getElaboratedType(Keyword, NNS, NamedType);
5344 }
5345
5346 case TYPE_OBJC_INTERFACE: {
5347 unsigned Idx = 0;
5348 ObjCInterfaceDecl *ItfD
5349 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5350 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5351 }
5352
5353 case TYPE_OBJC_OBJECT: {
5354 unsigned Idx = 0;
5355 QualType Base = readType(*Loc.F, Record, Idx);
5356 unsigned NumProtos = Record[Idx++];
5357 SmallVector<ObjCProtocolDecl*, 4> Protos;
5358 for (unsigned I = 0; I != NumProtos; ++I)
5359 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5360 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5361 }
5362
5363 case TYPE_OBJC_OBJECT_POINTER: {
5364 unsigned Idx = 0;
5365 QualType Pointee = readType(*Loc.F, Record, Idx);
5366 return Context.getObjCObjectPointerType(Pointee);
5367 }
5368
5369 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5370 unsigned Idx = 0;
5371 QualType Parm = readType(*Loc.F, Record, Idx);
5372 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005373 return Context.getSubstTemplateTypeParmType(
5374 cast<TemplateTypeParmType>(Parm),
5375 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005376 }
5377
5378 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5379 unsigned Idx = 0;
5380 QualType Parm = readType(*Loc.F, Record, Idx);
5381 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5382 return Context.getSubstTemplateTypeParmPackType(
5383 cast<TemplateTypeParmType>(Parm),
5384 ArgPack);
5385 }
5386
5387 case TYPE_INJECTED_CLASS_NAME: {
5388 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5389 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5390 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5391 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005392 const Type *T;
5393 if (const Type *Existing = D->getTypeForDecl())
5394 T = Existing;
5395 else if (auto *Prev = D->getPreviousDecl())
5396 T = Prev->getTypeForDecl();
5397 else
5398 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5399 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 }
5401
5402 case TYPE_TEMPLATE_TYPE_PARM: {
5403 unsigned Idx = 0;
5404 unsigned Depth = Record[Idx++];
5405 unsigned Index = Record[Idx++];
5406 bool Pack = Record[Idx++];
5407 TemplateTypeParmDecl *D
5408 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5409 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5410 }
5411
5412 case TYPE_DEPENDENT_NAME: {
5413 unsigned Idx = 0;
5414 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5415 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5416 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5417 QualType Canon = readType(*Loc.F, Record, Idx);
5418 if (!Canon.isNull())
5419 Canon = Context.getCanonicalType(Canon);
5420 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5421 }
5422
5423 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5424 unsigned Idx = 0;
5425 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5426 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5427 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5428 unsigned NumArgs = Record[Idx++];
5429 SmallVector<TemplateArgument, 8> Args;
5430 Args.reserve(NumArgs);
5431 while (NumArgs--)
5432 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5433 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5434 Args.size(), Args.data());
5435 }
5436
5437 case TYPE_DEPENDENT_SIZED_ARRAY: {
5438 unsigned Idx = 0;
5439
5440 // ArrayType
5441 QualType ElementType = readType(*Loc.F, Record, Idx);
5442 ArrayType::ArraySizeModifier ASM
5443 = (ArrayType::ArraySizeModifier)Record[Idx++];
5444 unsigned IndexTypeQuals = Record[Idx++];
5445
5446 // DependentSizedArrayType
5447 Expr *NumElts = ReadExpr(*Loc.F);
5448 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5449
5450 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5451 IndexTypeQuals, Brackets);
5452 }
5453
5454 case TYPE_TEMPLATE_SPECIALIZATION: {
5455 unsigned Idx = 0;
5456 bool IsDependent = Record[Idx++];
5457 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5458 SmallVector<TemplateArgument, 8> Args;
5459 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5460 QualType Underlying = readType(*Loc.F, Record, Idx);
5461 QualType T;
5462 if (Underlying.isNull())
5463 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5464 Args.size());
5465 else
5466 T = Context.getTemplateSpecializationType(Name, Args.data(),
5467 Args.size(), Underlying);
5468 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5469 return T;
5470 }
5471
5472 case TYPE_ATOMIC: {
5473 if (Record.size() != 1) {
5474 Error("Incorrect encoding of atomic type");
5475 return QualType();
5476 }
5477 QualType ValueType = readType(*Loc.F, Record, Idx);
5478 return Context.getAtomicType(ValueType);
5479 }
5480 }
5481 llvm_unreachable("Invalid TypeCode!");
5482}
5483
Richard Smith564417a2014-03-20 21:47:22 +00005484void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5485 SmallVectorImpl<QualType> &Exceptions,
5486 FunctionProtoType::ExtProtoInfo &EPI,
5487 const RecordData &Record, unsigned &Idx) {
5488 ExceptionSpecificationType EST =
5489 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5490 EPI.ExceptionSpecType = EST;
5491 if (EST == EST_Dynamic) {
5492 EPI.NumExceptions = Record[Idx++];
5493 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5494 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5495 EPI.Exceptions = Exceptions.data();
5496 } else if (EST == EST_ComputedNoexcept) {
5497 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5498 } else if (EST == EST_Uninstantiated) {
5499 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5500 EPI.ExceptionSpecTemplate =
5501 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5502 } else if (EST == EST_Unevaluated) {
5503 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5504 }
5505}
5506
Guy Benyei11169dd2012-12-18 14:30:41 +00005507class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5508 ASTReader &Reader;
5509 ModuleFile &F;
5510 const ASTReader::RecordData &Record;
5511 unsigned &Idx;
5512
5513 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5514 unsigned &I) {
5515 return Reader.ReadSourceLocation(F, R, I);
5516 }
5517
5518 template<typename T>
5519 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5520 return Reader.ReadDeclAs<T>(F, Record, Idx);
5521 }
5522
5523public:
5524 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5525 const ASTReader::RecordData &Record, unsigned &Idx)
5526 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5527 { }
5528
5529 // We want compile-time assurance that we've enumerated all of
5530 // these, so unfortunately we have to declare them first, then
5531 // define them out-of-line.
5532#define ABSTRACT_TYPELOC(CLASS, PARENT)
5533#define TYPELOC(CLASS, PARENT) \
5534 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5535#include "clang/AST/TypeLocNodes.def"
5536
5537 void VisitFunctionTypeLoc(FunctionTypeLoc);
5538 void VisitArrayTypeLoc(ArrayTypeLoc);
5539};
5540
5541void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5542 // nothing to do
5543}
5544void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5545 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5546 if (TL.needsExtraLocalData()) {
5547 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5548 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5549 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5550 TL.setModeAttr(Record[Idx++]);
5551 }
5552}
5553void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5554 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5555}
5556void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5557 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5558}
Reid Kleckner8a365022013-06-24 17:51:48 +00005559void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5560 // nothing to do
5561}
Reid Kleckner0503a872013-12-05 01:23:43 +00005562void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5563 // nothing to do
5564}
Guy Benyei11169dd2012-12-18 14:30:41 +00005565void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5566 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5567}
5568void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5569 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5570}
5571void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5572 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5573}
5574void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5575 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5576 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5577}
5578void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5579 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5580 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5581 if (Record[Idx++])
5582 TL.setSizeExpr(Reader.ReadExpr(F));
5583 else
5584 TL.setSizeExpr(0);
5585}
5586void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5587 VisitArrayTypeLoc(TL);
5588}
5589void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5590 VisitArrayTypeLoc(TL);
5591}
5592void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5593 VisitArrayTypeLoc(TL);
5594}
5595void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5596 DependentSizedArrayTypeLoc TL) {
5597 VisitArrayTypeLoc(TL);
5598}
5599void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5600 DependentSizedExtVectorTypeLoc TL) {
5601 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5602}
5603void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5604 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5605}
5606void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5607 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5610 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5611 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5612 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5613 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005614 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5615 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 }
5617}
5618void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5619 VisitFunctionTypeLoc(TL);
5620}
5621void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5622 VisitFunctionTypeLoc(TL);
5623}
5624void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5625 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5631 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5632 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5633 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5636 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5637 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5639 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5640}
5641void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5642 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5643}
5644void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5645 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5646 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5647 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5648 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5649}
5650void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5651 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5652}
5653void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5654 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5655}
5656void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5657 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5658}
5659void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5660 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5661 if (TL.hasAttrOperand()) {
5662 SourceRange range;
5663 range.setBegin(ReadSourceLocation(Record, Idx));
5664 range.setEnd(ReadSourceLocation(Record, Idx));
5665 TL.setAttrOperandParensRange(range);
5666 }
5667 if (TL.hasAttrExprOperand()) {
5668 if (Record[Idx++])
5669 TL.setAttrExprOperand(Reader.ReadExpr(F));
5670 else
5671 TL.setAttrExprOperand(0);
5672 } else if (TL.hasAttrEnumOperand())
5673 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5674}
5675void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5676 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5677}
5678void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5679 SubstTemplateTypeParmTypeLoc TL) {
5680 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5681}
5682void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5683 SubstTemplateTypeParmPackTypeLoc TL) {
5684 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5685}
5686void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5687 TemplateSpecializationTypeLoc TL) {
5688 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5689 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5690 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5691 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5692 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5693 TL.setArgLocInfo(i,
5694 Reader.GetTemplateArgumentLocInfo(F,
5695 TL.getTypePtr()->getArg(i).getKind(),
5696 Record, Idx));
5697}
5698void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5699 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5700 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5703 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5704 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5705}
5706void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5708}
5709void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5710 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5711 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5712 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5713}
5714void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5715 DependentTemplateSpecializationTypeLoc TL) {
5716 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5717 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5718 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5719 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5720 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5721 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5722 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5723 TL.setArgLocInfo(I,
5724 Reader.GetTemplateArgumentLocInfo(F,
5725 TL.getTypePtr()->getArg(I).getKind(),
5726 Record, Idx));
5727}
5728void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5729 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5730}
5731void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5732 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5733}
5734void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5735 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5736 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5737 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5738 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5739 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5740}
5741void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5742 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5743}
5744void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5745 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5746 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5747 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5748}
5749
5750TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5751 const RecordData &Record,
5752 unsigned &Idx) {
5753 QualType InfoTy = readType(F, Record, Idx);
5754 if (InfoTy.isNull())
5755 return 0;
5756
5757 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5758 TypeLocReader TLR(*this, F, Record, Idx);
5759 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5760 TLR.Visit(TL);
5761 return TInfo;
5762}
5763
5764QualType ASTReader::GetType(TypeID ID) {
5765 unsigned FastQuals = ID & Qualifiers::FastMask;
5766 unsigned Index = ID >> Qualifiers::FastWidth;
5767
5768 if (Index < NUM_PREDEF_TYPE_IDS) {
5769 QualType T;
5770 switch ((PredefinedTypeIDs)Index) {
5771 case PREDEF_TYPE_NULL_ID: return QualType();
5772 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5773 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5774
5775 case PREDEF_TYPE_CHAR_U_ID:
5776 case PREDEF_TYPE_CHAR_S_ID:
5777 // FIXME: Check that the signedness of CharTy is correct!
5778 T = Context.CharTy;
5779 break;
5780
5781 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5782 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5783 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5784 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5785 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5786 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5787 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5788 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5789 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5790 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5791 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5792 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5793 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5794 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5795 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5796 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5797 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5798 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5799 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5800 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5801 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5802 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5803 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5804 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5805 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5806 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5807 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5808 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005809 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5810 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5811 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5812 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5813 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5814 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005815 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005816 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5818
5819 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5820 T = Context.getAutoRRefDeductType();
5821 break;
5822
5823 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5824 T = Context.ARCUnbridgedCastTy;
5825 break;
5826
5827 case PREDEF_TYPE_VA_LIST_TAG:
5828 T = Context.getVaListTagType();
5829 break;
5830
5831 case PREDEF_TYPE_BUILTIN_FN:
5832 T = Context.BuiltinFnTy;
5833 break;
5834 }
5835
5836 assert(!T.isNull() && "Unknown predefined type");
5837 return T.withFastQualifiers(FastQuals);
5838 }
5839
5840 Index -= NUM_PREDEF_TYPE_IDS;
5841 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5842 if (TypesLoaded[Index].isNull()) {
5843 TypesLoaded[Index] = readTypeRecord(Index);
5844 if (TypesLoaded[Index].isNull())
5845 return QualType();
5846
5847 TypesLoaded[Index]->setFromAST();
5848 if (DeserializationListener)
5849 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5850 TypesLoaded[Index]);
5851 }
5852
5853 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5854}
5855
5856QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5857 return GetType(getGlobalTypeID(F, LocalID));
5858}
5859
5860serialization::TypeID
5861ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5862 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5863 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5864
5865 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5866 return LocalID;
5867
5868 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5869 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5870 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5871
5872 unsigned GlobalIndex = LocalIndex + I->second;
5873 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5874}
5875
5876TemplateArgumentLocInfo
5877ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5878 TemplateArgument::ArgKind Kind,
5879 const RecordData &Record,
5880 unsigned &Index) {
5881 switch (Kind) {
5882 case TemplateArgument::Expression:
5883 return ReadExpr(F);
5884 case TemplateArgument::Type:
5885 return GetTypeSourceInfo(F, Record, Index);
5886 case TemplateArgument::Template: {
5887 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5888 Index);
5889 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5890 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5891 SourceLocation());
5892 }
5893 case TemplateArgument::TemplateExpansion: {
5894 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5895 Index);
5896 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5897 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5898 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5899 EllipsisLoc);
5900 }
5901 case TemplateArgument::Null:
5902 case TemplateArgument::Integral:
5903 case TemplateArgument::Declaration:
5904 case TemplateArgument::NullPtr:
5905 case TemplateArgument::Pack:
5906 // FIXME: Is this right?
5907 return TemplateArgumentLocInfo();
5908 }
5909 llvm_unreachable("unexpected template argument loc");
5910}
5911
5912TemplateArgumentLoc
5913ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5914 const RecordData &Record, unsigned &Index) {
5915 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5916
5917 if (Arg.getKind() == TemplateArgument::Expression) {
5918 if (Record[Index++]) // bool InfoHasSameExpr.
5919 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5920 }
5921 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5922 Record, Index));
5923}
5924
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005925const ASTTemplateArgumentListInfo*
5926ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5927 const RecordData &Record,
5928 unsigned &Index) {
5929 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5930 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5931 unsigned NumArgsAsWritten = Record[Index++];
5932 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5933 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5934 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5935 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5936}
5937
Guy Benyei11169dd2012-12-18 14:30:41 +00005938Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5939 return GetDecl(ID);
5940}
5941
Richard Smith053f6c62014-05-16 23:01:30 +00005942void ASTReader::CompleteRedeclChain(const Decl *D) {
5943 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5944
5945 // Recursively ensure that the decl context itself is complete
5946 // (in particular, this matters if the decl context is a namespace).
5947 //
5948 // FIXME: This should be performed by lookup instead of here.
5949 cast<Decl>(DC)->getMostRecentDecl();
5950
5951 // If this is a named declaration, complete it by looking it up
5952 // within its context.
5953 //
5954 // FIXME: We don't currently handle the cases where we can't do this;
5955 // merging a class definition that contains unnamed entities should merge
5956 // those entities. Likewise, merging a function definition should merge
5957 // all mergeable entities within it.
5958 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5959 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5960 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5961 auto *II = Name.getAsIdentifierInfo();
5962 if (isa<TranslationUnitDecl>(DC) && II) {
5963 // Outside of C++, we don't have a lookup table for the TU, so update
5964 // the identifier instead. In C++, either way should work fine.
5965 if (II->isOutOfDate())
5966 updateOutOfDateIdentifier(*II);
5967 } else
5968 DC->lookup(Name);
5969 }
5970 }
5971}
5972
Richard Smithcd45dbc2014-04-19 03:48:30 +00005973uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5974 const RecordData &Record,
5975 unsigned &Idx) {
5976 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5977 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005978 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005979 }
5980
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 unsigned LocalID = Record[Idx++];
5982 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5983}
5984
5985CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5986 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005987 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 SavedStreamPosition SavedPosition(Cursor);
5989 Cursor.JumpToBit(Loc.Offset);
5990 ReadingKindTracker ReadingKind(Read_Decl, *this);
5991 RecordData Record;
5992 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005993 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005994 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005995 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00005996 return 0;
5997 }
5998
5999 unsigned Idx = 0;
6000 unsigned NumBases = Record[Idx++];
6001 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6002 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6003 for (unsigned I = 0; I != NumBases; ++I)
6004 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6005 return Bases;
6006}
6007
6008serialization::DeclID
6009ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6010 if (LocalID < NUM_PREDEF_DECL_IDS)
6011 return LocalID;
6012
6013 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6014 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6015 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6016
6017 return LocalID + I->second;
6018}
6019
6020bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6021 ModuleFile &M) const {
6022 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6023 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6024 return &M == I->second;
6025}
6026
Douglas Gregor9f782892013-01-21 15:25:38 +00006027ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 if (!D->isFromASTFile())
6029 return 0;
6030 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6031 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6032 return I->second;
6033}
6034
6035SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6036 if (ID < NUM_PREDEF_DECL_IDS)
6037 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6040
6041 if (Index > DeclsLoaded.size()) {
6042 Error("declaration ID out-of-range for AST file");
6043 return SourceLocation();
6044 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006045
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 if (Decl *D = DeclsLoaded[Index])
6047 return D->getLocation();
6048
6049 unsigned RawLocation = 0;
6050 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6051 return ReadSourceLocation(*Rec.F, RawLocation);
6052}
6053
Richard Smithcd45dbc2014-04-19 03:48:30 +00006054Decl *ASTReader::GetExistingDecl(DeclID ID) {
6055 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 switch ((PredefinedDeclIDs)ID) {
6057 case PREDEF_DECL_NULL_ID:
6058 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006059
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6061 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006062
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 case PREDEF_DECL_OBJC_ID_ID:
6064 return Context.getObjCIdDecl();
6065
6066 case PREDEF_DECL_OBJC_SEL_ID:
6067 return Context.getObjCSelDecl();
6068
6069 case PREDEF_DECL_OBJC_CLASS_ID:
6070 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006071
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6073 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006074
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 case PREDEF_DECL_INT_128_ID:
6076 return Context.getInt128Decl();
6077
6078 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6079 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006080
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6082 return Context.getObjCInstanceTypeDecl();
6083
6084 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6085 return Context.getBuiltinVaListDecl();
6086 }
6087 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6090
6091 if (Index >= DeclsLoaded.size()) {
6092 assert(0 && "declaration ID out-of-range for AST file");
6093 Error("declaration ID out-of-range for AST file");
6094 return 0;
6095 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006096
6097 return DeclsLoaded[Index];
6098}
6099
6100Decl *ASTReader::GetDecl(DeclID ID) {
6101 if (ID < NUM_PREDEF_DECL_IDS)
6102 return GetExistingDecl(ID);
6103
6104 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6105
6106 if (Index >= DeclsLoaded.size()) {
6107 assert(0 && "declaration ID out-of-range for AST file");
6108 Error("declaration ID out-of-range for AST file");
6109 return 0;
6110 }
6111
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 if (!DeclsLoaded[Index]) {
6113 ReadDeclRecord(ID);
6114 if (DeserializationListener)
6115 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6116 }
6117
6118 return DeclsLoaded[Index];
6119}
6120
6121DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6122 DeclID GlobalID) {
6123 if (GlobalID < NUM_PREDEF_DECL_IDS)
6124 return GlobalID;
6125
6126 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6127 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6128 ModuleFile *Owner = I->second;
6129
6130 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6131 = M.GlobalToLocalDeclIDs.find(Owner);
6132 if (Pos == M.GlobalToLocalDeclIDs.end())
6133 return 0;
6134
6135 return GlobalID - Owner->BaseDeclID + Pos->second;
6136}
6137
6138serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6139 const RecordData &Record,
6140 unsigned &Idx) {
6141 if (Idx >= Record.size()) {
6142 Error("Corrupted AST file");
6143 return 0;
6144 }
6145
6146 return getGlobalDeclID(F, Record[Idx++]);
6147}
6148
6149/// \brief Resolve the offset of a statement into a statement.
6150///
6151/// This operation will read a new statement from the external
6152/// source each time it is called, and is meant to be used via a
6153/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6154Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6155 // Switch case IDs are per Decl.
6156 ClearSwitchCaseIDs();
6157
6158 // Offset here is a global offset across the entire chain.
6159 RecordLocation Loc = getLocalBitOffset(Offset);
6160 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6161 return ReadStmtFromStream(*Loc.F);
6162}
6163
6164namespace {
6165 class FindExternalLexicalDeclsVisitor {
6166 ASTReader &Reader;
6167 const DeclContext *DC;
6168 bool (*isKindWeWant)(Decl::Kind);
6169
6170 SmallVectorImpl<Decl*> &Decls;
6171 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6172
6173 public:
6174 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6175 bool (*isKindWeWant)(Decl::Kind),
6176 SmallVectorImpl<Decl*> &Decls)
6177 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6178 {
6179 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6180 PredefsVisited[I] = false;
6181 }
6182
6183 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6184 if (Preorder)
6185 return false;
6186
6187 FindExternalLexicalDeclsVisitor *This
6188 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6189
6190 ModuleFile::DeclContextInfosMap::iterator Info
6191 = M.DeclContextInfos.find(This->DC);
6192 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6193 return false;
6194
6195 // Load all of the declaration IDs
6196 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6197 *IDE = ID + Info->second.NumLexicalDecls;
6198 ID != IDE; ++ID) {
6199 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6200 continue;
6201
6202 // Don't add predefined declarations to the lexical context more
6203 // than once.
6204 if (ID->second < NUM_PREDEF_DECL_IDS) {
6205 if (This->PredefsVisited[ID->second])
6206 continue;
6207
6208 This->PredefsVisited[ID->second] = true;
6209 }
6210
6211 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6212 if (!This->DC->isDeclInLexicalTraversal(D))
6213 This->Decls.push_back(D);
6214 }
6215 }
6216
6217 return false;
6218 }
6219 };
6220}
6221
6222ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6223 bool (*isKindWeWant)(Decl::Kind),
6224 SmallVectorImpl<Decl*> &Decls) {
6225 // There might be lexical decls in multiple modules, for the TU at
6226 // least. Walk all of the modules in the order they were loaded.
6227 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6228 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6229 ++NumLexicalDeclContextsRead;
6230 return ELR_Success;
6231}
6232
6233namespace {
6234
6235class DeclIDComp {
6236 ASTReader &Reader;
6237 ModuleFile &Mod;
6238
6239public:
6240 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6241
6242 bool operator()(LocalDeclID L, LocalDeclID R) const {
6243 SourceLocation LHS = getLocation(L);
6244 SourceLocation RHS = getLocation(R);
6245 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6246 }
6247
6248 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6249 SourceLocation RHS = getLocation(R);
6250 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6251 }
6252
6253 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6254 SourceLocation LHS = getLocation(L);
6255 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6256 }
6257
6258 SourceLocation getLocation(LocalDeclID ID) const {
6259 return Reader.getSourceManager().getFileLoc(
6260 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6261 }
6262};
6263
6264}
6265
6266void ASTReader::FindFileRegionDecls(FileID File,
6267 unsigned Offset, unsigned Length,
6268 SmallVectorImpl<Decl *> &Decls) {
6269 SourceManager &SM = getSourceManager();
6270
6271 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6272 if (I == FileDeclIDs.end())
6273 return;
6274
6275 FileDeclsInfo &DInfo = I->second;
6276 if (DInfo.Decls.empty())
6277 return;
6278
6279 SourceLocation
6280 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6281 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6282
6283 DeclIDComp DIDComp(*this, *DInfo.Mod);
6284 ArrayRef<serialization::LocalDeclID>::iterator
6285 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6286 BeginLoc, DIDComp);
6287 if (BeginIt != DInfo.Decls.begin())
6288 --BeginIt;
6289
6290 // If we are pointing at a top-level decl inside an objc container, we need
6291 // to backtrack until we find it otherwise we will fail to report that the
6292 // region overlaps with an objc container.
6293 while (BeginIt != DInfo.Decls.begin() &&
6294 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6295 ->isTopLevelDeclInObjCContainer())
6296 --BeginIt;
6297
6298 ArrayRef<serialization::LocalDeclID>::iterator
6299 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6300 EndLoc, DIDComp);
6301 if (EndIt != DInfo.Decls.end())
6302 ++EndIt;
6303
6304 for (ArrayRef<serialization::LocalDeclID>::iterator
6305 DIt = BeginIt; DIt != EndIt; ++DIt)
6306 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6307}
6308
6309namespace {
6310 /// \brief ModuleFile visitor used to perform name lookup into a
6311 /// declaration context.
6312 class DeclContextNameLookupVisitor {
6313 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006314 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 DeclarationName Name;
6316 SmallVectorImpl<NamedDecl *> &Decls;
6317
6318 public:
6319 DeclContextNameLookupVisitor(ASTReader &Reader,
6320 SmallVectorImpl<const DeclContext *> &Contexts,
6321 DeclarationName Name,
6322 SmallVectorImpl<NamedDecl *> &Decls)
6323 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6324
6325 static bool visit(ModuleFile &M, void *UserData) {
6326 DeclContextNameLookupVisitor *This
6327 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6328
6329 // Check whether we have any visible declaration information for
6330 // this context in this module.
6331 ModuleFile::DeclContextInfosMap::iterator Info;
6332 bool FoundInfo = false;
6333 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6334 Info = M.DeclContextInfos.find(This->Contexts[I]);
6335 if (Info != M.DeclContextInfos.end() &&
6336 Info->second.NameLookupTableData) {
6337 FoundInfo = true;
6338 break;
6339 }
6340 }
6341
6342 if (!FoundInfo)
6343 return false;
6344
6345 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006346 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 Info->second.NameLookupTableData;
6348 ASTDeclContextNameLookupTable::iterator Pos
6349 = LookupTable->find(This->Name);
6350 if (Pos == LookupTable->end())
6351 return false;
6352
6353 bool FoundAnything = false;
6354 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6355 for (; Data.first != Data.second; ++Data.first) {
6356 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6357 if (!ND)
6358 continue;
6359
6360 if (ND->getDeclName() != This->Name) {
6361 // A name might be null because the decl's redeclarable part is
6362 // currently read before reading its name. The lookup is triggered by
6363 // building that decl (likely indirectly), and so it is later in the
6364 // sense of "already existing" and can be ignored here.
6365 continue;
6366 }
6367
6368 // Record this declaration.
6369 FoundAnything = true;
6370 This->Decls.push_back(ND);
6371 }
6372
6373 return FoundAnything;
6374 }
6375 };
6376}
6377
Douglas Gregor9f782892013-01-21 15:25:38 +00006378/// \brief Retrieve the "definitive" module file for the definition of the
6379/// given declaration context, if there is one.
6380///
6381/// The "definitive" module file is the only place where we need to look to
6382/// find information about the declarations within the given declaration
6383/// context. For example, C++ and Objective-C classes, C structs/unions, and
6384/// Objective-C protocols, categories, and extensions are all defined in a
6385/// single place in the source code, so they have definitive module files
6386/// associated with them. C++ namespaces, on the other hand, can have
6387/// definitions in multiple different module files.
6388///
6389/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6390/// NDEBUG checking.
6391static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6392 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006393 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6394 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006395
6396 return 0;
6397}
6398
Richard Smith9ce12e32013-02-07 03:30:24 +00006399bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006400ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6401 DeclarationName Name) {
6402 assert(DC->hasExternalVisibleStorage() &&
6403 "DeclContext has no visible decls in storage");
6404 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006405 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006406
6407 SmallVector<NamedDecl *, 64> Decls;
6408
6409 // Compute the declaration contexts we need to look into. Multiple such
6410 // declaration contexts occur when two declaration contexts from disjoint
6411 // modules get merged, e.g., when two namespaces with the same name are
6412 // independently defined in separate modules.
6413 SmallVector<const DeclContext *, 2> Contexts;
6414 Contexts.push_back(DC);
6415
6416 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006417 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 if (Merged != MergedDecls.end()) {
6419 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6420 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6421 }
6422 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006423 if (isa<CXXRecordDecl>(DC)) {
6424 auto Merged = MergedLookups.find(DC);
6425 if (Merged != MergedLookups.end())
6426 Contexts.insert(Contexts.end(), Merged->second.begin(),
6427 Merged->second.end());
6428 }
6429
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006431
6432 // If we can definitively determine which module file to look into,
6433 // only look there. Otherwise, look in all module files.
6434 ModuleFile *Definitive;
6435 if (Contexts.size() == 1 &&
6436 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6437 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6438 } else {
6439 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 ++NumVisibleDeclContextsRead;
6442 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006443 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006444}
6445
6446namespace {
6447 /// \brief ModuleFile visitor used to retrieve all visible names in a
6448 /// declaration context.
6449 class DeclContextAllNamesVisitor {
6450 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006451 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006452 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006453 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006454
6455 public:
6456 DeclContextAllNamesVisitor(ASTReader &Reader,
6457 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006458 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006459 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006460
6461 static bool visit(ModuleFile &M, void *UserData) {
6462 DeclContextAllNamesVisitor *This
6463 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6464
6465 // Check whether we have any visible declaration information for
6466 // this context in this module.
6467 ModuleFile::DeclContextInfosMap::iterator Info;
6468 bool FoundInfo = false;
6469 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6470 Info = M.DeclContextInfos.find(This->Contexts[I]);
6471 if (Info != M.DeclContextInfos.end() &&
6472 Info->second.NameLookupTableData) {
6473 FoundInfo = true;
6474 break;
6475 }
6476 }
6477
6478 if (!FoundInfo)
6479 return false;
6480
Richard Smith52e3fba2014-03-11 07:17:35 +00006481 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 Info->second.NameLookupTableData;
6483 bool FoundAnything = false;
6484 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006485 I = LookupTable->data_begin(), E = LookupTable->data_end();
6486 I != E;
6487 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006488 ASTDeclContextNameLookupTrait::data_type Data = *I;
6489 for (; Data.first != Data.second; ++Data.first) {
6490 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6491 *Data.first);
6492 if (!ND)
6493 continue;
6494
6495 // Record this declaration.
6496 FoundAnything = true;
6497 This->Decls[ND->getDeclName()].push_back(ND);
6498 }
6499 }
6500
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006501 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 }
6503 };
6504}
6505
6506void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6507 if (!DC->hasExternalVisibleStorage())
6508 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006509 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006510
6511 // Compute the declaration contexts we need to look into. Multiple such
6512 // declaration contexts occur when two declaration contexts from disjoint
6513 // modules get merged, e.g., when two namespaces with the same name are
6514 // independently defined in separate modules.
6515 SmallVector<const DeclContext *, 2> Contexts;
6516 Contexts.push_back(DC);
6517
6518 if (DC->isNamespace()) {
6519 MergedDeclsMap::iterator Merged
6520 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6521 if (Merged != MergedDecls.end()) {
6522 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6523 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6524 }
6525 }
6526
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006527 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6528 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6530 ++NumVisibleDeclContextsRead;
6531
Craig Topper79be4cd2013-07-05 04:33:53 +00006532 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006533 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6534 }
6535 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6536}
6537
6538/// \brief Under non-PCH compilation the consumer receives the objc methods
6539/// before receiving the implementation, and codegen depends on this.
6540/// We simulate this by deserializing and passing to consumer the methods of the
6541/// implementation before passing the deserialized implementation decl.
6542static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6543 ASTConsumer *Consumer) {
6544 assert(ImplD && Consumer);
6545
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006546 for (auto *I : ImplD->methods())
6547 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006548
6549 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6550}
6551
6552void ASTReader::PassInterestingDeclsToConsumer() {
6553 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006554
6555 if (PassingDeclsToConsumer)
6556 return;
6557
6558 // Guard variable to avoid recursively redoing the process of passing
6559 // decls to consumer.
6560 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6561 true);
6562
Guy Benyei11169dd2012-12-18 14:30:41 +00006563 while (!InterestingDecls.empty()) {
6564 Decl *D = InterestingDecls.front();
6565 InterestingDecls.pop_front();
6566
6567 PassInterestingDeclToConsumer(D);
6568 }
6569}
6570
6571void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6572 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6573 PassObjCImplDeclToConsumer(ImplD, Consumer);
6574 else
6575 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6576}
6577
6578void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6579 this->Consumer = Consumer;
6580
6581 if (!Consumer)
6582 return;
6583
Ben Langmuir332aafe2014-01-31 01:06:56 +00006584 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 // Force deserialization of this decl, which will cause it to be queued for
6586 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006587 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006589 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006590
6591 PassInterestingDeclsToConsumer();
6592}
6593
6594void ASTReader::PrintStats() {
6595 std::fprintf(stderr, "*** AST File Statistics:\n");
6596
6597 unsigned NumTypesLoaded
6598 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6599 QualType());
6600 unsigned NumDeclsLoaded
6601 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6602 (Decl *)0);
6603 unsigned NumIdentifiersLoaded
6604 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6605 IdentifiersLoaded.end(),
6606 (IdentifierInfo *)0);
6607 unsigned NumMacrosLoaded
6608 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6609 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006610 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006611 unsigned NumSelectorsLoaded
6612 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6613 SelectorsLoaded.end(),
6614 Selector());
6615
6616 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6617 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6618 NumSLocEntriesRead, TotalNumSLocEntries,
6619 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6620 if (!TypesLoaded.empty())
6621 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6622 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6623 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6624 if (!DeclsLoaded.empty())
6625 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6626 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6627 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6628 if (!IdentifiersLoaded.empty())
6629 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6630 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6631 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6632 if (!MacrosLoaded.empty())
6633 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6634 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6635 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6636 if (!SelectorsLoaded.empty())
6637 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6638 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6639 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6640 if (TotalNumStatements)
6641 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6642 NumStatementsRead, TotalNumStatements,
6643 ((float)NumStatementsRead/TotalNumStatements * 100));
6644 if (TotalNumMacros)
6645 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6646 NumMacrosRead, TotalNumMacros,
6647 ((float)NumMacrosRead/TotalNumMacros * 100));
6648 if (TotalLexicalDeclContexts)
6649 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6650 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6651 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6652 * 100));
6653 if (TotalVisibleDeclContexts)
6654 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6655 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6656 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6657 * 100));
6658 if (TotalNumMethodPoolEntries) {
6659 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6660 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6661 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6662 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006664 if (NumMethodPoolLookups) {
6665 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6666 NumMethodPoolHits, NumMethodPoolLookups,
6667 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6668 }
6669 if (NumMethodPoolTableLookups) {
6670 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6671 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6672 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6673 * 100.0));
6674 }
6675
Douglas Gregor00a50f72013-01-25 00:38:33 +00006676 if (NumIdentifierLookupHits) {
6677 std::fprintf(stderr,
6678 " %u / %u identifier table lookups succeeded (%f%%)\n",
6679 NumIdentifierLookupHits, NumIdentifierLookups,
6680 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6681 }
6682
Douglas Gregore060e572013-01-25 01:03:03 +00006683 if (GlobalIndex) {
6684 std::fprintf(stderr, "\n");
6685 GlobalIndex->printStats();
6686 }
6687
Guy Benyei11169dd2012-12-18 14:30:41 +00006688 std::fprintf(stderr, "\n");
6689 dump();
6690 std::fprintf(stderr, "\n");
6691}
6692
6693template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6694static void
6695dumpModuleIDMap(StringRef Name,
6696 const ContinuousRangeMap<Key, ModuleFile *,
6697 InitialCapacity> &Map) {
6698 if (Map.begin() == Map.end())
6699 return;
6700
6701 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6702 llvm::errs() << Name << ":\n";
6703 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6704 I != IEnd; ++I) {
6705 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6706 << "\n";
6707 }
6708}
6709
6710void ASTReader::dump() {
6711 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6712 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6713 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6714 dumpModuleIDMap("Global type map", GlobalTypeMap);
6715 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6716 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6717 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6718 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6719 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6720 dumpModuleIDMap("Global preprocessed entity map",
6721 GlobalPreprocessedEntityMap);
6722
6723 llvm::errs() << "\n*** PCH/Modules Loaded:";
6724 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6725 MEnd = ModuleMgr.end();
6726 M != MEnd; ++M)
6727 (*M)->dump();
6728}
6729
6730/// Return the amount of memory used by memory buffers, breaking down
6731/// by heap-backed versus mmap'ed memory.
6732void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6733 for (ModuleConstIterator I = ModuleMgr.begin(),
6734 E = ModuleMgr.end(); I != E; ++I) {
6735 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6736 size_t bytes = buf->getBufferSize();
6737 switch (buf->getBufferKind()) {
6738 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6739 sizes.malloc_bytes += bytes;
6740 break;
6741 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6742 sizes.mmap_bytes += bytes;
6743 break;
6744 }
6745 }
6746 }
6747}
6748
6749void ASTReader::InitializeSema(Sema &S) {
6750 SemaObj = &S;
6751 S.addExternalSource(this);
6752
6753 // Makes sure any declarations that were deserialized "too early"
6754 // still get added to the identifier's declaration chains.
6755 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006756 pushExternalDeclIntoScope(PreloadedDecls[I],
6757 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006758 }
6759 PreloadedDecls.clear();
6760
Richard Smith3d8e97e2013-10-18 06:54:39 +00006761 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 if (!FPPragmaOptions.empty()) {
6763 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6764 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6765 }
6766
Richard Smith3d8e97e2013-10-18 06:54:39 +00006767 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 if (!OpenCLExtensions.empty()) {
6769 unsigned I = 0;
6770#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6771#include "clang/Basic/OpenCLExtensions.def"
6772
6773 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6774 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006775
6776 UpdateSema();
6777}
6778
6779void ASTReader::UpdateSema() {
6780 assert(SemaObj && "no Sema to update");
6781
6782 // Load the offsets of the declarations that Sema references.
6783 // They will be lazily deserialized when needed.
6784 if (!SemaDeclRefs.empty()) {
6785 assert(SemaDeclRefs.size() % 2 == 0);
6786 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6787 if (!SemaObj->StdNamespace)
6788 SemaObj->StdNamespace = SemaDeclRefs[I];
6789 if (!SemaObj->StdBadAlloc)
6790 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6791 }
6792 SemaDeclRefs.clear();
6793 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006794}
6795
6796IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6797 // Note that we are loading an identifier.
6798 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006799 StringRef Name(NameStart, NameEnd - NameStart);
6800
6801 // If there is a global index, look there first to determine which modules
6802 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006803 GlobalModuleIndex::HitSet Hits;
6804 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006805 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006806 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6807 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006808 }
6809 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006810 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006811 NumIdentifierLookups,
6812 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006813 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 IdentifierInfo *II = Visitor.getIdentifierInfo();
6815 markIdentifierUpToDate(II);
6816 return II;
6817}
6818
6819namespace clang {
6820 /// \brief An identifier-lookup iterator that enumerates all of the
6821 /// identifiers stored within a set of AST files.
6822 class ASTIdentifierIterator : public IdentifierIterator {
6823 /// \brief The AST reader whose identifiers are being enumerated.
6824 const ASTReader &Reader;
6825
6826 /// \brief The current index into the chain of AST files stored in
6827 /// the AST reader.
6828 unsigned Index;
6829
6830 /// \brief The current position within the identifier lookup table
6831 /// of the current AST file.
6832 ASTIdentifierLookupTable::key_iterator Current;
6833
6834 /// \brief The end position within the identifier lookup table of
6835 /// the current AST file.
6836 ASTIdentifierLookupTable::key_iterator End;
6837
6838 public:
6839 explicit ASTIdentifierIterator(const ASTReader &Reader);
6840
Craig Topper3e89dfe2014-03-13 02:13:41 +00006841 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 };
6843}
6844
6845ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6846 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6847 ASTIdentifierLookupTable *IdTable
6848 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6849 Current = IdTable->key_begin();
6850 End = IdTable->key_end();
6851}
6852
6853StringRef ASTIdentifierIterator::Next() {
6854 while (Current == End) {
6855 // If we have exhausted all of our AST files, we're done.
6856 if (Index == 0)
6857 return StringRef();
6858
6859 --Index;
6860 ASTIdentifierLookupTable *IdTable
6861 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6862 IdentifierLookupTable;
6863 Current = IdTable->key_begin();
6864 End = IdTable->key_end();
6865 }
6866
6867 // We have any identifiers remaining in the current AST file; return
6868 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006869 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006871 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006872}
6873
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006874IdentifierIterator *ASTReader::getIdentifiers() {
6875 if (!loadGlobalIndex())
6876 return GlobalIndex->createIdentifierIterator();
6877
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 return new ASTIdentifierIterator(*this);
6879}
6880
6881namespace clang { namespace serialization {
6882 class ReadMethodPoolVisitor {
6883 ASTReader &Reader;
6884 Selector Sel;
6885 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006886 unsigned InstanceBits;
6887 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006888 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6889 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
6891 public:
6892 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6893 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006894 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6895 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006896
6897 static bool visit(ModuleFile &M, void *UserData) {
6898 ReadMethodPoolVisitor *This
6899 = static_cast<ReadMethodPoolVisitor *>(UserData);
6900
6901 if (!M.SelectorLookupTable)
6902 return false;
6903
6904 // If we've already searched this module file, skip it now.
6905 if (M.Generation <= This->PriorGeneration)
6906 return true;
6907
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006908 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 ASTSelectorLookupTable *PoolTable
6910 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6911 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6912 if (Pos == PoolTable->end())
6913 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006914
6915 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 ++This->Reader.NumSelectorsRead;
6917 // FIXME: Not quite happy with the statistics here. We probably should
6918 // disable this tracking when called via LoadSelector.
6919 // Also, should entries without methods count as misses?
6920 ++This->Reader.NumMethodPoolEntriesRead;
6921 ASTSelectorLookupTrait::data_type Data = *Pos;
6922 if (This->Reader.DeserializationListener)
6923 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6924 This->Sel);
6925
6926 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6927 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006928 This->InstanceBits = Data.InstanceBits;
6929 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 return true;
6931 }
6932
6933 /// \brief Retrieve the instance methods found by this visitor.
6934 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6935 return InstanceMethods;
6936 }
6937
6938 /// \brief Retrieve the instance methods found by this visitor.
6939 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6940 return FactoryMethods;
6941 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006942
6943 unsigned getInstanceBits() const { return InstanceBits; }
6944 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 };
6946} } // end namespace clang::serialization
6947
6948/// \brief Add the given set of methods to the method list.
6949static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6950 ObjCMethodList &List) {
6951 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6952 S.addMethodToGlobalList(&List, Methods[I]);
6953 }
6954}
6955
6956void ASTReader::ReadMethodPool(Selector Sel) {
6957 // Get the selector generation and update it to the current generation.
6958 unsigned &Generation = SelectorGeneration[Sel];
6959 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006960 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006961
6962 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006963 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6965 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6966
6967 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006968 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006970
6971 ++NumMethodPoolHits;
6972
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 if (!getSema())
6974 return;
6975
6976 Sema &S = *getSema();
6977 Sema::GlobalMethodPool::iterator Pos
6978 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6979
6980 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6981 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006982 Pos->second.first.setBits(Visitor.getInstanceBits());
6983 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006984}
6985
6986void ASTReader::ReadKnownNamespaces(
6987 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6988 Namespaces.clear();
6989
6990 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6991 if (NamespaceDecl *Namespace
6992 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6993 Namespaces.push_back(Namespace);
6994 }
6995}
6996
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006997void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006998 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006999 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7000 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007001 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007002 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007003 Undefined.insert(std::make_pair(D, Loc));
7004 }
7005}
Nick Lewycky8334af82013-01-26 00:35:08 +00007006
Guy Benyei11169dd2012-12-18 14:30:41 +00007007void ASTReader::ReadTentativeDefinitions(
7008 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7009 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7010 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7011 if (Var)
7012 TentativeDefs.push_back(Var);
7013 }
7014 TentativeDefinitions.clear();
7015}
7016
7017void ASTReader::ReadUnusedFileScopedDecls(
7018 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7019 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7020 DeclaratorDecl *D
7021 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7022 if (D)
7023 Decls.push_back(D);
7024 }
7025 UnusedFileScopedDecls.clear();
7026}
7027
7028void ASTReader::ReadDelegatingConstructors(
7029 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7030 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7031 CXXConstructorDecl *D
7032 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7033 if (D)
7034 Decls.push_back(D);
7035 }
7036 DelegatingCtorDecls.clear();
7037}
7038
7039void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7040 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7041 TypedefNameDecl *D
7042 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7043 if (D)
7044 Decls.push_back(D);
7045 }
7046 ExtVectorDecls.clear();
7047}
7048
7049void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7050 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7051 CXXRecordDecl *D
7052 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7053 if (D)
7054 Decls.push_back(D);
7055 }
7056 DynamicClasses.clear();
7057}
7058
7059void
Richard Smith78165b52013-01-10 23:43:47 +00007060ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7061 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7062 NamedDecl *D
7063 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 if (D)
7065 Decls.push_back(D);
7066 }
Richard Smith78165b52013-01-10 23:43:47 +00007067 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007068}
7069
7070void ASTReader::ReadReferencedSelectors(
7071 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7072 if (ReferencedSelectorsData.empty())
7073 return;
7074
7075 // If there are @selector references added them to its pool. This is for
7076 // implementation of -Wselector.
7077 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7078 unsigned I = 0;
7079 while (I < DataSize) {
7080 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7081 SourceLocation SelLoc
7082 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7083 Sels.push_back(std::make_pair(Sel, SelLoc));
7084 }
7085 ReferencedSelectorsData.clear();
7086}
7087
7088void ASTReader::ReadWeakUndeclaredIdentifiers(
7089 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7090 if (WeakUndeclaredIdentifiers.empty())
7091 return;
7092
7093 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7094 IdentifierInfo *WeakId
7095 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7096 IdentifierInfo *AliasId
7097 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7098 SourceLocation Loc
7099 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7100 bool Used = WeakUndeclaredIdentifiers[I++];
7101 WeakInfo WI(AliasId, Loc);
7102 WI.setUsed(Used);
7103 WeakIDs.push_back(std::make_pair(WeakId, WI));
7104 }
7105 WeakUndeclaredIdentifiers.clear();
7106}
7107
7108void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7109 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7110 ExternalVTableUse VT;
7111 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7112 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7113 VT.DefinitionRequired = VTableUses[Idx++];
7114 VTables.push_back(VT);
7115 }
7116
7117 VTableUses.clear();
7118}
7119
7120void ASTReader::ReadPendingInstantiations(
7121 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7122 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7123 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7124 SourceLocation Loc
7125 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7126
7127 Pending.push_back(std::make_pair(D, Loc));
7128 }
7129 PendingInstantiations.clear();
7130}
7131
Richard Smithe40f2ba2013-08-07 21:41:30 +00007132void ASTReader::ReadLateParsedTemplates(
7133 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7134 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7135 /* In loop */) {
7136 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7137
7138 LateParsedTemplate *LT = new LateParsedTemplate;
7139 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7140
7141 ModuleFile *F = getOwningModuleFile(LT->D);
7142 assert(F && "No module");
7143
7144 unsigned TokN = LateParsedTemplates[Idx++];
7145 LT->Toks.reserve(TokN);
7146 for (unsigned T = 0; T < TokN; ++T)
7147 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7148
7149 LPTMap[FD] = LT;
7150 }
7151
7152 LateParsedTemplates.clear();
7153}
7154
Guy Benyei11169dd2012-12-18 14:30:41 +00007155void ASTReader::LoadSelector(Selector Sel) {
7156 // It would be complicated to avoid reading the methods anyway. So don't.
7157 ReadMethodPool(Sel);
7158}
7159
7160void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7161 assert(ID && "Non-zero identifier ID required");
7162 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7163 IdentifiersLoaded[ID - 1] = II;
7164 if (DeserializationListener)
7165 DeserializationListener->IdentifierRead(ID, II);
7166}
7167
7168/// \brief Set the globally-visible declarations associated with the given
7169/// identifier.
7170///
7171/// If the AST reader is currently in a state where the given declaration IDs
7172/// cannot safely be resolved, they are queued until it is safe to resolve
7173/// them.
7174///
7175/// \param II an IdentifierInfo that refers to one or more globally-visible
7176/// declarations.
7177///
7178/// \param DeclIDs the set of declaration IDs with the name @p II that are
7179/// visible at global scope.
7180///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007181/// \param Decls if non-null, this vector will be populated with the set of
7182/// deserialized declarations. These declarations will not be pushed into
7183/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007184void
7185ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7186 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007187 SmallVectorImpl<Decl *> *Decls) {
7188 if (NumCurrentElementsDeserializing && !Decls) {
7189 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007190 return;
7191 }
7192
7193 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7194 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7195 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007196 // If we're simply supposed to record the declarations, do so now.
7197 if (Decls) {
7198 Decls->push_back(D);
7199 continue;
7200 }
7201
Guy Benyei11169dd2012-12-18 14:30:41 +00007202 // Introduce this declaration into the translation-unit scope
7203 // and add it to the declaration chain for this identifier, so
7204 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007205 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007206 } else {
7207 // Queue this declaration so that it will be added to the
7208 // translation unit scope and identifier's declaration chain
7209 // once a Sema object is known.
7210 PreloadedDecls.push_back(D);
7211 }
7212 }
7213}
7214
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007215IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 if (ID == 0)
7217 return 0;
7218
7219 if (IdentifiersLoaded.empty()) {
7220 Error("no identifier table in AST file");
7221 return 0;
7222 }
7223
7224 ID -= 1;
7225 if (!IdentifiersLoaded[ID]) {
7226 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7227 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7228 ModuleFile *M = I->second;
7229 unsigned Index = ID - M->BaseIdentifierID;
7230 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7231
7232 // All of the strings in the AST file are preceded by a 16-bit length.
7233 // Extract that 16-bit length to avoid having to execute strlen().
7234 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7235 // unsigned integers. This is important to avoid integer overflow when
7236 // we cast them to 'unsigned'.
7237 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7238 unsigned StrLen = (((unsigned) StrLenPtr[0])
7239 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007240 IdentifiersLoaded[ID]
7241 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 if (DeserializationListener)
7243 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7244 }
7245
7246 return IdentifiersLoaded[ID];
7247}
7248
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007249IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7250 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007251}
7252
7253IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7254 if (LocalID < NUM_PREDEF_IDENT_IDS)
7255 return LocalID;
7256
7257 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7258 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7259 assert(I != M.IdentifierRemap.end()
7260 && "Invalid index into identifier index remap");
7261
7262 return LocalID + I->second;
7263}
7264
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007265MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 if (ID == 0)
7267 return 0;
7268
7269 if (MacrosLoaded.empty()) {
7270 Error("no macro table in AST file");
7271 return 0;
7272 }
7273
7274 ID -= NUM_PREDEF_MACRO_IDS;
7275 if (!MacrosLoaded[ID]) {
7276 GlobalMacroMapType::iterator I
7277 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7278 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7279 ModuleFile *M = I->second;
7280 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007281 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7282
7283 if (DeserializationListener)
7284 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7285 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007286 }
7287
7288 return MacrosLoaded[ID];
7289}
7290
7291MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7292 if (LocalID < NUM_PREDEF_MACRO_IDS)
7293 return LocalID;
7294
7295 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7296 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7297 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7298
7299 return LocalID + I->second;
7300}
7301
7302serialization::SubmoduleID
7303ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7304 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7305 return LocalID;
7306
7307 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7308 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7309 assert(I != M.SubmoduleRemap.end()
7310 && "Invalid index into submodule index remap");
7311
7312 return LocalID + I->second;
7313}
7314
7315Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7316 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7317 assert(GlobalID == 0 && "Unhandled global submodule ID");
7318 return 0;
7319 }
7320
7321 if (GlobalID > SubmodulesLoaded.size()) {
7322 Error("submodule ID out of range in AST file");
7323 return 0;
7324 }
7325
7326 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7327}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007328
7329Module *ASTReader::getModule(unsigned ID) {
7330 return getSubmodule(ID);
7331}
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7334 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7335}
7336
7337Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7338 if (ID == 0)
7339 return Selector();
7340
7341 if (ID > SelectorsLoaded.size()) {
7342 Error("selector ID out of range in AST file");
7343 return Selector();
7344 }
7345
7346 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7347 // Load this selector from the selector table.
7348 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7349 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7350 ModuleFile &M = *I->second;
7351 ASTSelectorLookupTrait Trait(*this, M);
7352 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7353 SelectorsLoaded[ID - 1] =
7354 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7355 if (DeserializationListener)
7356 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7357 }
7358
7359 return SelectorsLoaded[ID - 1];
7360}
7361
7362Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7363 return DecodeSelector(ID);
7364}
7365
7366uint32_t ASTReader::GetNumExternalSelectors() {
7367 // ID 0 (the null selector) is considered an external selector.
7368 return getTotalNumSelectors() + 1;
7369}
7370
7371serialization::SelectorID
7372ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7373 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7374 return LocalID;
7375
7376 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7377 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7378 assert(I != M.SelectorRemap.end()
7379 && "Invalid index into selector index remap");
7380
7381 return LocalID + I->second;
7382}
7383
7384DeclarationName
7385ASTReader::ReadDeclarationName(ModuleFile &F,
7386 const RecordData &Record, unsigned &Idx) {
7387 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7388 switch (Kind) {
7389 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007390 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007391
7392 case DeclarationName::ObjCZeroArgSelector:
7393 case DeclarationName::ObjCOneArgSelector:
7394 case DeclarationName::ObjCMultiArgSelector:
7395 return DeclarationName(ReadSelector(F, Record, Idx));
7396
7397 case DeclarationName::CXXConstructorName:
7398 return Context.DeclarationNames.getCXXConstructorName(
7399 Context.getCanonicalType(readType(F, Record, Idx)));
7400
7401 case DeclarationName::CXXDestructorName:
7402 return Context.DeclarationNames.getCXXDestructorName(
7403 Context.getCanonicalType(readType(F, Record, Idx)));
7404
7405 case DeclarationName::CXXConversionFunctionName:
7406 return Context.DeclarationNames.getCXXConversionFunctionName(
7407 Context.getCanonicalType(readType(F, Record, Idx)));
7408
7409 case DeclarationName::CXXOperatorName:
7410 return Context.DeclarationNames.getCXXOperatorName(
7411 (OverloadedOperatorKind)Record[Idx++]);
7412
7413 case DeclarationName::CXXLiteralOperatorName:
7414 return Context.DeclarationNames.getCXXLiteralOperatorName(
7415 GetIdentifierInfo(F, Record, Idx));
7416
7417 case DeclarationName::CXXUsingDirective:
7418 return DeclarationName::getUsingDirectiveName();
7419 }
7420
7421 llvm_unreachable("Invalid NameKind!");
7422}
7423
7424void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7425 DeclarationNameLoc &DNLoc,
7426 DeclarationName Name,
7427 const RecordData &Record, unsigned &Idx) {
7428 switch (Name.getNameKind()) {
7429 case DeclarationName::CXXConstructorName:
7430 case DeclarationName::CXXDestructorName:
7431 case DeclarationName::CXXConversionFunctionName:
7432 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7433 break;
7434
7435 case DeclarationName::CXXOperatorName:
7436 DNLoc.CXXOperatorName.BeginOpNameLoc
7437 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7438 DNLoc.CXXOperatorName.EndOpNameLoc
7439 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7440 break;
7441
7442 case DeclarationName::CXXLiteralOperatorName:
7443 DNLoc.CXXLiteralOperatorName.OpNameLoc
7444 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7445 break;
7446
7447 case DeclarationName::Identifier:
7448 case DeclarationName::ObjCZeroArgSelector:
7449 case DeclarationName::ObjCOneArgSelector:
7450 case DeclarationName::ObjCMultiArgSelector:
7451 case DeclarationName::CXXUsingDirective:
7452 break;
7453 }
7454}
7455
7456void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7457 DeclarationNameInfo &NameInfo,
7458 const RecordData &Record, unsigned &Idx) {
7459 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7460 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7461 DeclarationNameLoc DNLoc;
7462 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7463 NameInfo.setInfo(DNLoc);
7464}
7465
7466void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7467 const RecordData &Record, unsigned &Idx) {
7468 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7469 unsigned NumTPLists = Record[Idx++];
7470 Info.NumTemplParamLists = NumTPLists;
7471 if (NumTPLists) {
7472 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7473 for (unsigned i=0; i != NumTPLists; ++i)
7474 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7475 }
7476}
7477
7478TemplateName
7479ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7480 unsigned &Idx) {
7481 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7482 switch (Kind) {
7483 case TemplateName::Template:
7484 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7485
7486 case TemplateName::OverloadedTemplate: {
7487 unsigned size = Record[Idx++];
7488 UnresolvedSet<8> Decls;
7489 while (size--)
7490 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7491
7492 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7493 }
7494
7495 case TemplateName::QualifiedTemplate: {
7496 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7497 bool hasTemplKeyword = Record[Idx++];
7498 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7499 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7500 }
7501
7502 case TemplateName::DependentTemplate: {
7503 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7504 if (Record[Idx++]) // isIdentifier
7505 return Context.getDependentTemplateName(NNS,
7506 GetIdentifierInfo(F, Record,
7507 Idx));
7508 return Context.getDependentTemplateName(NNS,
7509 (OverloadedOperatorKind)Record[Idx++]);
7510 }
7511
7512 case TemplateName::SubstTemplateTemplateParm: {
7513 TemplateTemplateParmDecl *param
7514 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7515 if (!param) return TemplateName();
7516 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7517 return Context.getSubstTemplateTemplateParm(param, replacement);
7518 }
7519
7520 case TemplateName::SubstTemplateTemplateParmPack: {
7521 TemplateTemplateParmDecl *Param
7522 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7523 if (!Param)
7524 return TemplateName();
7525
7526 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7527 if (ArgPack.getKind() != TemplateArgument::Pack)
7528 return TemplateName();
7529
7530 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7531 }
7532 }
7533
7534 llvm_unreachable("Unhandled template name kind!");
7535}
7536
7537TemplateArgument
7538ASTReader::ReadTemplateArgument(ModuleFile &F,
7539 const RecordData &Record, unsigned &Idx) {
7540 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7541 switch (Kind) {
7542 case TemplateArgument::Null:
7543 return TemplateArgument();
7544 case TemplateArgument::Type:
7545 return TemplateArgument(readType(F, Record, Idx));
7546 case TemplateArgument::Declaration: {
7547 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7548 bool ForReferenceParam = Record[Idx++];
7549 return TemplateArgument(D, ForReferenceParam);
7550 }
7551 case TemplateArgument::NullPtr:
7552 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7553 case TemplateArgument::Integral: {
7554 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7555 QualType T = readType(F, Record, Idx);
7556 return TemplateArgument(Context, Value, T);
7557 }
7558 case TemplateArgument::Template:
7559 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7560 case TemplateArgument::TemplateExpansion: {
7561 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007562 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007563 if (unsigned NumExpansions = Record[Idx++])
7564 NumTemplateExpansions = NumExpansions - 1;
7565 return TemplateArgument(Name, NumTemplateExpansions);
7566 }
7567 case TemplateArgument::Expression:
7568 return TemplateArgument(ReadExpr(F));
7569 case TemplateArgument::Pack: {
7570 unsigned NumArgs = Record[Idx++];
7571 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7572 for (unsigned I = 0; I != NumArgs; ++I)
7573 Args[I] = ReadTemplateArgument(F, Record, Idx);
7574 return TemplateArgument(Args, NumArgs);
7575 }
7576 }
7577
7578 llvm_unreachable("Unhandled template argument kind!");
7579}
7580
7581TemplateParameterList *
7582ASTReader::ReadTemplateParameterList(ModuleFile &F,
7583 const RecordData &Record, unsigned &Idx) {
7584 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7585 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7586 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7587
7588 unsigned NumParams = Record[Idx++];
7589 SmallVector<NamedDecl *, 16> Params;
7590 Params.reserve(NumParams);
7591 while (NumParams--)
7592 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7593
7594 TemplateParameterList* TemplateParams =
7595 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7596 Params.data(), Params.size(), RAngleLoc);
7597 return TemplateParams;
7598}
7599
7600void
7601ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007602ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007603 ModuleFile &F, const RecordData &Record,
7604 unsigned &Idx) {
7605 unsigned NumTemplateArgs = Record[Idx++];
7606 TemplArgs.reserve(NumTemplateArgs);
7607 while (NumTemplateArgs--)
7608 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7609}
7610
7611/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007612void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 const RecordData &Record, unsigned &Idx) {
7614 unsigned NumDecls = Record[Idx++];
7615 Set.reserve(Context, NumDecls);
7616 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007617 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007619 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 }
7621}
7622
7623CXXBaseSpecifier
7624ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7625 const RecordData &Record, unsigned &Idx) {
7626 bool isVirtual = static_cast<bool>(Record[Idx++]);
7627 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7628 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7629 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7630 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7631 SourceRange Range = ReadSourceRange(F, Record, Idx);
7632 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7633 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7634 EllipsisLoc);
7635 Result.setInheritConstructors(inheritConstructors);
7636 return Result;
7637}
7638
7639std::pair<CXXCtorInitializer **, unsigned>
7640ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7641 unsigned &Idx) {
7642 CXXCtorInitializer **CtorInitializers = 0;
7643 unsigned NumInitializers = Record[Idx++];
7644 if (NumInitializers) {
7645 CtorInitializers
7646 = new (Context) CXXCtorInitializer*[NumInitializers];
7647 for (unsigned i=0; i != NumInitializers; ++i) {
7648 TypeSourceInfo *TInfo = 0;
7649 bool IsBaseVirtual = false;
7650 FieldDecl *Member = 0;
7651 IndirectFieldDecl *IndirectMember = 0;
7652
7653 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7654 switch (Type) {
7655 case CTOR_INITIALIZER_BASE:
7656 TInfo = GetTypeSourceInfo(F, Record, Idx);
7657 IsBaseVirtual = Record[Idx++];
7658 break;
7659
7660 case CTOR_INITIALIZER_DELEGATING:
7661 TInfo = GetTypeSourceInfo(F, Record, Idx);
7662 break;
7663
7664 case CTOR_INITIALIZER_MEMBER:
7665 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7666 break;
7667
7668 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7669 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7670 break;
7671 }
7672
7673 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7674 Expr *Init = ReadExpr(F);
7675 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7676 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7677 bool IsWritten = Record[Idx++];
7678 unsigned SourceOrderOrNumArrayIndices;
7679 SmallVector<VarDecl *, 8> Indices;
7680 if (IsWritten) {
7681 SourceOrderOrNumArrayIndices = Record[Idx++];
7682 } else {
7683 SourceOrderOrNumArrayIndices = Record[Idx++];
7684 Indices.reserve(SourceOrderOrNumArrayIndices);
7685 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7686 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7687 }
7688
7689 CXXCtorInitializer *BOMInit;
7690 if (Type == CTOR_INITIALIZER_BASE) {
7691 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7692 LParenLoc, Init, RParenLoc,
7693 MemberOrEllipsisLoc);
7694 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7695 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7696 Init, RParenLoc);
7697 } else if (IsWritten) {
7698 if (Member)
7699 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7700 LParenLoc, Init, RParenLoc);
7701 else
7702 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7703 MemberOrEllipsisLoc, LParenLoc,
7704 Init, RParenLoc);
7705 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007706 if (IndirectMember) {
7707 assert(Indices.empty() && "Indirect field improperly initialized");
7708 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7709 MemberOrEllipsisLoc, LParenLoc,
7710 Init, RParenLoc);
7711 } else {
7712 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7713 LParenLoc, Init, RParenLoc,
7714 Indices.data(), Indices.size());
7715 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 }
7717
7718 if (IsWritten)
7719 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7720 CtorInitializers[i] = BOMInit;
7721 }
7722 }
7723
7724 return std::make_pair(CtorInitializers, NumInitializers);
7725}
7726
7727NestedNameSpecifier *
7728ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7729 const RecordData &Record, unsigned &Idx) {
7730 unsigned N = Record[Idx++];
7731 NestedNameSpecifier *NNS = 0, *Prev = 0;
7732 for (unsigned I = 0; I != N; ++I) {
7733 NestedNameSpecifier::SpecifierKind Kind
7734 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7735 switch (Kind) {
7736 case NestedNameSpecifier::Identifier: {
7737 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7738 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7739 break;
7740 }
7741
7742 case NestedNameSpecifier::Namespace: {
7743 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7744 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7745 break;
7746 }
7747
7748 case NestedNameSpecifier::NamespaceAlias: {
7749 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7750 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7751 break;
7752 }
7753
7754 case NestedNameSpecifier::TypeSpec:
7755 case NestedNameSpecifier::TypeSpecWithTemplate: {
7756 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7757 if (!T)
7758 return 0;
7759
7760 bool Template = Record[Idx++];
7761 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7762 break;
7763 }
7764
7765 case NestedNameSpecifier::Global: {
7766 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7767 // No associated value, and there can't be a prefix.
7768 break;
7769 }
7770 }
7771 Prev = NNS;
7772 }
7773 return NNS;
7774}
7775
7776NestedNameSpecifierLoc
7777ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7778 unsigned &Idx) {
7779 unsigned N = Record[Idx++];
7780 NestedNameSpecifierLocBuilder Builder;
7781 for (unsigned I = 0; I != N; ++I) {
7782 NestedNameSpecifier::SpecifierKind Kind
7783 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7784 switch (Kind) {
7785 case NestedNameSpecifier::Identifier: {
7786 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7787 SourceRange Range = ReadSourceRange(F, Record, Idx);
7788 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7789 break;
7790 }
7791
7792 case NestedNameSpecifier::Namespace: {
7793 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7794 SourceRange Range = ReadSourceRange(F, Record, Idx);
7795 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7796 break;
7797 }
7798
7799 case NestedNameSpecifier::NamespaceAlias: {
7800 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7801 SourceRange Range = ReadSourceRange(F, Record, Idx);
7802 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7803 break;
7804 }
7805
7806 case NestedNameSpecifier::TypeSpec:
7807 case NestedNameSpecifier::TypeSpecWithTemplate: {
7808 bool Template = Record[Idx++];
7809 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7810 if (!T)
7811 return NestedNameSpecifierLoc();
7812 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7813
7814 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7815 Builder.Extend(Context,
7816 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7817 T->getTypeLoc(), ColonColonLoc);
7818 break;
7819 }
7820
7821 case NestedNameSpecifier::Global: {
7822 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7823 Builder.MakeGlobal(Context, ColonColonLoc);
7824 break;
7825 }
7826 }
7827 }
7828
7829 return Builder.getWithLocInContext(Context);
7830}
7831
7832SourceRange
7833ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7834 unsigned &Idx) {
7835 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7836 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7837 return SourceRange(beg, end);
7838}
7839
7840/// \brief Read an integral value
7841llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7842 unsigned BitWidth = Record[Idx++];
7843 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7844 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7845 Idx += NumWords;
7846 return Result;
7847}
7848
7849/// \brief Read a signed integral value
7850llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7851 bool isUnsigned = Record[Idx++];
7852 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7853}
7854
7855/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007856llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7857 const llvm::fltSemantics &Sem,
7858 unsigned &Idx) {
7859 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007860}
7861
7862// \brief Read a string
7863std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7864 unsigned Len = Record[Idx++];
7865 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7866 Idx += Len;
7867 return Result;
7868}
7869
7870VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7871 unsigned &Idx) {
7872 unsigned Major = Record[Idx++];
7873 unsigned Minor = Record[Idx++];
7874 unsigned Subminor = Record[Idx++];
7875 if (Minor == 0)
7876 return VersionTuple(Major);
7877 if (Subminor == 0)
7878 return VersionTuple(Major, Minor - 1);
7879 return VersionTuple(Major, Minor - 1, Subminor - 1);
7880}
7881
7882CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7883 const RecordData &Record,
7884 unsigned &Idx) {
7885 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7886 return CXXTemporary::Create(Context, Decl);
7887}
7888
7889DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007890 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007891}
7892
7893DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7894 return Diags.Report(Loc, DiagID);
7895}
7896
7897/// \brief Retrieve the identifier table associated with the
7898/// preprocessor.
7899IdentifierTable &ASTReader::getIdentifierTable() {
7900 return PP.getIdentifierTable();
7901}
7902
7903/// \brief Record that the given ID maps to the given switch-case
7904/// statement.
7905void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7906 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7907 "Already have a SwitchCase with this ID");
7908 (*CurrSwitchCaseStmts)[ID] = SC;
7909}
7910
7911/// \brief Retrieve the switch-case statement with the given ID.
7912SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7913 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7914 return (*CurrSwitchCaseStmts)[ID];
7915}
7916
7917void ASTReader::ClearSwitchCaseIDs() {
7918 CurrSwitchCaseStmts->clear();
7919}
7920
7921void ASTReader::ReadComments() {
7922 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007923 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 serialization::ModuleFile *> >::iterator
7925 I = CommentsCursors.begin(),
7926 E = CommentsCursors.end();
7927 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007928 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007929 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 serialization::ModuleFile &F = *I->second;
7931 SavedStreamPosition SavedPosition(Cursor);
7932
7933 RecordData Record;
7934 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007935 llvm::BitstreamEntry Entry =
7936 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007937
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007938 switch (Entry.Kind) {
7939 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7940 case llvm::BitstreamEntry::Error:
7941 Error("malformed block record in AST file");
7942 return;
7943 case llvm::BitstreamEntry::EndBlock:
7944 goto NextCursor;
7945 case llvm::BitstreamEntry::Record:
7946 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007948 }
7949
7950 // Read a record.
7951 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007952 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 case COMMENTS_RAW_COMMENT: {
7954 unsigned Idx = 0;
7955 SourceRange SR = ReadSourceRange(F, Record, Idx);
7956 RawComment::CommentKind Kind =
7957 (RawComment::CommentKind) Record[Idx++];
7958 bool IsTrailingComment = Record[Idx++];
7959 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007960 Comments.push_back(new (Context) RawComment(
7961 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7962 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 break;
7964 }
7965 }
7966 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007967 NextCursor:
7968 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007970}
7971
Richard Smithcd45dbc2014-04-19 03:48:30 +00007972std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7973 // If we know the owning module, use it.
7974 if (Module *M = D->getOwningModule())
7975 return M->getFullModuleName();
7976
7977 // Otherwise, use the name of the top-level module the decl is within.
7978 if (ModuleFile *M = getOwningModuleFile(D))
7979 return M->ModuleName;
7980
7981 // Not from a module.
7982 return "";
7983}
7984
Guy Benyei11169dd2012-12-18 14:30:41 +00007985void ASTReader::finishPendingActions() {
7986 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007987 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00007988 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 // If any identifiers with corresponding top-level declarations have
7990 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007991 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7992 TopLevelDeclsMap;
7993 TopLevelDeclsMap TopLevelDecls;
7994
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007996 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007997 SmallVector<uint32_t, 4> DeclIDs =
7998 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007999 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008000
8001 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008003
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 // Load pending declaration chains.
8005 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8006 loadPendingDeclChain(PendingDeclChains[I]);
8007 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8008 }
8009 PendingDeclChains.clear();
8010
Douglas Gregor6168bd22013-02-18 15:53:43 +00008011 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008012 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8013 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008014 IdentifierInfo *II = TLD->first;
8015 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008016 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008017 }
8018 }
8019
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 // Load any pending macro definitions.
8021 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008022 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8023 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8024 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8025 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008026 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008027 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008028 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8029 if (Info.M->Kind != MK_Module)
8030 resolvePendingMacro(II, Info);
8031 }
8032 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008033 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008034 ++IDIdx) {
8035 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8036 if (Info.M->Kind == MK_Module)
8037 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 }
8039 }
8040 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008041
8042 // Wire up the DeclContexts for Decls that we delayed setting until
8043 // recursive loading is completed.
8044 while (!PendingDeclContextInfos.empty()) {
8045 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8046 PendingDeclContextInfos.pop_front();
8047 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8048 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8049 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8050 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008051
Richard Smithd1c46742014-04-30 02:24:17 +00008052 // Perform any pending declaration updates.
8053 while (!PendingUpdateRecords.empty()) {
8054 auto Update = PendingUpdateRecords.pop_back_val();
8055 ReadingKindTracker ReadingKind(Read_Decl, *this);
8056 loadDeclUpdateRecords(Update.first, Update.second);
8057 }
8058
Richard Smithcd45dbc2014-04-19 03:48:30 +00008059 // Trigger the import of the full definition of each class that had any
8060 // odr-merging problems, so we can produce better diagnostics for them.
8061 for (auto &Merge : PendingOdrMergeFailures) {
8062 Merge.first->buildLookup();
8063 Merge.first->decls_begin();
8064 Merge.first->bases_begin();
8065 Merge.first->vbases_begin();
8066 for (auto *RD : Merge.second) {
8067 RD->decls_begin();
8068 RD->bases_begin();
8069 RD->vbases_begin();
8070 }
8071 }
8072
Richard Smith2b9e3e32013-10-18 06:05:18 +00008073 // For each declaration from a merged context, check that the canonical
8074 // definition of that context also contains a declaration of the same
8075 // entity.
8076 while (!PendingOdrMergeChecks.empty()) {
8077 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8078
8079 // FIXME: Skip over implicit declarations for now. This matters for things
8080 // like implicitly-declared special member functions. This isn't entirely
8081 // correct; we can end up with multiple unmerged declarations of the same
8082 // implicit entity.
8083 if (D->isImplicit())
8084 continue;
8085
8086 DeclContext *CanonDef = D->getDeclContext();
8087 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8088
8089 bool Found = false;
8090 const Decl *DCanon = D->getCanonicalDecl();
8091
8092 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8093 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8094 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008095 for (auto RI : (*I)->redecls()) {
8096 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008097 // This declaration is present in the canonical definition. If it's
8098 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008099 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008100 Found = true;
8101 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008102 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008103 break;
8104 }
8105 }
8106 }
8107
8108 if (!Found) {
8109 D->setInvalidDecl();
8110
Richard Smithcd45dbc2014-04-19 03:48:30 +00008111 std::string CanonDefModule =
8112 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008113 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008114 << D << getOwningModuleNameForDiagnostic(D)
8115 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008116
8117 if (Candidates.empty())
8118 Diag(cast<Decl>(CanonDef)->getLocation(),
8119 diag::note_module_odr_violation_no_possible_decls) << D;
8120 else {
8121 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8122 Diag(Candidates[I]->getLocation(),
8123 diag::note_module_odr_violation_possible_decl)
8124 << Candidates[I];
8125 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008126
8127 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008128 }
8129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 }
8131
8132 // If we deserialized any C++ or Objective-C class definitions, any
8133 // Objective-C protocol definitions, or any redeclarable templates, make sure
8134 // that all redeclarations point to the definitions. Note that this can only
8135 // happen now, after the redeclaration chains have been fully wired.
8136 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8137 DEnd = PendingDefinitions.end();
8138 D != DEnd; ++D) {
8139 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008140 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 // Make sure that the TagType points at the definition.
8142 const_cast<TagType*>(TagT)->decl = TD;
8143 }
8144
Aaron Ballman86c93902014-03-06 23:45:36 +00008145 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8146 for (auto R : RD->redecls())
8147 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 }
8149
8150 continue;
8151 }
8152
Aaron Ballman86c93902014-03-06 23:45:36 +00008153 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008154 // Make sure that the ObjCInterfaceType points at the definition.
8155 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8156 ->Decl = ID;
8157
Aaron Ballman86c93902014-03-06 23:45:36 +00008158 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 R->Data = ID->Data;
8160
8161 continue;
8162 }
8163
Aaron Ballman86c93902014-03-06 23:45:36 +00008164 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8165 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 R->Data = PD->Data;
8167
8168 continue;
8169 }
8170
Aaron Ballman86c93902014-03-06 23:45:36 +00008171 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8172 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 R->Common = RTD->Common;
8174 }
8175 PendingDefinitions.clear();
8176
8177 // Load the bodies of any functions or methods we've encountered. We do
8178 // this now (delayed) so that we can be sure that the declaration chains
8179 // have been fully wired up.
8180 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8181 PBEnd = PendingBodies.end();
8182 PB != PBEnd; ++PB) {
8183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8184 // FIXME: Check for =delete/=default?
8185 // FIXME: Complain about ODR violations here?
8186 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8187 FD->setLazyBody(PB->second);
8188 continue;
8189 }
8190
8191 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8192 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8193 MD->setLazyBody(PB->second);
8194 }
8195 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008196
8197 // Issue any pending ODR-failure diagnostics.
8198 for (auto &Merge : PendingOdrMergeFailures) {
8199 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8200 continue;
8201
8202 bool Diagnosed = false;
8203 for (auto *RD : Merge.second) {
8204 // Multiple different declarations got merged together; tell the user
8205 // where they came from.
8206 if (Merge.first != RD) {
8207 // FIXME: Walk the definition, figure out what's different,
8208 // and diagnose that.
8209 if (!Diagnosed) {
8210 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8211 Diag(Merge.first->getLocation(),
8212 diag::err_module_odr_violation_different_definitions)
8213 << Merge.first << Module.empty() << Module;
8214 Diagnosed = true;
8215 }
8216
8217 Diag(RD->getLocation(),
8218 diag::note_module_odr_violation_different_definitions)
8219 << getOwningModuleNameForDiagnostic(RD);
8220 }
8221 }
8222
8223 if (!Diagnosed) {
8224 // All definitions are updates to the same declaration. This happens if a
8225 // module instantiates the declaration of a class template specialization
8226 // and two or more other modules instantiate its definition.
8227 //
8228 // FIXME: Indicate which modules had instantiations of this definition.
8229 // FIXME: How can this even happen?
8230 Diag(Merge.first->getLocation(),
8231 diag::err_module_odr_violation_different_instantiations)
8232 << Merge.first;
8233 }
8234 }
8235 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008236}
8237
8238void ASTReader::FinishedDeserializing() {
8239 assert(NumCurrentElementsDeserializing &&
8240 "FinishedDeserializing not paired with StartedDeserializing");
8241 if (NumCurrentElementsDeserializing == 1) {
8242 // We decrease NumCurrentElementsDeserializing only after pending actions
8243 // are finished, to avoid recursively re-calling finishPendingActions().
8244 finishPendingActions();
8245 }
8246 --NumCurrentElementsDeserializing;
8247
Richard Smith04d05b52014-03-23 00:27:18 +00008248 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8249 // We are not in recursive loading, so it's safe to pass the "interesting"
8250 // decls to the consumer.
8251 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 }
8253}
8254
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008255void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008256 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008257
8258 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8259 SemaObj->TUScope->AddDecl(D);
8260 } else if (SemaObj->TUScope) {
8261 // Adding the decl to IdResolver may have failed because it was already in
8262 // (even though it was not added in scope). If it is already in, make sure
8263 // it gets in the scope as well.
8264 if (std::find(SemaObj->IdResolver.begin(Name),
8265 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8266 SemaObj->TUScope->AddDecl(D);
8267 }
8268}
8269
Nico Weber824285e2014-05-08 04:26:47 +00008270ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8271 bool DisableValidation, bool AllowASTWithCompilerErrors,
8272 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008273 bool UseGlobalIndex)
Nico Weber824285e2014-05-08 04:26:47 +00008274 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8275 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8276 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()), SemaObj(0),
8277 PP(PP), Context(Context), Consumer(0), ModuleMgr(PP.getFileManager()),
8278 isysroot(isysroot), DisableValidation(DisableValidation),
8279 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8280 AllowConfigurationMismatch(AllowConfigurationMismatch),
8281 ValidateSystemInputs(ValidateSystemInputs),
8282 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008283 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008284 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8285 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8286 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8287 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8288 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8289 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8290 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8291 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8292 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8293 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8294 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008295 SourceMgr.setExternalSLocEntrySource(this);
8296}
8297
8298ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008299 if (OwnsDeserializationListener)
8300 delete DeserializationListener;
8301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 for (DeclContextVisibleUpdatesPending::iterator
8303 I = PendingVisibleUpdates.begin(),
8304 E = PendingVisibleUpdates.end();
8305 I != E; ++I) {
8306 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8307 F = I->second.end();
8308 J != F; ++J)
8309 delete J->first;
8310 }
8311}