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