blob: ea7f953b9f5e485a0e28712807472120427ac311 [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)
1710 IdentifierGeneration[II] = CurrentGeneration;
1711}
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.
3438 unsigned PreviousGeneration = CurrentGeneration++;
3439
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,
3618 CurrentGeneration, ExpectedSize, ExpectedModTime,
3619 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
4842/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4843PreprocessedEntityID
4844ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4845 if (SourceMgr.isLocalSourceLocation(BLoc))
4846 return getTotalNumPreprocessedEntities();
4847
4848 GlobalSLocOffsetMapType::const_iterator
4849 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004850 BLoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004851 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4852 "Corrupted global sloc offset map");
4853
4854 if (SLocMapI->second->NumPreprocessedEntities == 0)
4855 return findNextPreprocessedEntity(SLocMapI);
4856
4857 ModuleFile &M = *SLocMapI->second;
4858 typedef const PPEntityOffset *pp_iterator;
4859 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4860 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4861
4862 size_t Count = M.NumPreprocessedEntities;
4863 size_t Half;
4864 pp_iterator First = pp_begin;
4865 pp_iterator PPI;
4866
4867 // Do a binary search manually instead of using std::lower_bound because
4868 // The end locations of entities may be unordered (when a macro expansion
4869 // is inside another macro argument), but for this case it is not important
4870 // whether we get the first macro expansion or its containing macro.
4871 while (Count > 0) {
4872 Half = Count/2;
4873 PPI = First;
4874 std::advance(PPI, Half);
4875 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4876 BLoc)){
4877 First = PPI;
4878 ++First;
4879 Count = Count - Half - 1;
4880 } else
4881 Count = Half;
4882 }
4883
4884 if (PPI == pp_end)
4885 return findNextPreprocessedEntity(SLocMapI);
4886
4887 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4888}
4889
4890/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4891PreprocessedEntityID
4892ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4893 if (SourceMgr.isLocalSourceLocation(ELoc))
4894 return getTotalNumPreprocessedEntities();
4895
4896 GlobalSLocOffsetMapType::const_iterator
4897 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004898 ELoc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4900 "Corrupted global sloc offset map");
4901
4902 if (SLocMapI->second->NumPreprocessedEntities == 0)
4903 return findNextPreprocessedEntity(SLocMapI);
4904
4905 ModuleFile &M = *SLocMapI->second;
4906 typedef const PPEntityOffset *pp_iterator;
4907 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4908 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4909 pp_iterator PPI =
4910 std::upper_bound(pp_begin, pp_end, ELoc,
4911 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4912
4913 if (PPI == pp_end)
4914 return findNextPreprocessedEntity(SLocMapI);
4915
4916 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4917}
4918
4919/// \brief Returns a pair of [Begin, End) indices of preallocated
4920/// preprocessed entities that \arg Range encompasses.
4921std::pair<unsigned, unsigned>
4922 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4923 if (Range.isInvalid())
4924 return std::make_pair(0,0);
4925 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4926
4927 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4928 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4929 return std::make_pair(BeginID, EndID);
4930}
4931
4932/// \brief Optionally returns true or false if the preallocated preprocessed
4933/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004934Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 FileID FID) {
4936 if (FID.isInvalid())
4937 return false;
4938
4939 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4940 ModuleFile &M = *PPInfo.first;
4941 unsigned LocalIndex = PPInfo.second;
4942 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4943
4944 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4945 if (Loc.isInvalid())
4946 return false;
4947
4948 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4949 return true;
4950 else
4951 return false;
4952}
4953
4954namespace {
4955 /// \brief Visitor used to search for information about a header file.
4956 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 const FileEntry *FE;
4958
David Blaikie05785d12013-02-20 22:23:23 +00004959 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004960
4961 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004962 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4963 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004964
4965 static bool visit(ModuleFile &M, void *UserData) {
4966 HeaderFileInfoVisitor *This
4967 = static_cast<HeaderFileInfoVisitor *>(UserData);
4968
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 HeaderFileInfoLookupTable *Table
4970 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4971 if (!Table)
4972 return false;
4973
4974 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004975 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 if (Pos == Table->end())
4977 return false;
4978
4979 This->HFI = *Pos;
4980 return true;
4981 }
4982
David Blaikie05785d12013-02-20 22:23:23 +00004983 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 };
4985}
4986
4987HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004988 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004989 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004990 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004992
4993 return HeaderFileInfo();
4994}
4995
4996void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4997 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004998 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5000 ModuleFile &F = *(*I);
5001 unsigned Idx = 0;
5002 DiagStates.clear();
5003 assert(!Diag.DiagStates.empty());
5004 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5005 while (Idx < F.PragmaDiagMappings.size()) {
5006 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5007 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5008 if (DiagStateID != 0) {
5009 Diag.DiagStatePoints.push_back(
5010 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5011 FullSourceLoc(Loc, SourceMgr)));
5012 continue;
5013 }
5014
5015 assert(DiagStateID == 0);
5016 // A new DiagState was created here.
5017 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5018 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5019 DiagStates.push_back(NewState);
5020 Diag.DiagStatePoints.push_back(
5021 DiagnosticsEngine::DiagStatePoint(NewState,
5022 FullSourceLoc(Loc, SourceMgr)));
5023 while (1) {
5024 assert(Idx < F.PragmaDiagMappings.size() &&
5025 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5026 if (Idx >= F.PragmaDiagMappings.size()) {
5027 break; // Something is messed up but at least avoid infinite loop in
5028 // release build.
5029 }
5030 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5031 if (DiagID == (unsigned)-1) {
5032 break; // no more diag/map pairs for this location.
5033 }
5034 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5035 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5036 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5037 }
5038 }
5039 }
5040}
5041
5042/// \brief Get the correct cursor and offset for loading a type.
5043ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5044 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5045 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5046 ModuleFile *M = I->second;
5047 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5048}
5049
5050/// \brief Read and return the type with the given index..
5051///
5052/// The index is the type ID, shifted and minus the number of predefs. This
5053/// routine actually reads the record corresponding to the type at the given
5054/// location. It is a helper routine for GetType, which deals with reading type
5055/// IDs.
5056QualType ASTReader::readTypeRecord(unsigned Index) {
5057 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005058 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005059
5060 // Keep track of where we are in the stream, then jump back there
5061 // after reading this type.
5062 SavedStreamPosition SavedPosition(DeclsCursor);
5063
5064 ReadingKindTracker ReadingKind(Read_Type, *this);
5065
5066 // Note that we are loading a type record.
5067 Deserializing AType(this);
5068
5069 unsigned Idx = 0;
5070 DeclsCursor.JumpToBit(Loc.Offset);
5071 RecordData Record;
5072 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005073 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 case TYPE_EXT_QUAL: {
5075 if (Record.size() != 2) {
5076 Error("Incorrect encoding of extended qualifier type");
5077 return QualType();
5078 }
5079 QualType Base = readType(*Loc.F, Record, Idx);
5080 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5081 return Context.getQualifiedType(Base, Quals);
5082 }
5083
5084 case TYPE_COMPLEX: {
5085 if (Record.size() != 1) {
5086 Error("Incorrect encoding of complex type");
5087 return QualType();
5088 }
5089 QualType ElemType = readType(*Loc.F, Record, Idx);
5090 return Context.getComplexType(ElemType);
5091 }
5092
5093 case TYPE_POINTER: {
5094 if (Record.size() != 1) {
5095 Error("Incorrect encoding of pointer type");
5096 return QualType();
5097 }
5098 QualType PointeeType = readType(*Loc.F, Record, Idx);
5099 return Context.getPointerType(PointeeType);
5100 }
5101
Reid Kleckner8a365022013-06-24 17:51:48 +00005102 case TYPE_DECAYED: {
5103 if (Record.size() != 1) {
5104 Error("Incorrect encoding of decayed type");
5105 return QualType();
5106 }
5107 QualType OriginalType = readType(*Loc.F, Record, Idx);
5108 QualType DT = Context.getAdjustedParameterType(OriginalType);
5109 if (!isa<DecayedType>(DT))
5110 Error("Decayed type does not decay");
5111 return DT;
5112 }
5113
Reid Kleckner0503a872013-12-05 01:23:43 +00005114 case TYPE_ADJUSTED: {
5115 if (Record.size() != 2) {
5116 Error("Incorrect encoding of adjusted type");
5117 return QualType();
5118 }
5119 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5120 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5121 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5122 }
5123
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case TYPE_BLOCK_POINTER: {
5125 if (Record.size() != 1) {
5126 Error("Incorrect encoding of block pointer type");
5127 return QualType();
5128 }
5129 QualType PointeeType = readType(*Loc.F, Record, Idx);
5130 return Context.getBlockPointerType(PointeeType);
5131 }
5132
5133 case TYPE_LVALUE_REFERENCE: {
5134 if (Record.size() != 2) {
5135 Error("Incorrect encoding of lvalue reference type");
5136 return QualType();
5137 }
5138 QualType PointeeType = readType(*Loc.F, Record, Idx);
5139 return Context.getLValueReferenceType(PointeeType, Record[1]);
5140 }
5141
5142 case TYPE_RVALUE_REFERENCE: {
5143 if (Record.size() != 1) {
5144 Error("Incorrect encoding of rvalue reference type");
5145 return QualType();
5146 }
5147 QualType PointeeType = readType(*Loc.F, Record, Idx);
5148 return Context.getRValueReferenceType(PointeeType);
5149 }
5150
5151 case TYPE_MEMBER_POINTER: {
5152 if (Record.size() != 2) {
5153 Error("Incorrect encoding of member pointer type");
5154 return QualType();
5155 }
5156 QualType PointeeType = readType(*Loc.F, Record, Idx);
5157 QualType ClassType = readType(*Loc.F, Record, Idx);
5158 if (PointeeType.isNull() || ClassType.isNull())
5159 return QualType();
5160
5161 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5162 }
5163
5164 case TYPE_CONSTANT_ARRAY: {
5165 QualType ElementType = readType(*Loc.F, Record, Idx);
5166 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5167 unsigned IndexTypeQuals = Record[2];
5168 unsigned Idx = 3;
5169 llvm::APInt Size = ReadAPInt(Record, Idx);
5170 return Context.getConstantArrayType(ElementType, Size,
5171 ASM, IndexTypeQuals);
5172 }
5173
5174 case TYPE_INCOMPLETE_ARRAY: {
5175 QualType ElementType = readType(*Loc.F, Record, Idx);
5176 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5177 unsigned IndexTypeQuals = Record[2];
5178 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5179 }
5180
5181 case TYPE_VARIABLE_ARRAY: {
5182 QualType ElementType = readType(*Loc.F, Record, Idx);
5183 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5184 unsigned IndexTypeQuals = Record[2];
5185 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5186 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5187 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5188 ASM, IndexTypeQuals,
5189 SourceRange(LBLoc, RBLoc));
5190 }
5191
5192 case TYPE_VECTOR: {
5193 if (Record.size() != 3) {
5194 Error("incorrect encoding of vector type in AST file");
5195 return QualType();
5196 }
5197
5198 QualType ElementType = readType(*Loc.F, Record, Idx);
5199 unsigned NumElements = Record[1];
5200 unsigned VecKind = Record[2];
5201 return Context.getVectorType(ElementType, NumElements,
5202 (VectorType::VectorKind)VecKind);
5203 }
5204
5205 case TYPE_EXT_VECTOR: {
5206 if (Record.size() != 3) {
5207 Error("incorrect encoding of extended vector type in AST file");
5208 return QualType();
5209 }
5210
5211 QualType ElementType = readType(*Loc.F, Record, Idx);
5212 unsigned NumElements = Record[1];
5213 return Context.getExtVectorType(ElementType, NumElements);
5214 }
5215
5216 case TYPE_FUNCTION_NO_PROTO: {
5217 if (Record.size() != 6) {
5218 Error("incorrect encoding of no-proto function type");
5219 return QualType();
5220 }
5221 QualType ResultType = readType(*Loc.F, Record, Idx);
5222 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5223 (CallingConv)Record[4], Record[5]);
5224 return Context.getFunctionNoProtoType(ResultType, Info);
5225 }
5226
5227 case TYPE_FUNCTION_PROTO: {
5228 QualType ResultType = readType(*Loc.F, Record, Idx);
5229
5230 FunctionProtoType::ExtProtoInfo EPI;
5231 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5232 /*hasregparm*/ Record[2],
5233 /*regparm*/ Record[3],
5234 static_cast<CallingConv>(Record[4]),
5235 /*produces*/ Record[5]);
5236
5237 unsigned Idx = 6;
5238 unsigned NumParams = Record[Idx++];
5239 SmallVector<QualType, 16> ParamTypes;
5240 for (unsigned I = 0; I != NumParams; ++I)
5241 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5242
5243 EPI.Variadic = Record[Idx++];
5244 EPI.HasTrailingReturn = Record[Idx++];
5245 EPI.TypeQuals = Record[Idx++];
5246 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005247 SmallVector<QualType, 8> ExceptionStorage;
5248 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005249 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 }
5251
5252 case TYPE_UNRESOLVED_USING: {
5253 unsigned Idx = 0;
5254 return Context.getTypeDeclType(
5255 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5256 }
5257
5258 case TYPE_TYPEDEF: {
5259 if (Record.size() != 2) {
5260 Error("incorrect encoding of typedef type");
5261 return QualType();
5262 }
5263 unsigned Idx = 0;
5264 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5265 QualType Canonical = readType(*Loc.F, Record, Idx);
5266 if (!Canonical.isNull())
5267 Canonical = Context.getCanonicalType(Canonical);
5268 return Context.getTypedefType(Decl, Canonical);
5269 }
5270
5271 case TYPE_TYPEOF_EXPR:
5272 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5273
5274 case TYPE_TYPEOF: {
5275 if (Record.size() != 1) {
5276 Error("incorrect encoding of typeof(type) in AST file");
5277 return QualType();
5278 }
5279 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5280 return Context.getTypeOfType(UnderlyingType);
5281 }
5282
5283 case TYPE_DECLTYPE: {
5284 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5285 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5286 }
5287
5288 case TYPE_UNARY_TRANSFORM: {
5289 QualType BaseType = readType(*Loc.F, Record, Idx);
5290 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5291 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5292 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5293 }
5294
Richard Smith74aeef52013-04-26 16:15:35 +00005295 case TYPE_AUTO: {
5296 QualType Deduced = readType(*Loc.F, Record, Idx);
5297 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005298 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005299 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005300 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005301
5302 case TYPE_RECORD: {
5303 if (Record.size() != 2) {
5304 Error("incorrect encoding of record type");
5305 return QualType();
5306 }
5307 unsigned Idx = 0;
5308 bool IsDependent = Record[Idx++];
5309 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5310 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5311 QualType T = Context.getRecordType(RD);
5312 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5313 return T;
5314 }
5315
5316 case TYPE_ENUM: {
5317 if (Record.size() != 2) {
5318 Error("incorrect encoding of enum type");
5319 return QualType();
5320 }
5321 unsigned Idx = 0;
5322 bool IsDependent = Record[Idx++];
5323 QualType T
5324 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5325 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5326 return T;
5327 }
5328
5329 case TYPE_ATTRIBUTED: {
5330 if (Record.size() != 3) {
5331 Error("incorrect encoding of attributed type");
5332 return QualType();
5333 }
5334 QualType modifiedType = readType(*Loc.F, Record, Idx);
5335 QualType equivalentType = readType(*Loc.F, Record, Idx);
5336 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5337 return Context.getAttributedType(kind, modifiedType, equivalentType);
5338 }
5339
5340 case TYPE_PAREN: {
5341 if (Record.size() != 1) {
5342 Error("incorrect encoding of paren type");
5343 return QualType();
5344 }
5345 QualType InnerType = readType(*Loc.F, Record, Idx);
5346 return Context.getParenType(InnerType);
5347 }
5348
5349 case TYPE_PACK_EXPANSION: {
5350 if (Record.size() != 2) {
5351 Error("incorrect encoding of pack expansion type");
5352 return QualType();
5353 }
5354 QualType Pattern = readType(*Loc.F, Record, Idx);
5355 if (Pattern.isNull())
5356 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005357 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 if (Record[1])
5359 NumExpansions = Record[1] - 1;
5360 return Context.getPackExpansionType(Pattern, NumExpansions);
5361 }
5362
5363 case TYPE_ELABORATED: {
5364 unsigned Idx = 0;
5365 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5366 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5367 QualType NamedType = readType(*Loc.F, Record, Idx);
5368 return Context.getElaboratedType(Keyword, NNS, NamedType);
5369 }
5370
5371 case TYPE_OBJC_INTERFACE: {
5372 unsigned Idx = 0;
5373 ObjCInterfaceDecl *ItfD
5374 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5375 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5376 }
5377
5378 case TYPE_OBJC_OBJECT: {
5379 unsigned Idx = 0;
5380 QualType Base = readType(*Loc.F, Record, Idx);
5381 unsigned NumProtos = Record[Idx++];
5382 SmallVector<ObjCProtocolDecl*, 4> Protos;
5383 for (unsigned I = 0; I != NumProtos; ++I)
5384 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5385 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5386 }
5387
5388 case TYPE_OBJC_OBJECT_POINTER: {
5389 unsigned Idx = 0;
5390 QualType Pointee = readType(*Loc.F, Record, Idx);
5391 return Context.getObjCObjectPointerType(Pointee);
5392 }
5393
5394 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5395 unsigned Idx = 0;
5396 QualType Parm = readType(*Loc.F, Record, Idx);
5397 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005398 return Context.getSubstTemplateTypeParmType(
5399 cast<TemplateTypeParmType>(Parm),
5400 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005401 }
5402
5403 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5404 unsigned Idx = 0;
5405 QualType Parm = readType(*Loc.F, Record, Idx);
5406 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5407 return Context.getSubstTemplateTypeParmPackType(
5408 cast<TemplateTypeParmType>(Parm),
5409 ArgPack);
5410 }
5411
5412 case TYPE_INJECTED_CLASS_NAME: {
5413 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5414 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5415 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5416 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005417 const Type *T;
5418 if (const Type *Existing = D->getTypeForDecl())
5419 T = Existing;
5420 else if (auto *Prev = D->getPreviousDecl())
5421 T = Prev->getTypeForDecl();
5422 else
5423 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5424 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005425 }
5426
5427 case TYPE_TEMPLATE_TYPE_PARM: {
5428 unsigned Idx = 0;
5429 unsigned Depth = Record[Idx++];
5430 unsigned Index = Record[Idx++];
5431 bool Pack = Record[Idx++];
5432 TemplateTypeParmDecl *D
5433 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5434 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5435 }
5436
5437 case TYPE_DEPENDENT_NAME: {
5438 unsigned Idx = 0;
5439 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5440 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5441 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5442 QualType Canon = readType(*Loc.F, Record, Idx);
5443 if (!Canon.isNull())
5444 Canon = Context.getCanonicalType(Canon);
5445 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5446 }
5447
5448 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5449 unsigned Idx = 0;
5450 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5451 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5452 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5453 unsigned NumArgs = Record[Idx++];
5454 SmallVector<TemplateArgument, 8> Args;
5455 Args.reserve(NumArgs);
5456 while (NumArgs--)
5457 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5458 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5459 Args.size(), Args.data());
5460 }
5461
5462 case TYPE_DEPENDENT_SIZED_ARRAY: {
5463 unsigned Idx = 0;
5464
5465 // ArrayType
5466 QualType ElementType = readType(*Loc.F, Record, Idx);
5467 ArrayType::ArraySizeModifier ASM
5468 = (ArrayType::ArraySizeModifier)Record[Idx++];
5469 unsigned IndexTypeQuals = Record[Idx++];
5470
5471 // DependentSizedArrayType
5472 Expr *NumElts = ReadExpr(*Loc.F);
5473 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5474
5475 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5476 IndexTypeQuals, Brackets);
5477 }
5478
5479 case TYPE_TEMPLATE_SPECIALIZATION: {
5480 unsigned Idx = 0;
5481 bool IsDependent = Record[Idx++];
5482 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5483 SmallVector<TemplateArgument, 8> Args;
5484 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5485 QualType Underlying = readType(*Loc.F, Record, Idx);
5486 QualType T;
5487 if (Underlying.isNull())
5488 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5489 Args.size());
5490 else
5491 T = Context.getTemplateSpecializationType(Name, Args.data(),
5492 Args.size(), Underlying);
5493 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5494 return T;
5495 }
5496
5497 case TYPE_ATOMIC: {
5498 if (Record.size() != 1) {
5499 Error("Incorrect encoding of atomic type");
5500 return QualType();
5501 }
5502 QualType ValueType = readType(*Loc.F, Record, Idx);
5503 return Context.getAtomicType(ValueType);
5504 }
5505 }
5506 llvm_unreachable("Invalid TypeCode!");
5507}
5508
Richard Smith564417a2014-03-20 21:47:22 +00005509void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5510 SmallVectorImpl<QualType> &Exceptions,
5511 FunctionProtoType::ExtProtoInfo &EPI,
5512 const RecordData &Record, unsigned &Idx) {
5513 ExceptionSpecificationType EST =
5514 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5515 EPI.ExceptionSpecType = EST;
5516 if (EST == EST_Dynamic) {
5517 EPI.NumExceptions = Record[Idx++];
5518 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5519 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5520 EPI.Exceptions = Exceptions.data();
5521 } else if (EST == EST_ComputedNoexcept) {
5522 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5523 } else if (EST == EST_Uninstantiated) {
5524 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5525 EPI.ExceptionSpecTemplate =
5526 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5527 } else if (EST == EST_Unevaluated) {
5528 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5529 }
5530}
5531
Guy Benyei11169dd2012-12-18 14:30:41 +00005532class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5533 ASTReader &Reader;
5534 ModuleFile &F;
5535 const ASTReader::RecordData &Record;
5536 unsigned &Idx;
5537
5538 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5539 unsigned &I) {
5540 return Reader.ReadSourceLocation(F, R, I);
5541 }
5542
5543 template<typename T>
5544 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5545 return Reader.ReadDeclAs<T>(F, Record, Idx);
5546 }
5547
5548public:
5549 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5550 const ASTReader::RecordData &Record, unsigned &Idx)
5551 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5552 { }
5553
5554 // We want compile-time assurance that we've enumerated all of
5555 // these, so unfortunately we have to declare them first, then
5556 // define them out-of-line.
5557#define ABSTRACT_TYPELOC(CLASS, PARENT)
5558#define TYPELOC(CLASS, PARENT) \
5559 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5560#include "clang/AST/TypeLocNodes.def"
5561
5562 void VisitFunctionTypeLoc(FunctionTypeLoc);
5563 void VisitArrayTypeLoc(ArrayTypeLoc);
5564};
5565
5566void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5567 // nothing to do
5568}
5569void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5570 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5571 if (TL.needsExtraLocalData()) {
5572 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5573 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5574 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5575 TL.setModeAttr(Record[Idx++]);
5576 }
5577}
5578void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5579 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5580}
5581void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5582 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5583}
Reid Kleckner8a365022013-06-24 17:51:48 +00005584void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5585 // nothing to do
5586}
Reid Kleckner0503a872013-12-05 01:23:43 +00005587void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5588 // nothing to do
5589}
Guy Benyei11169dd2012-12-18 14:30:41 +00005590void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5591 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5594 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5597 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5598}
5599void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5600 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5601 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5602}
5603void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5604 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5605 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5606 if (Record[Idx++])
5607 TL.setSizeExpr(Reader.ReadExpr(F));
5608 else
5609 TL.setSizeExpr(0);
5610}
5611void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5612 VisitArrayTypeLoc(TL);
5613}
5614void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5615 VisitArrayTypeLoc(TL);
5616}
5617void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5618 VisitArrayTypeLoc(TL);
5619}
5620void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5621 DependentSizedArrayTypeLoc TL) {
5622 VisitArrayTypeLoc(TL);
5623}
5624void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5625 DependentSizedExtVectorTypeLoc TL) {
5626 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5627}
5628void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5629 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5630}
5631void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5633}
5634void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5635 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5636 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5637 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005639 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5640 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005641 }
5642}
5643void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5644 VisitFunctionTypeLoc(TL);
5645}
5646void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5647 VisitFunctionTypeLoc(TL);
5648}
5649void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5654}
5655void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5656 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5657 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5658 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5661 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5662 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5663 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5664 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5665}
5666void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5667 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5668}
5669void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5670 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5671 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5672 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5673 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5674}
5675void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5676 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5677}
5678void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5682 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5683}
5684void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5685 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5686 if (TL.hasAttrOperand()) {
5687 SourceRange range;
5688 range.setBegin(ReadSourceLocation(Record, Idx));
5689 range.setEnd(ReadSourceLocation(Record, Idx));
5690 TL.setAttrOperandParensRange(range);
5691 }
5692 if (TL.hasAttrExprOperand()) {
5693 if (Record[Idx++])
5694 TL.setAttrExprOperand(Reader.ReadExpr(F));
5695 else
5696 TL.setAttrExprOperand(0);
5697 } else if (TL.hasAttrEnumOperand())
5698 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5699}
5700void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5701 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5702}
5703void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5704 SubstTemplateTypeParmTypeLoc TL) {
5705 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5706}
5707void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5708 SubstTemplateTypeParmPackTypeLoc TL) {
5709 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5710}
5711void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5712 TemplateSpecializationTypeLoc TL) {
5713 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5714 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5715 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5716 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5717 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5718 TL.setArgLocInfo(i,
5719 Reader.GetTemplateArgumentLocInfo(F,
5720 TL.getTypePtr()->getArg(i).getKind(),
5721 Record, Idx));
5722}
5723void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5724 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5725 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5728 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5729 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5730}
5731void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5732 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5733}
5734void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5735 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5736 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5737 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5738}
5739void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5740 DependentTemplateSpecializationTypeLoc TL) {
5741 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5742 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5743 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5744 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5745 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5746 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5747 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5748 TL.setArgLocInfo(I,
5749 Reader.GetTemplateArgumentLocInfo(F,
5750 TL.getTypePtr()->getArg(I).getKind(),
5751 Record, Idx));
5752}
5753void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5754 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5755}
5756void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5757 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5758}
5759void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5760 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5761 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5762 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5763 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5764 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5765}
5766void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5767 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5768}
5769void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5770 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5771 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5772 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5773}
5774
5775TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5776 const RecordData &Record,
5777 unsigned &Idx) {
5778 QualType InfoTy = readType(F, Record, Idx);
5779 if (InfoTy.isNull())
5780 return 0;
5781
5782 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5783 TypeLocReader TLR(*this, F, Record, Idx);
5784 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5785 TLR.Visit(TL);
5786 return TInfo;
5787}
5788
5789QualType ASTReader::GetType(TypeID ID) {
5790 unsigned FastQuals = ID & Qualifiers::FastMask;
5791 unsigned Index = ID >> Qualifiers::FastWidth;
5792
5793 if (Index < NUM_PREDEF_TYPE_IDS) {
5794 QualType T;
5795 switch ((PredefinedTypeIDs)Index) {
5796 case PREDEF_TYPE_NULL_ID: return QualType();
5797 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5798 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5799
5800 case PREDEF_TYPE_CHAR_U_ID:
5801 case PREDEF_TYPE_CHAR_S_ID:
5802 // FIXME: Check that the signedness of CharTy is correct!
5803 T = Context.CharTy;
5804 break;
5805
5806 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5807 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5808 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5809 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5810 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5811 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5812 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5813 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5814 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5815 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5816 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5817 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5818 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5819 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5820 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5821 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5822 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5823 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5824 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5825 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5826 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5827 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5828 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5829 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5830 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5831 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5832 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5833 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005834 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5835 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5836 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5837 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5838 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5839 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005840 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005841 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005842 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5843
5844 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5845 T = Context.getAutoRRefDeductType();
5846 break;
5847
5848 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5849 T = Context.ARCUnbridgedCastTy;
5850 break;
5851
5852 case PREDEF_TYPE_VA_LIST_TAG:
5853 T = Context.getVaListTagType();
5854 break;
5855
5856 case PREDEF_TYPE_BUILTIN_FN:
5857 T = Context.BuiltinFnTy;
5858 break;
5859 }
5860
5861 assert(!T.isNull() && "Unknown predefined type");
5862 return T.withFastQualifiers(FastQuals);
5863 }
5864
5865 Index -= NUM_PREDEF_TYPE_IDS;
5866 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5867 if (TypesLoaded[Index].isNull()) {
5868 TypesLoaded[Index] = readTypeRecord(Index);
5869 if (TypesLoaded[Index].isNull())
5870 return QualType();
5871
5872 TypesLoaded[Index]->setFromAST();
5873 if (DeserializationListener)
5874 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5875 TypesLoaded[Index]);
5876 }
5877
5878 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5879}
5880
5881QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5882 return GetType(getGlobalTypeID(F, LocalID));
5883}
5884
5885serialization::TypeID
5886ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5887 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5888 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5889
5890 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5891 return LocalID;
5892
5893 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5894 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5895 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5896
5897 unsigned GlobalIndex = LocalIndex + I->second;
5898 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5899}
5900
5901TemplateArgumentLocInfo
5902ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5903 TemplateArgument::ArgKind Kind,
5904 const RecordData &Record,
5905 unsigned &Index) {
5906 switch (Kind) {
5907 case TemplateArgument::Expression:
5908 return ReadExpr(F);
5909 case TemplateArgument::Type:
5910 return GetTypeSourceInfo(F, Record, Index);
5911 case TemplateArgument::Template: {
5912 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5913 Index);
5914 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5915 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5916 SourceLocation());
5917 }
5918 case TemplateArgument::TemplateExpansion: {
5919 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5920 Index);
5921 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5922 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5923 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5924 EllipsisLoc);
5925 }
5926 case TemplateArgument::Null:
5927 case TemplateArgument::Integral:
5928 case TemplateArgument::Declaration:
5929 case TemplateArgument::NullPtr:
5930 case TemplateArgument::Pack:
5931 // FIXME: Is this right?
5932 return TemplateArgumentLocInfo();
5933 }
5934 llvm_unreachable("unexpected template argument loc");
5935}
5936
5937TemplateArgumentLoc
5938ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5939 const RecordData &Record, unsigned &Index) {
5940 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5941
5942 if (Arg.getKind() == TemplateArgument::Expression) {
5943 if (Record[Index++]) // bool InfoHasSameExpr.
5944 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5945 }
5946 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5947 Record, Index));
5948}
5949
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005950const ASTTemplateArgumentListInfo*
5951ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5952 const RecordData &Record,
5953 unsigned &Index) {
5954 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5955 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5956 unsigned NumArgsAsWritten = Record[Index++];
5957 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5958 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5959 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5960 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5961}
5962
Guy Benyei11169dd2012-12-18 14:30:41 +00005963Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5964 return GetDecl(ID);
5965}
5966
Richard Smithcd45dbc2014-04-19 03:48:30 +00005967uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5968 const RecordData &Record,
5969 unsigned &Idx) {
5970 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5971 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005973 }
5974
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 unsigned LocalID = Record[Idx++];
5976 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5977}
5978
5979CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5980 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005981 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 SavedStreamPosition SavedPosition(Cursor);
5983 Cursor.JumpToBit(Loc.Offset);
5984 ReadingKindTracker ReadingKind(Read_Decl, *this);
5985 RecordData Record;
5986 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005987 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005989 Error("malformed AST file: missing C++ base specifiers");
Guy Benyei11169dd2012-12-18 14:30:41 +00005990 return 0;
5991 }
5992
5993 unsigned Idx = 0;
5994 unsigned NumBases = Record[Idx++];
5995 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5996 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5997 for (unsigned I = 0; I != NumBases; ++I)
5998 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5999 return Bases;
6000}
6001
6002serialization::DeclID
6003ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6004 if (LocalID < NUM_PREDEF_DECL_IDS)
6005 return LocalID;
6006
6007 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6008 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6009 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6010
6011 return LocalID + I->second;
6012}
6013
6014bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6015 ModuleFile &M) const {
6016 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6017 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6018 return &M == I->second;
6019}
6020
Douglas Gregor9f782892013-01-21 15:25:38 +00006021ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 if (!D->isFromASTFile())
6023 return 0;
6024 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6025 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6026 return I->second;
6027}
6028
6029SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6030 if (ID < NUM_PREDEF_DECL_IDS)
6031 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006032
Guy Benyei11169dd2012-12-18 14:30:41 +00006033 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6034
6035 if (Index > DeclsLoaded.size()) {
6036 Error("declaration ID out-of-range for AST file");
6037 return SourceLocation();
6038 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006039
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 if (Decl *D = DeclsLoaded[Index])
6041 return D->getLocation();
6042
6043 unsigned RawLocation = 0;
6044 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6045 return ReadSourceLocation(*Rec.F, RawLocation);
6046}
6047
Richard Smithcd45dbc2014-04-19 03:48:30 +00006048Decl *ASTReader::GetExistingDecl(DeclID ID) {
6049 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 switch ((PredefinedDeclIDs)ID) {
6051 case PREDEF_DECL_NULL_ID:
6052 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006053
Guy Benyei11169dd2012-12-18 14:30:41 +00006054 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6055 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006056
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 case PREDEF_DECL_OBJC_ID_ID:
6058 return Context.getObjCIdDecl();
6059
6060 case PREDEF_DECL_OBJC_SEL_ID:
6061 return Context.getObjCSelDecl();
6062
6063 case PREDEF_DECL_OBJC_CLASS_ID:
6064 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006065
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6067 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006068
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 case PREDEF_DECL_INT_128_ID:
6070 return Context.getInt128Decl();
6071
6072 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6073 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006074
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6076 return Context.getObjCInstanceTypeDecl();
6077
6078 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6079 return Context.getBuiltinVaListDecl();
6080 }
6081 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006082
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6084
6085 if (Index >= DeclsLoaded.size()) {
6086 assert(0 && "declaration ID out-of-range for AST file");
6087 Error("declaration ID out-of-range for AST file");
6088 return 0;
6089 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006090
6091 return DeclsLoaded[Index];
6092}
6093
6094Decl *ASTReader::GetDecl(DeclID ID) {
6095 if (ID < NUM_PREDEF_DECL_IDS)
6096 return GetExistingDecl(ID);
6097
6098 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6099
6100 if (Index >= DeclsLoaded.size()) {
6101 assert(0 && "declaration ID out-of-range for AST file");
6102 Error("declaration ID out-of-range for AST file");
6103 return 0;
6104 }
6105
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (!DeclsLoaded[Index]) {
6107 ReadDeclRecord(ID);
6108 if (DeserializationListener)
6109 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6110 }
6111
6112 return DeclsLoaded[Index];
6113}
6114
6115DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6116 DeclID GlobalID) {
6117 if (GlobalID < NUM_PREDEF_DECL_IDS)
6118 return GlobalID;
6119
6120 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6121 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6122 ModuleFile *Owner = I->second;
6123
6124 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6125 = M.GlobalToLocalDeclIDs.find(Owner);
6126 if (Pos == M.GlobalToLocalDeclIDs.end())
6127 return 0;
6128
6129 return GlobalID - Owner->BaseDeclID + Pos->second;
6130}
6131
6132serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6133 const RecordData &Record,
6134 unsigned &Idx) {
6135 if (Idx >= Record.size()) {
6136 Error("Corrupted AST file");
6137 return 0;
6138 }
6139
6140 return getGlobalDeclID(F, Record[Idx++]);
6141}
6142
6143/// \brief Resolve the offset of a statement into a statement.
6144///
6145/// This operation will read a new statement from the external
6146/// source each time it is called, and is meant to be used via a
6147/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6148Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6149 // Switch case IDs are per Decl.
6150 ClearSwitchCaseIDs();
6151
6152 // Offset here is a global offset across the entire chain.
6153 RecordLocation Loc = getLocalBitOffset(Offset);
6154 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6155 return ReadStmtFromStream(*Loc.F);
6156}
6157
6158namespace {
6159 class FindExternalLexicalDeclsVisitor {
6160 ASTReader &Reader;
6161 const DeclContext *DC;
6162 bool (*isKindWeWant)(Decl::Kind);
6163
6164 SmallVectorImpl<Decl*> &Decls;
6165 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6166
6167 public:
6168 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6169 bool (*isKindWeWant)(Decl::Kind),
6170 SmallVectorImpl<Decl*> &Decls)
6171 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6172 {
6173 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6174 PredefsVisited[I] = false;
6175 }
6176
6177 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6178 if (Preorder)
6179 return false;
6180
6181 FindExternalLexicalDeclsVisitor *This
6182 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6183
6184 ModuleFile::DeclContextInfosMap::iterator Info
6185 = M.DeclContextInfos.find(This->DC);
6186 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6187 return false;
6188
6189 // Load all of the declaration IDs
6190 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6191 *IDE = ID + Info->second.NumLexicalDecls;
6192 ID != IDE; ++ID) {
6193 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6194 continue;
6195
6196 // Don't add predefined declarations to the lexical context more
6197 // than once.
6198 if (ID->second < NUM_PREDEF_DECL_IDS) {
6199 if (This->PredefsVisited[ID->second])
6200 continue;
6201
6202 This->PredefsVisited[ID->second] = true;
6203 }
6204
6205 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6206 if (!This->DC->isDeclInLexicalTraversal(D))
6207 This->Decls.push_back(D);
6208 }
6209 }
6210
6211 return false;
6212 }
6213 };
6214}
6215
6216ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6217 bool (*isKindWeWant)(Decl::Kind),
6218 SmallVectorImpl<Decl*> &Decls) {
6219 // There might be lexical decls in multiple modules, for the TU at
6220 // least. Walk all of the modules in the order they were loaded.
6221 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6222 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6223 ++NumLexicalDeclContextsRead;
6224 return ELR_Success;
6225}
6226
6227namespace {
6228
6229class DeclIDComp {
6230 ASTReader &Reader;
6231 ModuleFile &Mod;
6232
6233public:
6234 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6235
6236 bool operator()(LocalDeclID L, LocalDeclID R) const {
6237 SourceLocation LHS = getLocation(L);
6238 SourceLocation RHS = getLocation(R);
6239 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6240 }
6241
6242 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6243 SourceLocation RHS = getLocation(R);
6244 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6245 }
6246
6247 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6248 SourceLocation LHS = getLocation(L);
6249 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6250 }
6251
6252 SourceLocation getLocation(LocalDeclID ID) const {
6253 return Reader.getSourceManager().getFileLoc(
6254 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6255 }
6256};
6257
6258}
6259
6260void ASTReader::FindFileRegionDecls(FileID File,
6261 unsigned Offset, unsigned Length,
6262 SmallVectorImpl<Decl *> &Decls) {
6263 SourceManager &SM = getSourceManager();
6264
6265 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6266 if (I == FileDeclIDs.end())
6267 return;
6268
6269 FileDeclsInfo &DInfo = I->second;
6270 if (DInfo.Decls.empty())
6271 return;
6272
6273 SourceLocation
6274 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6275 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6276
6277 DeclIDComp DIDComp(*this, *DInfo.Mod);
6278 ArrayRef<serialization::LocalDeclID>::iterator
6279 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6280 BeginLoc, DIDComp);
6281 if (BeginIt != DInfo.Decls.begin())
6282 --BeginIt;
6283
6284 // If we are pointing at a top-level decl inside an objc container, we need
6285 // to backtrack until we find it otherwise we will fail to report that the
6286 // region overlaps with an objc container.
6287 while (BeginIt != DInfo.Decls.begin() &&
6288 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6289 ->isTopLevelDeclInObjCContainer())
6290 --BeginIt;
6291
6292 ArrayRef<serialization::LocalDeclID>::iterator
6293 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6294 EndLoc, DIDComp);
6295 if (EndIt != DInfo.Decls.end())
6296 ++EndIt;
6297
6298 for (ArrayRef<serialization::LocalDeclID>::iterator
6299 DIt = BeginIt; DIt != EndIt; ++DIt)
6300 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6301}
6302
6303namespace {
6304 /// \brief ModuleFile visitor used to perform name lookup into a
6305 /// declaration context.
6306 class DeclContextNameLookupVisitor {
6307 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006308 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 DeclarationName Name;
6310 SmallVectorImpl<NamedDecl *> &Decls;
6311
6312 public:
6313 DeclContextNameLookupVisitor(ASTReader &Reader,
6314 SmallVectorImpl<const DeclContext *> &Contexts,
6315 DeclarationName Name,
6316 SmallVectorImpl<NamedDecl *> &Decls)
6317 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6318
6319 static bool visit(ModuleFile &M, void *UserData) {
6320 DeclContextNameLookupVisitor *This
6321 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6322
6323 // Check whether we have any visible declaration information for
6324 // this context in this module.
6325 ModuleFile::DeclContextInfosMap::iterator Info;
6326 bool FoundInfo = false;
6327 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6328 Info = M.DeclContextInfos.find(This->Contexts[I]);
6329 if (Info != M.DeclContextInfos.end() &&
6330 Info->second.NameLookupTableData) {
6331 FoundInfo = true;
6332 break;
6333 }
6334 }
6335
6336 if (!FoundInfo)
6337 return false;
6338
6339 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006340 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006341 Info->second.NameLookupTableData;
6342 ASTDeclContextNameLookupTable::iterator Pos
6343 = LookupTable->find(This->Name);
6344 if (Pos == LookupTable->end())
6345 return false;
6346
6347 bool FoundAnything = false;
6348 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6349 for (; Data.first != Data.second; ++Data.first) {
6350 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6351 if (!ND)
6352 continue;
6353
6354 if (ND->getDeclName() != This->Name) {
6355 // A name might be null because the decl's redeclarable part is
6356 // currently read before reading its name. The lookup is triggered by
6357 // building that decl (likely indirectly), and so it is later in the
6358 // sense of "already existing" and can be ignored here.
6359 continue;
6360 }
6361
6362 // Record this declaration.
6363 FoundAnything = true;
6364 This->Decls.push_back(ND);
6365 }
6366
6367 return FoundAnything;
6368 }
6369 };
6370}
6371
Douglas Gregor9f782892013-01-21 15:25:38 +00006372/// \brief Retrieve the "definitive" module file for the definition of the
6373/// given declaration context, if there is one.
6374///
6375/// The "definitive" module file is the only place where we need to look to
6376/// find information about the declarations within the given declaration
6377/// context. For example, C++ and Objective-C classes, C structs/unions, and
6378/// Objective-C protocols, categories, and extensions are all defined in a
6379/// single place in the source code, so they have definitive module files
6380/// associated with them. C++ namespaces, on the other hand, can have
6381/// definitions in multiple different module files.
6382///
6383/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6384/// NDEBUG checking.
6385static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6386 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006387 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6388 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006389
6390 return 0;
6391}
6392
Richard Smith9ce12e32013-02-07 03:30:24 +00006393bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006394ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6395 DeclarationName Name) {
6396 assert(DC->hasExternalVisibleStorage() &&
6397 "DeclContext has no visible decls in storage");
6398 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006399 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006400
6401 SmallVector<NamedDecl *, 64> Decls;
6402
6403 // Compute the declaration contexts we need to look into. Multiple such
6404 // declaration contexts occur when two declaration contexts from disjoint
6405 // modules get merged, e.g., when two namespaces with the same name are
6406 // independently defined in separate modules.
6407 SmallVector<const DeclContext *, 2> Contexts;
6408 Contexts.push_back(DC);
6409
6410 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006411 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 if (Merged != MergedDecls.end()) {
6413 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6414 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6415 }
6416 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006417 if (isa<CXXRecordDecl>(DC)) {
6418 auto Merged = MergedLookups.find(DC);
6419 if (Merged != MergedLookups.end())
6420 Contexts.insert(Contexts.end(), Merged->second.begin(),
6421 Merged->second.end());
6422 }
6423
Guy Benyei11169dd2012-12-18 14:30:41 +00006424 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006425
6426 // If we can definitively determine which module file to look into,
6427 // only look there. Otherwise, look in all module files.
6428 ModuleFile *Definitive;
6429 if (Contexts.size() == 1 &&
6430 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6431 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6432 } else {
6433 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6434 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 ++NumVisibleDeclContextsRead;
6436 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006437 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006438}
6439
6440namespace {
6441 /// \brief ModuleFile visitor used to retrieve all visible names in a
6442 /// declaration context.
6443 class DeclContextAllNamesVisitor {
6444 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006445 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006446 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006447 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006448
6449 public:
6450 DeclContextAllNamesVisitor(ASTReader &Reader,
6451 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006452 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006453 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006454
6455 static bool visit(ModuleFile &M, void *UserData) {
6456 DeclContextAllNamesVisitor *This
6457 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6458
6459 // Check whether we have any visible declaration information for
6460 // this context in this module.
6461 ModuleFile::DeclContextInfosMap::iterator Info;
6462 bool FoundInfo = false;
6463 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6464 Info = M.DeclContextInfos.find(This->Contexts[I]);
6465 if (Info != M.DeclContextInfos.end() &&
6466 Info->second.NameLookupTableData) {
6467 FoundInfo = true;
6468 break;
6469 }
6470 }
6471
6472 if (!FoundInfo)
6473 return false;
6474
Richard Smith52e3fba2014-03-11 07:17:35 +00006475 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 Info->second.NameLookupTableData;
6477 bool FoundAnything = false;
6478 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006479 I = LookupTable->data_begin(), E = LookupTable->data_end();
6480 I != E;
6481 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 ASTDeclContextNameLookupTrait::data_type Data = *I;
6483 for (; Data.first != Data.second; ++Data.first) {
6484 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6485 *Data.first);
6486 if (!ND)
6487 continue;
6488
6489 // Record this declaration.
6490 FoundAnything = true;
6491 This->Decls[ND->getDeclName()].push_back(ND);
6492 }
6493 }
6494
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006495 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006496 }
6497 };
6498}
6499
6500void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6501 if (!DC->hasExternalVisibleStorage())
6502 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006503 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006504
6505 // Compute the declaration contexts we need to look into. Multiple such
6506 // declaration contexts occur when two declaration contexts from disjoint
6507 // modules get merged, e.g., when two namespaces with the same name are
6508 // independently defined in separate modules.
6509 SmallVector<const DeclContext *, 2> Contexts;
6510 Contexts.push_back(DC);
6511
6512 if (DC->isNamespace()) {
6513 MergedDeclsMap::iterator Merged
6514 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6515 if (Merged != MergedDecls.end()) {
6516 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6517 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6518 }
6519 }
6520
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006521 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6522 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6524 ++NumVisibleDeclContextsRead;
6525
Craig Topper79be4cd2013-07-05 04:33:53 +00006526 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006527 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6528 }
6529 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6530}
6531
6532/// \brief Under non-PCH compilation the consumer receives the objc methods
6533/// before receiving the implementation, and codegen depends on this.
6534/// We simulate this by deserializing and passing to consumer the methods of the
6535/// implementation before passing the deserialized implementation decl.
6536static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6537 ASTConsumer *Consumer) {
6538 assert(ImplD && Consumer);
6539
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006540 for (auto *I : ImplD->methods())
6541 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006542
6543 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6544}
6545
6546void ASTReader::PassInterestingDeclsToConsumer() {
6547 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006548
6549 if (PassingDeclsToConsumer)
6550 return;
6551
6552 // Guard variable to avoid recursively redoing the process of passing
6553 // decls to consumer.
6554 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6555 true);
6556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557 while (!InterestingDecls.empty()) {
6558 Decl *D = InterestingDecls.front();
6559 InterestingDecls.pop_front();
6560
6561 PassInterestingDeclToConsumer(D);
6562 }
6563}
6564
6565void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6566 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6567 PassObjCImplDeclToConsumer(ImplD, Consumer);
6568 else
6569 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6570}
6571
6572void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6573 this->Consumer = Consumer;
6574
6575 if (!Consumer)
6576 return;
6577
Ben Langmuir332aafe2014-01-31 01:06:56 +00006578 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 // Force deserialization of this decl, which will cause it to be queued for
6580 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006581 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006582 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006583 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006584
6585 PassInterestingDeclsToConsumer();
6586}
6587
6588void ASTReader::PrintStats() {
6589 std::fprintf(stderr, "*** AST File Statistics:\n");
6590
6591 unsigned NumTypesLoaded
6592 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6593 QualType());
6594 unsigned NumDeclsLoaded
6595 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6596 (Decl *)0);
6597 unsigned NumIdentifiersLoaded
6598 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6599 IdentifiersLoaded.end(),
6600 (IdentifierInfo *)0);
6601 unsigned NumMacrosLoaded
6602 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6603 MacrosLoaded.end(),
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006604 (MacroInfo *)0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 unsigned NumSelectorsLoaded
6606 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6607 SelectorsLoaded.end(),
6608 Selector());
6609
6610 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6611 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6612 NumSLocEntriesRead, TotalNumSLocEntries,
6613 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6614 if (!TypesLoaded.empty())
6615 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6616 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6617 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6618 if (!DeclsLoaded.empty())
6619 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6620 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6621 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6622 if (!IdentifiersLoaded.empty())
6623 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6624 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6625 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6626 if (!MacrosLoaded.empty())
6627 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6628 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6629 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6630 if (!SelectorsLoaded.empty())
6631 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6632 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6633 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6634 if (TotalNumStatements)
6635 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6636 NumStatementsRead, TotalNumStatements,
6637 ((float)NumStatementsRead/TotalNumStatements * 100));
6638 if (TotalNumMacros)
6639 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6640 NumMacrosRead, TotalNumMacros,
6641 ((float)NumMacrosRead/TotalNumMacros * 100));
6642 if (TotalLexicalDeclContexts)
6643 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6644 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6645 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6646 * 100));
6647 if (TotalVisibleDeclContexts)
6648 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6649 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6650 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6651 * 100));
6652 if (TotalNumMethodPoolEntries) {
6653 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6654 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6655 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6656 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006657 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006658 if (NumMethodPoolLookups) {
6659 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6660 NumMethodPoolHits, NumMethodPoolLookups,
6661 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6662 }
6663 if (NumMethodPoolTableLookups) {
6664 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6665 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6666 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6667 * 100.0));
6668 }
6669
Douglas Gregor00a50f72013-01-25 00:38:33 +00006670 if (NumIdentifierLookupHits) {
6671 std::fprintf(stderr,
6672 " %u / %u identifier table lookups succeeded (%f%%)\n",
6673 NumIdentifierLookupHits, NumIdentifierLookups,
6674 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6675 }
6676
Douglas Gregore060e572013-01-25 01:03:03 +00006677 if (GlobalIndex) {
6678 std::fprintf(stderr, "\n");
6679 GlobalIndex->printStats();
6680 }
6681
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 std::fprintf(stderr, "\n");
6683 dump();
6684 std::fprintf(stderr, "\n");
6685}
6686
6687template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6688static void
6689dumpModuleIDMap(StringRef Name,
6690 const ContinuousRangeMap<Key, ModuleFile *,
6691 InitialCapacity> &Map) {
6692 if (Map.begin() == Map.end())
6693 return;
6694
6695 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6696 llvm::errs() << Name << ":\n";
6697 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6698 I != IEnd; ++I) {
6699 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6700 << "\n";
6701 }
6702}
6703
6704void ASTReader::dump() {
6705 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6706 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6707 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6708 dumpModuleIDMap("Global type map", GlobalTypeMap);
6709 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6710 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6711 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6712 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6713 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6714 dumpModuleIDMap("Global preprocessed entity map",
6715 GlobalPreprocessedEntityMap);
6716
6717 llvm::errs() << "\n*** PCH/Modules Loaded:";
6718 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6719 MEnd = ModuleMgr.end();
6720 M != MEnd; ++M)
6721 (*M)->dump();
6722}
6723
6724/// Return the amount of memory used by memory buffers, breaking down
6725/// by heap-backed versus mmap'ed memory.
6726void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6727 for (ModuleConstIterator I = ModuleMgr.begin(),
6728 E = ModuleMgr.end(); I != E; ++I) {
6729 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6730 size_t bytes = buf->getBufferSize();
6731 switch (buf->getBufferKind()) {
6732 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6733 sizes.malloc_bytes += bytes;
6734 break;
6735 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6736 sizes.mmap_bytes += bytes;
6737 break;
6738 }
6739 }
6740 }
6741}
6742
6743void ASTReader::InitializeSema(Sema &S) {
6744 SemaObj = &S;
6745 S.addExternalSource(this);
6746
6747 // Makes sure any declarations that were deserialized "too early"
6748 // still get added to the identifier's declaration chains.
6749 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006750 pushExternalDeclIntoScope(PreloadedDecls[I],
6751 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 }
6753 PreloadedDecls.clear();
6754
Richard Smith3d8e97e2013-10-18 06:54:39 +00006755 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 if (!FPPragmaOptions.empty()) {
6757 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6758 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6759 }
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 (!OpenCLExtensions.empty()) {
6763 unsigned I = 0;
6764#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6765#include "clang/Basic/OpenCLExtensions.def"
6766
6767 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6768 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006769
6770 UpdateSema();
6771}
6772
6773void ASTReader::UpdateSema() {
6774 assert(SemaObj && "no Sema to update");
6775
6776 // Load the offsets of the declarations that Sema references.
6777 // They will be lazily deserialized when needed.
6778 if (!SemaDeclRefs.empty()) {
6779 assert(SemaDeclRefs.size() % 2 == 0);
6780 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6781 if (!SemaObj->StdNamespace)
6782 SemaObj->StdNamespace = SemaDeclRefs[I];
6783 if (!SemaObj->StdBadAlloc)
6784 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6785 }
6786 SemaDeclRefs.clear();
6787 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006788}
6789
6790IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6791 // Note that we are loading an identifier.
6792 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006793 StringRef Name(NameStart, NameEnd - NameStart);
6794
6795 // If there is a global index, look there first to determine which modules
6796 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006797 GlobalModuleIndex::HitSet Hits;
6798 GlobalModuleIndex::HitSet *HitsPtr = 0;
Douglas Gregore060e572013-01-25 01:03:03 +00006799 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006800 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6801 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006802 }
6803 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006804 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006805 NumIdentifierLookups,
6806 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006807 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006808 IdentifierInfo *II = Visitor.getIdentifierInfo();
6809 markIdentifierUpToDate(II);
6810 return II;
6811}
6812
6813namespace clang {
6814 /// \brief An identifier-lookup iterator that enumerates all of the
6815 /// identifiers stored within a set of AST files.
6816 class ASTIdentifierIterator : public IdentifierIterator {
6817 /// \brief The AST reader whose identifiers are being enumerated.
6818 const ASTReader &Reader;
6819
6820 /// \brief The current index into the chain of AST files stored in
6821 /// the AST reader.
6822 unsigned Index;
6823
6824 /// \brief The current position within the identifier lookup table
6825 /// of the current AST file.
6826 ASTIdentifierLookupTable::key_iterator Current;
6827
6828 /// \brief The end position within the identifier lookup table of
6829 /// the current AST file.
6830 ASTIdentifierLookupTable::key_iterator End;
6831
6832 public:
6833 explicit ASTIdentifierIterator(const ASTReader &Reader);
6834
Craig Topper3e89dfe2014-03-13 02:13:41 +00006835 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006836 };
6837}
6838
6839ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6840 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6841 ASTIdentifierLookupTable *IdTable
6842 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6843 Current = IdTable->key_begin();
6844 End = IdTable->key_end();
6845}
6846
6847StringRef ASTIdentifierIterator::Next() {
6848 while (Current == End) {
6849 // If we have exhausted all of our AST files, we're done.
6850 if (Index == 0)
6851 return StringRef();
6852
6853 --Index;
6854 ASTIdentifierLookupTable *IdTable
6855 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6856 IdentifierLookupTable;
6857 Current = IdTable->key_begin();
6858 End = IdTable->key_end();
6859 }
6860
6861 // We have any identifiers remaining in the current AST file; return
6862 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006863 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006865 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006866}
6867
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006868IdentifierIterator *ASTReader::getIdentifiers() {
6869 if (!loadGlobalIndex())
6870 return GlobalIndex->createIdentifierIterator();
6871
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 return new ASTIdentifierIterator(*this);
6873}
6874
6875namespace clang { namespace serialization {
6876 class ReadMethodPoolVisitor {
6877 ASTReader &Reader;
6878 Selector Sel;
6879 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006880 unsigned InstanceBits;
6881 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006882 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6883 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006884
6885 public:
6886 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6887 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006888 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6889 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006890
6891 static bool visit(ModuleFile &M, void *UserData) {
6892 ReadMethodPoolVisitor *This
6893 = static_cast<ReadMethodPoolVisitor *>(UserData);
6894
6895 if (!M.SelectorLookupTable)
6896 return false;
6897
6898 // If we've already searched this module file, skip it now.
6899 if (M.Generation <= This->PriorGeneration)
6900 return true;
6901
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006902 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 ASTSelectorLookupTable *PoolTable
6904 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6905 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6906 if (Pos == PoolTable->end())
6907 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006908
6909 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 ++This->Reader.NumSelectorsRead;
6911 // FIXME: Not quite happy with the statistics here. We probably should
6912 // disable this tracking when called via LoadSelector.
6913 // Also, should entries without methods count as misses?
6914 ++This->Reader.NumMethodPoolEntriesRead;
6915 ASTSelectorLookupTrait::data_type Data = *Pos;
6916 if (This->Reader.DeserializationListener)
6917 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6918 This->Sel);
6919
6920 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6921 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006922 This->InstanceBits = Data.InstanceBits;
6923 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 return true;
6925 }
6926
6927 /// \brief Retrieve the instance methods found by this visitor.
6928 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6929 return InstanceMethods;
6930 }
6931
6932 /// \brief Retrieve the instance methods found by this visitor.
6933 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6934 return FactoryMethods;
6935 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006936
6937 unsigned getInstanceBits() const { return InstanceBits; }
6938 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 };
6940} } // end namespace clang::serialization
6941
6942/// \brief Add the given set of methods to the method list.
6943static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6944 ObjCMethodList &List) {
6945 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6946 S.addMethodToGlobalList(&List, Methods[I]);
6947 }
6948}
6949
6950void ASTReader::ReadMethodPool(Selector Sel) {
6951 // Get the selector generation and update it to the current generation.
6952 unsigned &Generation = SelectorGeneration[Sel];
6953 unsigned PriorGeneration = Generation;
6954 Generation = CurrentGeneration;
6955
6956 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006957 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6959 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6960
6961 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006962 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006964
6965 ++NumMethodPoolHits;
6966
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 if (!getSema())
6968 return;
6969
6970 Sema &S = *getSema();
6971 Sema::GlobalMethodPool::iterator Pos
6972 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6973
6974 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6975 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006976 Pos->second.first.setBits(Visitor.getInstanceBits());
6977 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00006978}
6979
6980void ASTReader::ReadKnownNamespaces(
6981 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6982 Namespaces.clear();
6983
6984 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6985 if (NamespaceDecl *Namespace
6986 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6987 Namespaces.push_back(Namespace);
6988 }
6989}
6990
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006991void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00006992 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006993 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6994 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00006995 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00006996 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00006997 Undefined.insert(std::make_pair(D, Loc));
6998 }
6999}
Nick Lewycky8334af82013-01-26 00:35:08 +00007000
Guy Benyei11169dd2012-12-18 14:30:41 +00007001void ASTReader::ReadTentativeDefinitions(
7002 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7003 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7004 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7005 if (Var)
7006 TentativeDefs.push_back(Var);
7007 }
7008 TentativeDefinitions.clear();
7009}
7010
7011void ASTReader::ReadUnusedFileScopedDecls(
7012 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7013 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7014 DeclaratorDecl *D
7015 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7016 if (D)
7017 Decls.push_back(D);
7018 }
7019 UnusedFileScopedDecls.clear();
7020}
7021
7022void ASTReader::ReadDelegatingConstructors(
7023 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7024 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7025 CXXConstructorDecl *D
7026 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7027 if (D)
7028 Decls.push_back(D);
7029 }
7030 DelegatingCtorDecls.clear();
7031}
7032
7033void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7034 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7035 TypedefNameDecl *D
7036 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7037 if (D)
7038 Decls.push_back(D);
7039 }
7040 ExtVectorDecls.clear();
7041}
7042
7043void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7044 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7045 CXXRecordDecl *D
7046 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7047 if (D)
7048 Decls.push_back(D);
7049 }
7050 DynamicClasses.clear();
7051}
7052
7053void
Richard Smith78165b52013-01-10 23:43:47 +00007054ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7055 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7056 NamedDecl *D
7057 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007058 if (D)
7059 Decls.push_back(D);
7060 }
Richard Smith78165b52013-01-10 23:43:47 +00007061 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007062}
7063
7064void ASTReader::ReadReferencedSelectors(
7065 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7066 if (ReferencedSelectorsData.empty())
7067 return;
7068
7069 // If there are @selector references added them to its pool. This is for
7070 // implementation of -Wselector.
7071 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7072 unsigned I = 0;
7073 while (I < DataSize) {
7074 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7075 SourceLocation SelLoc
7076 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7077 Sels.push_back(std::make_pair(Sel, SelLoc));
7078 }
7079 ReferencedSelectorsData.clear();
7080}
7081
7082void ASTReader::ReadWeakUndeclaredIdentifiers(
7083 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7084 if (WeakUndeclaredIdentifiers.empty())
7085 return;
7086
7087 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7088 IdentifierInfo *WeakId
7089 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7090 IdentifierInfo *AliasId
7091 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7092 SourceLocation Loc
7093 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7094 bool Used = WeakUndeclaredIdentifiers[I++];
7095 WeakInfo WI(AliasId, Loc);
7096 WI.setUsed(Used);
7097 WeakIDs.push_back(std::make_pair(WeakId, WI));
7098 }
7099 WeakUndeclaredIdentifiers.clear();
7100}
7101
7102void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7103 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7104 ExternalVTableUse VT;
7105 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7106 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7107 VT.DefinitionRequired = VTableUses[Idx++];
7108 VTables.push_back(VT);
7109 }
7110
7111 VTableUses.clear();
7112}
7113
7114void ASTReader::ReadPendingInstantiations(
7115 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7116 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7117 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7118 SourceLocation Loc
7119 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7120
7121 Pending.push_back(std::make_pair(D, Loc));
7122 }
7123 PendingInstantiations.clear();
7124}
7125
Richard Smithe40f2ba2013-08-07 21:41:30 +00007126void ASTReader::ReadLateParsedTemplates(
7127 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7128 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7129 /* In loop */) {
7130 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7131
7132 LateParsedTemplate *LT = new LateParsedTemplate;
7133 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7134
7135 ModuleFile *F = getOwningModuleFile(LT->D);
7136 assert(F && "No module");
7137
7138 unsigned TokN = LateParsedTemplates[Idx++];
7139 LT->Toks.reserve(TokN);
7140 for (unsigned T = 0; T < TokN; ++T)
7141 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7142
7143 LPTMap[FD] = LT;
7144 }
7145
7146 LateParsedTemplates.clear();
7147}
7148
Guy Benyei11169dd2012-12-18 14:30:41 +00007149void ASTReader::LoadSelector(Selector Sel) {
7150 // It would be complicated to avoid reading the methods anyway. So don't.
7151 ReadMethodPool(Sel);
7152}
7153
7154void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7155 assert(ID && "Non-zero identifier ID required");
7156 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7157 IdentifiersLoaded[ID - 1] = II;
7158 if (DeserializationListener)
7159 DeserializationListener->IdentifierRead(ID, II);
7160}
7161
7162/// \brief Set the globally-visible declarations associated with the given
7163/// identifier.
7164///
7165/// If the AST reader is currently in a state where the given declaration IDs
7166/// cannot safely be resolved, they are queued until it is safe to resolve
7167/// them.
7168///
7169/// \param II an IdentifierInfo that refers to one or more globally-visible
7170/// declarations.
7171///
7172/// \param DeclIDs the set of declaration IDs with the name @p II that are
7173/// visible at global scope.
7174///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007175/// \param Decls if non-null, this vector will be populated with the set of
7176/// deserialized declarations. These declarations will not be pushed into
7177/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007178void
7179ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7180 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007181 SmallVectorImpl<Decl *> *Decls) {
7182 if (NumCurrentElementsDeserializing && !Decls) {
7183 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 return;
7185 }
7186
7187 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7188 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7189 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007190 // If we're simply supposed to record the declarations, do so now.
7191 if (Decls) {
7192 Decls->push_back(D);
7193 continue;
7194 }
7195
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 // Introduce this declaration into the translation-unit scope
7197 // and add it to the declaration chain for this identifier, so
7198 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007199 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 } else {
7201 // Queue this declaration so that it will be added to the
7202 // translation unit scope and identifier's declaration chain
7203 // once a Sema object is known.
7204 PreloadedDecls.push_back(D);
7205 }
7206 }
7207}
7208
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007209IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 if (ID == 0)
7211 return 0;
7212
7213 if (IdentifiersLoaded.empty()) {
7214 Error("no identifier table in AST file");
7215 return 0;
7216 }
7217
7218 ID -= 1;
7219 if (!IdentifiersLoaded[ID]) {
7220 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7221 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7222 ModuleFile *M = I->second;
7223 unsigned Index = ID - M->BaseIdentifierID;
7224 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7225
7226 // All of the strings in the AST file are preceded by a 16-bit length.
7227 // Extract that 16-bit length to avoid having to execute strlen().
7228 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7229 // unsigned integers. This is important to avoid integer overflow when
7230 // we cast them to 'unsigned'.
7231 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7232 unsigned StrLen = (((unsigned) StrLenPtr[0])
7233 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007234 IdentifiersLoaded[ID]
7235 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 if (DeserializationListener)
7237 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7238 }
7239
7240 return IdentifiersLoaded[ID];
7241}
7242
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007243IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7244 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007245}
7246
7247IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7248 if (LocalID < NUM_PREDEF_IDENT_IDS)
7249 return LocalID;
7250
7251 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7252 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7253 assert(I != M.IdentifierRemap.end()
7254 && "Invalid index into identifier index remap");
7255
7256 return LocalID + I->second;
7257}
7258
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007259MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 if (ID == 0)
7261 return 0;
7262
7263 if (MacrosLoaded.empty()) {
7264 Error("no macro table in AST file");
7265 return 0;
7266 }
7267
7268 ID -= NUM_PREDEF_MACRO_IDS;
7269 if (!MacrosLoaded[ID]) {
7270 GlobalMacroMapType::iterator I
7271 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7272 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7273 ModuleFile *M = I->second;
7274 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007275 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7276
7277 if (DeserializationListener)
7278 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7279 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 }
7281
7282 return MacrosLoaded[ID];
7283}
7284
7285MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7286 if (LocalID < NUM_PREDEF_MACRO_IDS)
7287 return LocalID;
7288
7289 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7290 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7291 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7292
7293 return LocalID + I->second;
7294}
7295
7296serialization::SubmoduleID
7297ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7298 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7299 return LocalID;
7300
7301 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7302 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7303 assert(I != M.SubmoduleRemap.end()
7304 && "Invalid index into submodule index remap");
7305
7306 return LocalID + I->second;
7307}
7308
7309Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7310 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7311 assert(GlobalID == 0 && "Unhandled global submodule ID");
7312 return 0;
7313 }
7314
7315 if (GlobalID > SubmodulesLoaded.size()) {
7316 Error("submodule ID out of range in AST file");
7317 return 0;
7318 }
7319
7320 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7321}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007322
7323Module *ASTReader::getModule(unsigned ID) {
7324 return getSubmodule(ID);
7325}
7326
Guy Benyei11169dd2012-12-18 14:30:41 +00007327Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7328 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7329}
7330
7331Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7332 if (ID == 0)
7333 return Selector();
7334
7335 if (ID > SelectorsLoaded.size()) {
7336 Error("selector ID out of range in AST file");
7337 return Selector();
7338 }
7339
7340 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7341 // Load this selector from the selector table.
7342 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7343 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7344 ModuleFile &M = *I->second;
7345 ASTSelectorLookupTrait Trait(*this, M);
7346 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7347 SelectorsLoaded[ID - 1] =
7348 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7349 if (DeserializationListener)
7350 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7351 }
7352
7353 return SelectorsLoaded[ID - 1];
7354}
7355
7356Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7357 return DecodeSelector(ID);
7358}
7359
7360uint32_t ASTReader::GetNumExternalSelectors() {
7361 // ID 0 (the null selector) is considered an external selector.
7362 return getTotalNumSelectors() + 1;
7363}
7364
7365serialization::SelectorID
7366ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7367 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7368 return LocalID;
7369
7370 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7371 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7372 assert(I != M.SelectorRemap.end()
7373 && "Invalid index into selector index remap");
7374
7375 return LocalID + I->second;
7376}
7377
7378DeclarationName
7379ASTReader::ReadDeclarationName(ModuleFile &F,
7380 const RecordData &Record, unsigned &Idx) {
7381 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7382 switch (Kind) {
7383 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007384 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007385
7386 case DeclarationName::ObjCZeroArgSelector:
7387 case DeclarationName::ObjCOneArgSelector:
7388 case DeclarationName::ObjCMultiArgSelector:
7389 return DeclarationName(ReadSelector(F, Record, Idx));
7390
7391 case DeclarationName::CXXConstructorName:
7392 return Context.DeclarationNames.getCXXConstructorName(
7393 Context.getCanonicalType(readType(F, Record, Idx)));
7394
7395 case DeclarationName::CXXDestructorName:
7396 return Context.DeclarationNames.getCXXDestructorName(
7397 Context.getCanonicalType(readType(F, Record, Idx)));
7398
7399 case DeclarationName::CXXConversionFunctionName:
7400 return Context.DeclarationNames.getCXXConversionFunctionName(
7401 Context.getCanonicalType(readType(F, Record, Idx)));
7402
7403 case DeclarationName::CXXOperatorName:
7404 return Context.DeclarationNames.getCXXOperatorName(
7405 (OverloadedOperatorKind)Record[Idx++]);
7406
7407 case DeclarationName::CXXLiteralOperatorName:
7408 return Context.DeclarationNames.getCXXLiteralOperatorName(
7409 GetIdentifierInfo(F, Record, Idx));
7410
7411 case DeclarationName::CXXUsingDirective:
7412 return DeclarationName::getUsingDirectiveName();
7413 }
7414
7415 llvm_unreachable("Invalid NameKind!");
7416}
7417
7418void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7419 DeclarationNameLoc &DNLoc,
7420 DeclarationName Name,
7421 const RecordData &Record, unsigned &Idx) {
7422 switch (Name.getNameKind()) {
7423 case DeclarationName::CXXConstructorName:
7424 case DeclarationName::CXXDestructorName:
7425 case DeclarationName::CXXConversionFunctionName:
7426 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7427 break;
7428
7429 case DeclarationName::CXXOperatorName:
7430 DNLoc.CXXOperatorName.BeginOpNameLoc
7431 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7432 DNLoc.CXXOperatorName.EndOpNameLoc
7433 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7434 break;
7435
7436 case DeclarationName::CXXLiteralOperatorName:
7437 DNLoc.CXXLiteralOperatorName.OpNameLoc
7438 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7439 break;
7440
7441 case DeclarationName::Identifier:
7442 case DeclarationName::ObjCZeroArgSelector:
7443 case DeclarationName::ObjCOneArgSelector:
7444 case DeclarationName::ObjCMultiArgSelector:
7445 case DeclarationName::CXXUsingDirective:
7446 break;
7447 }
7448}
7449
7450void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7451 DeclarationNameInfo &NameInfo,
7452 const RecordData &Record, unsigned &Idx) {
7453 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7454 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7455 DeclarationNameLoc DNLoc;
7456 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7457 NameInfo.setInfo(DNLoc);
7458}
7459
7460void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7461 const RecordData &Record, unsigned &Idx) {
7462 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7463 unsigned NumTPLists = Record[Idx++];
7464 Info.NumTemplParamLists = NumTPLists;
7465 if (NumTPLists) {
7466 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7467 for (unsigned i=0; i != NumTPLists; ++i)
7468 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7469 }
7470}
7471
7472TemplateName
7473ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7474 unsigned &Idx) {
7475 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7476 switch (Kind) {
7477 case TemplateName::Template:
7478 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7479
7480 case TemplateName::OverloadedTemplate: {
7481 unsigned size = Record[Idx++];
7482 UnresolvedSet<8> Decls;
7483 while (size--)
7484 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7485
7486 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7487 }
7488
7489 case TemplateName::QualifiedTemplate: {
7490 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7491 bool hasTemplKeyword = Record[Idx++];
7492 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7493 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7494 }
7495
7496 case TemplateName::DependentTemplate: {
7497 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7498 if (Record[Idx++]) // isIdentifier
7499 return Context.getDependentTemplateName(NNS,
7500 GetIdentifierInfo(F, Record,
7501 Idx));
7502 return Context.getDependentTemplateName(NNS,
7503 (OverloadedOperatorKind)Record[Idx++]);
7504 }
7505
7506 case TemplateName::SubstTemplateTemplateParm: {
7507 TemplateTemplateParmDecl *param
7508 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7509 if (!param) return TemplateName();
7510 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7511 return Context.getSubstTemplateTemplateParm(param, replacement);
7512 }
7513
7514 case TemplateName::SubstTemplateTemplateParmPack: {
7515 TemplateTemplateParmDecl *Param
7516 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7517 if (!Param)
7518 return TemplateName();
7519
7520 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7521 if (ArgPack.getKind() != TemplateArgument::Pack)
7522 return TemplateName();
7523
7524 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7525 }
7526 }
7527
7528 llvm_unreachable("Unhandled template name kind!");
7529}
7530
7531TemplateArgument
7532ASTReader::ReadTemplateArgument(ModuleFile &F,
7533 const RecordData &Record, unsigned &Idx) {
7534 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7535 switch (Kind) {
7536 case TemplateArgument::Null:
7537 return TemplateArgument();
7538 case TemplateArgument::Type:
7539 return TemplateArgument(readType(F, Record, Idx));
7540 case TemplateArgument::Declaration: {
7541 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7542 bool ForReferenceParam = Record[Idx++];
7543 return TemplateArgument(D, ForReferenceParam);
7544 }
7545 case TemplateArgument::NullPtr:
7546 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7547 case TemplateArgument::Integral: {
7548 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7549 QualType T = readType(F, Record, Idx);
7550 return TemplateArgument(Context, Value, T);
7551 }
7552 case TemplateArgument::Template:
7553 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7554 case TemplateArgument::TemplateExpansion: {
7555 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007556 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007557 if (unsigned NumExpansions = Record[Idx++])
7558 NumTemplateExpansions = NumExpansions - 1;
7559 return TemplateArgument(Name, NumTemplateExpansions);
7560 }
7561 case TemplateArgument::Expression:
7562 return TemplateArgument(ReadExpr(F));
7563 case TemplateArgument::Pack: {
7564 unsigned NumArgs = Record[Idx++];
7565 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7566 for (unsigned I = 0; I != NumArgs; ++I)
7567 Args[I] = ReadTemplateArgument(F, Record, Idx);
7568 return TemplateArgument(Args, NumArgs);
7569 }
7570 }
7571
7572 llvm_unreachable("Unhandled template argument kind!");
7573}
7574
7575TemplateParameterList *
7576ASTReader::ReadTemplateParameterList(ModuleFile &F,
7577 const RecordData &Record, unsigned &Idx) {
7578 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7579 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7580 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7581
7582 unsigned NumParams = Record[Idx++];
7583 SmallVector<NamedDecl *, 16> Params;
7584 Params.reserve(NumParams);
7585 while (NumParams--)
7586 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7587
7588 TemplateParameterList* TemplateParams =
7589 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7590 Params.data(), Params.size(), RAngleLoc);
7591 return TemplateParams;
7592}
7593
7594void
7595ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007596ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 ModuleFile &F, const RecordData &Record,
7598 unsigned &Idx) {
7599 unsigned NumTemplateArgs = Record[Idx++];
7600 TemplArgs.reserve(NumTemplateArgs);
7601 while (NumTemplateArgs--)
7602 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7603}
7604
7605/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007606void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007607 const RecordData &Record, unsigned &Idx) {
7608 unsigned NumDecls = Record[Idx++];
7609 Set.reserve(Context, NumDecls);
7610 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007611 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007613 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007614 }
7615}
7616
7617CXXBaseSpecifier
7618ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7619 const RecordData &Record, unsigned &Idx) {
7620 bool isVirtual = static_cast<bool>(Record[Idx++]);
7621 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7622 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7623 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7624 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7625 SourceRange Range = ReadSourceRange(F, Record, Idx);
7626 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7627 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7628 EllipsisLoc);
7629 Result.setInheritConstructors(inheritConstructors);
7630 return Result;
7631}
7632
7633std::pair<CXXCtorInitializer **, unsigned>
7634ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7635 unsigned &Idx) {
7636 CXXCtorInitializer **CtorInitializers = 0;
7637 unsigned NumInitializers = Record[Idx++];
7638 if (NumInitializers) {
7639 CtorInitializers
7640 = new (Context) CXXCtorInitializer*[NumInitializers];
7641 for (unsigned i=0; i != NumInitializers; ++i) {
7642 TypeSourceInfo *TInfo = 0;
7643 bool IsBaseVirtual = false;
7644 FieldDecl *Member = 0;
7645 IndirectFieldDecl *IndirectMember = 0;
7646
7647 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7648 switch (Type) {
7649 case CTOR_INITIALIZER_BASE:
7650 TInfo = GetTypeSourceInfo(F, Record, Idx);
7651 IsBaseVirtual = Record[Idx++];
7652 break;
7653
7654 case CTOR_INITIALIZER_DELEGATING:
7655 TInfo = GetTypeSourceInfo(F, Record, Idx);
7656 break;
7657
7658 case CTOR_INITIALIZER_MEMBER:
7659 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7660 break;
7661
7662 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7663 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7664 break;
7665 }
7666
7667 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7668 Expr *Init = ReadExpr(F);
7669 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7670 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7671 bool IsWritten = Record[Idx++];
7672 unsigned SourceOrderOrNumArrayIndices;
7673 SmallVector<VarDecl *, 8> Indices;
7674 if (IsWritten) {
7675 SourceOrderOrNumArrayIndices = Record[Idx++];
7676 } else {
7677 SourceOrderOrNumArrayIndices = Record[Idx++];
7678 Indices.reserve(SourceOrderOrNumArrayIndices);
7679 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7680 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7681 }
7682
7683 CXXCtorInitializer *BOMInit;
7684 if (Type == CTOR_INITIALIZER_BASE) {
7685 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7686 LParenLoc, Init, RParenLoc,
7687 MemberOrEllipsisLoc);
7688 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7689 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7690 Init, RParenLoc);
7691 } else if (IsWritten) {
7692 if (Member)
7693 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7694 LParenLoc, Init, RParenLoc);
7695 else
7696 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7697 MemberOrEllipsisLoc, LParenLoc,
7698 Init, RParenLoc);
7699 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007700 if (IndirectMember) {
7701 assert(Indices.empty() && "Indirect field improperly initialized");
7702 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7703 MemberOrEllipsisLoc, LParenLoc,
7704 Init, RParenLoc);
7705 } else {
7706 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7707 LParenLoc, Init, RParenLoc,
7708 Indices.data(), Indices.size());
7709 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 }
7711
7712 if (IsWritten)
7713 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7714 CtorInitializers[i] = BOMInit;
7715 }
7716 }
7717
7718 return std::make_pair(CtorInitializers, NumInitializers);
7719}
7720
7721NestedNameSpecifier *
7722ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7723 const RecordData &Record, unsigned &Idx) {
7724 unsigned N = Record[Idx++];
7725 NestedNameSpecifier *NNS = 0, *Prev = 0;
7726 for (unsigned I = 0; I != N; ++I) {
7727 NestedNameSpecifier::SpecifierKind Kind
7728 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7729 switch (Kind) {
7730 case NestedNameSpecifier::Identifier: {
7731 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7732 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7733 break;
7734 }
7735
7736 case NestedNameSpecifier::Namespace: {
7737 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7738 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7739 break;
7740 }
7741
7742 case NestedNameSpecifier::NamespaceAlias: {
7743 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7744 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7745 break;
7746 }
7747
7748 case NestedNameSpecifier::TypeSpec:
7749 case NestedNameSpecifier::TypeSpecWithTemplate: {
7750 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7751 if (!T)
7752 return 0;
7753
7754 bool Template = Record[Idx++];
7755 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7756 break;
7757 }
7758
7759 case NestedNameSpecifier::Global: {
7760 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7761 // No associated value, and there can't be a prefix.
7762 break;
7763 }
7764 }
7765 Prev = NNS;
7766 }
7767 return NNS;
7768}
7769
7770NestedNameSpecifierLoc
7771ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7772 unsigned &Idx) {
7773 unsigned N = Record[Idx++];
7774 NestedNameSpecifierLocBuilder Builder;
7775 for (unsigned I = 0; I != N; ++I) {
7776 NestedNameSpecifier::SpecifierKind Kind
7777 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7778 switch (Kind) {
7779 case NestedNameSpecifier::Identifier: {
7780 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7781 SourceRange Range = ReadSourceRange(F, Record, Idx);
7782 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7783 break;
7784 }
7785
7786 case NestedNameSpecifier::Namespace: {
7787 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7788 SourceRange Range = ReadSourceRange(F, Record, Idx);
7789 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7790 break;
7791 }
7792
7793 case NestedNameSpecifier::NamespaceAlias: {
7794 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7795 SourceRange Range = ReadSourceRange(F, Record, Idx);
7796 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7797 break;
7798 }
7799
7800 case NestedNameSpecifier::TypeSpec:
7801 case NestedNameSpecifier::TypeSpecWithTemplate: {
7802 bool Template = Record[Idx++];
7803 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7804 if (!T)
7805 return NestedNameSpecifierLoc();
7806 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7807
7808 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7809 Builder.Extend(Context,
7810 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7811 T->getTypeLoc(), ColonColonLoc);
7812 break;
7813 }
7814
7815 case NestedNameSpecifier::Global: {
7816 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7817 Builder.MakeGlobal(Context, ColonColonLoc);
7818 break;
7819 }
7820 }
7821 }
7822
7823 return Builder.getWithLocInContext(Context);
7824}
7825
7826SourceRange
7827ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7828 unsigned &Idx) {
7829 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7830 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7831 return SourceRange(beg, end);
7832}
7833
7834/// \brief Read an integral value
7835llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7836 unsigned BitWidth = Record[Idx++];
7837 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7838 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7839 Idx += NumWords;
7840 return Result;
7841}
7842
7843/// \brief Read a signed integral value
7844llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7845 bool isUnsigned = Record[Idx++];
7846 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7847}
7848
7849/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007850llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7851 const llvm::fltSemantics &Sem,
7852 unsigned &Idx) {
7853 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007854}
7855
7856// \brief Read a string
7857std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7858 unsigned Len = Record[Idx++];
7859 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7860 Idx += Len;
7861 return Result;
7862}
7863
7864VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7865 unsigned &Idx) {
7866 unsigned Major = Record[Idx++];
7867 unsigned Minor = Record[Idx++];
7868 unsigned Subminor = Record[Idx++];
7869 if (Minor == 0)
7870 return VersionTuple(Major);
7871 if (Subminor == 0)
7872 return VersionTuple(Major, Minor - 1);
7873 return VersionTuple(Major, Minor - 1, Subminor - 1);
7874}
7875
7876CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7877 const RecordData &Record,
7878 unsigned &Idx) {
7879 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7880 return CXXTemporary::Create(Context, Decl);
7881}
7882
7883DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007884 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007885}
7886
7887DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7888 return Diags.Report(Loc, DiagID);
7889}
7890
7891/// \brief Retrieve the identifier table associated with the
7892/// preprocessor.
7893IdentifierTable &ASTReader::getIdentifierTable() {
7894 return PP.getIdentifierTable();
7895}
7896
7897/// \brief Record that the given ID maps to the given switch-case
7898/// statement.
7899void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7900 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7901 "Already have a SwitchCase with this ID");
7902 (*CurrSwitchCaseStmts)[ID] = SC;
7903}
7904
7905/// \brief Retrieve the switch-case statement with the given ID.
7906SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7907 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7908 return (*CurrSwitchCaseStmts)[ID];
7909}
7910
7911void ASTReader::ClearSwitchCaseIDs() {
7912 CurrSwitchCaseStmts->clear();
7913}
7914
7915void ASTReader::ReadComments() {
7916 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007917 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007918 serialization::ModuleFile *> >::iterator
7919 I = CommentsCursors.begin(),
7920 E = CommentsCursors.end();
7921 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007922 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007923 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 serialization::ModuleFile &F = *I->second;
7925 SavedStreamPosition SavedPosition(Cursor);
7926
7927 RecordData Record;
7928 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007929 llvm::BitstreamEntry Entry =
7930 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007931
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007932 switch (Entry.Kind) {
7933 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7934 case llvm::BitstreamEntry::Error:
7935 Error("malformed block record in AST file");
7936 return;
7937 case llvm::BitstreamEntry::EndBlock:
7938 goto NextCursor;
7939 case llvm::BitstreamEntry::Record:
7940 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 }
7943
7944 // Read a record.
7945 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007946 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 case COMMENTS_RAW_COMMENT: {
7948 unsigned Idx = 0;
7949 SourceRange SR = ReadSourceRange(F, Record, Idx);
7950 RawComment::CommentKind Kind =
7951 (RawComment::CommentKind) Record[Idx++];
7952 bool IsTrailingComment = Record[Idx++];
7953 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007954 Comments.push_back(new (Context) RawComment(
7955 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7956 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007957 break;
7958 }
7959 }
7960 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007961 NextCursor:
7962 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007964}
7965
Richard Smithcd45dbc2014-04-19 03:48:30 +00007966std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7967 // If we know the owning module, use it.
7968 if (Module *M = D->getOwningModule())
7969 return M->getFullModuleName();
7970
7971 // Otherwise, use the name of the top-level module the decl is within.
7972 if (ModuleFile *M = getOwningModuleFile(D))
7973 return M->ModuleName;
7974
7975 // Not from a module.
7976 return "";
7977}
7978
Guy Benyei11169dd2012-12-18 14:30:41 +00007979void ASTReader::finishPendingActions() {
7980 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00007981 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00007982 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 // If any identifiers with corresponding top-level declarations have
7984 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00007985 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7986 TopLevelDeclsMap;
7987 TopLevelDeclsMap TopLevelDecls;
7988
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007990 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007991 SmallVector<uint32_t, 4> DeclIDs =
7992 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00007993 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00007994
7995 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00007997
Guy Benyei11169dd2012-12-18 14:30:41 +00007998 // Load pending declaration chains.
7999 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8000 loadPendingDeclChain(PendingDeclChains[I]);
8001 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8002 }
8003 PendingDeclChains.clear();
8004
Douglas Gregor6168bd22013-02-18 15:53:43 +00008005 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008006 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8007 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008008 IdentifierInfo *II = TLD->first;
8009 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008010 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008011 }
8012 }
8013
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 // Load any pending macro definitions.
8015 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008016 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8017 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8018 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8019 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008020 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008021 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008022 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8023 if (Info.M->Kind != MK_Module)
8024 resolvePendingMacro(II, Info);
8025 }
8026 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008027 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008028 ++IDIdx) {
8029 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8030 if (Info.M->Kind == MK_Module)
8031 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008032 }
8033 }
8034 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008035
8036 // Wire up the DeclContexts for Decls that we delayed setting until
8037 // recursive loading is completed.
8038 while (!PendingDeclContextInfos.empty()) {
8039 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8040 PendingDeclContextInfos.pop_front();
8041 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8042 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8043 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8044 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008045
Richard Smithd1c46742014-04-30 02:24:17 +00008046 // Perform any pending declaration updates.
8047 while (!PendingUpdateRecords.empty()) {
8048 auto Update = PendingUpdateRecords.pop_back_val();
8049 ReadingKindTracker ReadingKind(Read_Decl, *this);
8050 loadDeclUpdateRecords(Update.first, Update.second);
8051 }
8052
Richard Smithcd45dbc2014-04-19 03:48:30 +00008053 // Trigger the import of the full definition of each class that had any
8054 // odr-merging problems, so we can produce better diagnostics for them.
8055 for (auto &Merge : PendingOdrMergeFailures) {
8056 Merge.first->buildLookup();
8057 Merge.first->decls_begin();
8058 Merge.first->bases_begin();
8059 Merge.first->vbases_begin();
8060 for (auto *RD : Merge.second) {
8061 RD->decls_begin();
8062 RD->bases_begin();
8063 RD->vbases_begin();
8064 }
8065 }
8066
Richard Smith2b9e3e32013-10-18 06:05:18 +00008067 // For each declaration from a merged context, check that the canonical
8068 // definition of that context also contains a declaration of the same
8069 // entity.
8070 while (!PendingOdrMergeChecks.empty()) {
8071 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8072
8073 // FIXME: Skip over implicit declarations for now. This matters for things
8074 // like implicitly-declared special member functions. This isn't entirely
8075 // correct; we can end up with multiple unmerged declarations of the same
8076 // implicit entity.
8077 if (D->isImplicit())
8078 continue;
8079
8080 DeclContext *CanonDef = D->getDeclContext();
8081 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8082
8083 bool Found = false;
8084 const Decl *DCanon = D->getCanonicalDecl();
8085
8086 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8087 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8088 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008089 for (auto RI : (*I)->redecls()) {
8090 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008091 // This declaration is present in the canonical definition. If it's
8092 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008093 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008094 Found = true;
8095 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008096 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008097 break;
8098 }
8099 }
8100 }
8101
8102 if (!Found) {
8103 D->setInvalidDecl();
8104
Richard Smithcd45dbc2014-04-19 03:48:30 +00008105 std::string CanonDefModule =
8106 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008107 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008108 << D << getOwningModuleNameForDiagnostic(D)
8109 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008110
8111 if (Candidates.empty())
8112 Diag(cast<Decl>(CanonDef)->getLocation(),
8113 diag::note_module_odr_violation_no_possible_decls) << D;
8114 else {
8115 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8116 Diag(Candidates[I]->getLocation(),
8117 diag::note_module_odr_violation_possible_decl)
8118 << Candidates[I];
8119 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008120
8121 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008122 }
8123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 }
8125
8126 // If we deserialized any C++ or Objective-C class definitions, any
8127 // Objective-C protocol definitions, or any redeclarable templates, make sure
8128 // that all redeclarations point to the definitions. Note that this can only
8129 // happen now, after the redeclaration chains have been fully wired.
8130 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8131 DEnd = PendingDefinitions.end();
8132 D != DEnd; ++D) {
8133 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008134 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 // Make sure that the TagType points at the definition.
8136 const_cast<TagType*>(TagT)->decl = TD;
8137 }
8138
Aaron Ballman86c93902014-03-06 23:45:36 +00008139 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8140 for (auto R : RD->redecls())
8141 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008142
8143 }
8144
8145 continue;
8146 }
8147
Aaron Ballman86c93902014-03-06 23:45:36 +00008148 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 // Make sure that the ObjCInterfaceType points at the definition.
8150 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8151 ->Decl = ID;
8152
Aaron Ballman86c93902014-03-06 23:45:36 +00008153 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008154 R->Data = ID->Data;
8155
8156 continue;
8157 }
8158
Aaron Ballman86c93902014-03-06 23:45:36 +00008159 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8160 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 R->Data = PD->Data;
8162
8163 continue;
8164 }
8165
Aaron Ballman86c93902014-03-06 23:45:36 +00008166 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8167 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 R->Common = RTD->Common;
8169 }
8170 PendingDefinitions.clear();
8171
8172 // Load the bodies of any functions or methods we've encountered. We do
8173 // this now (delayed) so that we can be sure that the declaration chains
8174 // have been fully wired up.
8175 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8176 PBEnd = PendingBodies.end();
8177 PB != PBEnd; ++PB) {
8178 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8179 // FIXME: Check for =delete/=default?
8180 // FIXME: Complain about ODR violations here?
8181 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8182 FD->setLazyBody(PB->second);
8183 continue;
8184 }
8185
8186 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8187 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8188 MD->setLazyBody(PB->second);
8189 }
8190 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008191
8192 // Issue any pending ODR-failure diagnostics.
8193 for (auto &Merge : PendingOdrMergeFailures) {
8194 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8195 continue;
8196
8197 bool Diagnosed = false;
8198 for (auto *RD : Merge.second) {
8199 // Multiple different declarations got merged together; tell the user
8200 // where they came from.
8201 if (Merge.first != RD) {
8202 // FIXME: Walk the definition, figure out what's different,
8203 // and diagnose that.
8204 if (!Diagnosed) {
8205 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8206 Diag(Merge.first->getLocation(),
8207 diag::err_module_odr_violation_different_definitions)
8208 << Merge.first << Module.empty() << Module;
8209 Diagnosed = true;
8210 }
8211
8212 Diag(RD->getLocation(),
8213 diag::note_module_odr_violation_different_definitions)
8214 << getOwningModuleNameForDiagnostic(RD);
8215 }
8216 }
8217
8218 if (!Diagnosed) {
8219 // All definitions are updates to the same declaration. This happens if a
8220 // module instantiates the declaration of a class template specialization
8221 // and two or more other modules instantiate its definition.
8222 //
8223 // FIXME: Indicate which modules had instantiations of this definition.
8224 // FIXME: How can this even happen?
8225 Diag(Merge.first->getLocation(),
8226 diag::err_module_odr_violation_different_instantiations)
8227 << Merge.first;
8228 }
8229 }
8230 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008231}
8232
8233void ASTReader::FinishedDeserializing() {
8234 assert(NumCurrentElementsDeserializing &&
8235 "FinishedDeserializing not paired with StartedDeserializing");
8236 if (NumCurrentElementsDeserializing == 1) {
8237 // We decrease NumCurrentElementsDeserializing only after pending actions
8238 // are finished, to avoid recursively re-calling finishPendingActions().
8239 finishPendingActions();
8240 }
8241 --NumCurrentElementsDeserializing;
8242
Richard Smith04d05b52014-03-23 00:27:18 +00008243 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8244 // We are not in recursive loading, so it's safe to pass the "interesting"
8245 // decls to the consumer.
8246 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 }
8248}
8249
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008250void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008251 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008252
8253 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8254 SemaObj->TUScope->AddDecl(D);
8255 } else if (SemaObj->TUScope) {
8256 // Adding the decl to IdResolver may have failed because it was already in
8257 // (even though it was not added in scope). If it is already in, make sure
8258 // it gets in the scope as well.
8259 if (std::find(SemaObj->IdResolver.begin(Name),
8260 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8261 SemaObj->TUScope->AddDecl(D);
8262 }
8263}
8264
Nico Weber824285e2014-05-08 04:26:47 +00008265ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8266 bool DisableValidation, bool AllowASTWithCompilerErrors,
8267 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008268 bool UseGlobalIndex)
Nico Weber824285e2014-05-08 04:26:47 +00008269 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
8270 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8271 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()), SemaObj(0),
8272 PP(PP), Context(Context), Consumer(0), ModuleMgr(PP.getFileManager()),
8273 isysroot(isysroot), DisableValidation(DisableValidation),
8274 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8275 AllowConfigurationMismatch(AllowConfigurationMismatch),
8276 ValidateSystemInputs(ValidateSystemInputs),
8277 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8278 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
8279 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8280 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8281 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8282 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8283 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8284 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8285 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8286 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8287 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8288 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8289 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 SourceMgr.setExternalSLocEntrySource(this);
8291}
8292
8293ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008294 if (OwnsDeserializationListener)
8295 delete DeserializationListener;
8296
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 for (DeclContextVisibleUpdatesPending::iterator
8298 I = PendingVisibleUpdates.begin(),
8299 E = PendingVisibleUpdates.end();
8300 I != E; ++I) {
8301 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8302 F = I->second.end();
8303 J != F; ++J)
8304 delete J->first;
8305 }
8306}