blob: 3ffbb501efcb11051197ff50ac19706345ea6d41 [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 <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
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) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000138 bool Continue = false;
139 if (First->needsInputFileVisitation() &&
140 (!isSystem || First->needsSystemInputFileVisitation()))
141 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
142 if (Second->needsInputFileVisitation() &&
143 (!isSystem || Second->needsSystemInputFileVisitation()))
144 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
145 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000146}
147
Guy Benyei11169dd2012-12-18 14:30:41 +0000148//===----------------------------------------------------------------------===//
149// PCH validator implementation
150//===----------------------------------------------------------------------===//
151
152ASTReaderListener::~ASTReaderListener() {}
153
154/// \brief Compare the given set of language options against an existing set of
155/// language options.
156///
157/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
158///
159/// \returns true if the languagae options mis-match, false otherwise.
160static bool checkLanguageOptions(const LangOptions &LangOpts,
161 const LangOptions &ExistingLangOpts,
162 DiagnosticsEngine *Diags) {
163#define LANGOPT(Name, Bits, Default, Description) \
164 if (ExistingLangOpts.Name != LangOpts.Name) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_mismatch) \
167 << Description << LangOpts.Name << ExistingLangOpts.Name; \
168 return true; \
169 }
170
171#define VALUE_LANGOPT(Name, Bits, Default, Description) \
172 if (ExistingLangOpts.Name != LangOpts.Name) { \
173 if (Diags) \
174 Diags->Report(diag::err_pch_langopt_value_mismatch) \
175 << Description; \
176 return true; \
177 }
178
179#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
180 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
181 if (Diags) \
182 Diags->Report(diag::err_pch_langopt_value_mismatch) \
183 << Description; \
184 return true; \
185 }
186
187#define BENIGN_LANGOPT(Name, Bits, Default, Description)
188#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
189#include "clang/Basic/LangOptions.def"
190
191 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
192 if (Diags)
193 Diags->Report(diag::err_pch_langopt_value_mismatch)
194 << "target Objective-C runtime";
195 return true;
196 }
197
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000198 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
199 LangOpts.CommentOpts.BlockCommandNames) {
200 if (Diags)
201 Diags->Report(diag::err_pch_langopt_value_mismatch)
202 << "block command names";
203 return true;
204 }
205
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 return false;
207}
208
209/// \brief Compare the given set of target options against an existing set of
210/// target options.
211///
212/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
213///
214/// \returns true if the target options mis-match, false otherwise.
215static bool checkTargetOptions(const TargetOptions &TargetOpts,
216 const TargetOptions &ExistingTargetOpts,
217 DiagnosticsEngine *Diags) {
218#define CHECK_TARGET_OPT(Field, Name) \
219 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
220 if (Diags) \
221 Diags->Report(diag::err_pch_targetopt_mismatch) \
222 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
223 return true; \
224 }
225
226 CHECK_TARGET_OPT(Triple, "target");
227 CHECK_TARGET_OPT(CPU, "target CPU");
228 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000229#undef CHECK_TARGET_OPT
230
231 // Compare feature sets.
232 SmallVector<StringRef, 4> ExistingFeatures(
233 ExistingTargetOpts.FeaturesAsWritten.begin(),
234 ExistingTargetOpts.FeaturesAsWritten.end());
235 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
236 TargetOpts.FeaturesAsWritten.end());
237 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
238 std::sort(ReadFeatures.begin(), ReadFeatures.end());
239
240 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
241 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
242 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
243 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
244 ++ExistingIdx;
245 ++ReadIdx;
246 continue;
247 }
248
249 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << false << ReadFeatures[ReadIdx];
253 return true;
254 }
255
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ExistingIdx < ExistingN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << true << ExistingFeatures[ExistingIdx];
266 return true;
267 }
268
269 if (ReadIdx < ReadN) {
270 if (Diags)
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
273 return true;
274 }
275
276 return false;
277}
278
279bool
280PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
281 bool Complain) {
282 const LangOptions &ExistingLangOpts = PP.getLangOpts();
283 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000284 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000285}
286
287bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
288 bool Complain) {
289 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
290 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000291 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294namespace {
295 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
296 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000297 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
298 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000299}
300
Ben Langmuirb92de022014-04-29 16:25:26 +0000301static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
302 DiagnosticsEngine &Diags,
303 bool Complain) {
304 typedef DiagnosticsEngine::Level Level;
305
306 // Check current mappings for new -Werror mappings, and the stored mappings
307 // for cases that were explicitly mapped to *not* be errors that are now
308 // errors because of options like -Werror.
309 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
310
311 for (DiagnosticsEngine *MappingSource : MappingSources) {
312 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
313 diag::kind DiagID = DiagIDMappingPair.first;
314 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
315 if (CurLevel < DiagnosticsEngine::Error)
316 continue; // not significant
317 Level StoredLevel =
318 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
319 if (StoredLevel < DiagnosticsEngine::Error) {
320 if (Complain)
321 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
322 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
323 return true;
324 }
325 }
326 }
327
328 return false;
329}
330
Alp Tokerac4e8e52014-06-22 21:58:33 +0000331static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
332 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
333 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
334 return true;
335 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000336}
337
338static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
339 DiagnosticsEngine &Diags,
340 bool IsSystem, bool Complain) {
341 // Top-level options
342 if (IsSystem) {
343 if (Diags.getSuppressSystemWarnings())
344 return false;
345 // If -Wsystem-headers was not enabled before, be conservative
346 if (StoredDiags.getSuppressSystemWarnings()) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
349 return true;
350 }
351 }
352
353 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
354 if (Complain)
355 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
356 return true;
357 }
358
359 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
360 !StoredDiags.getEnableAllWarnings()) {
361 if (Complain)
362 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
363 return true;
364 }
365
366 if (isExtHandlingFromDiagsError(Diags) &&
367 !isExtHandlingFromDiagsError(StoredDiags)) {
368 if (Complain)
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
370 return true;
371 }
372
373 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
374}
375
376bool PCHValidator::ReadDiagnosticOptions(
377 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
378 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
379 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
380 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000381 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000382 // This should never fail, because we would have processed these options
383 // before writing them to an ASTFile.
384 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
385
386 ModuleManager &ModuleMgr = Reader.getModuleManager();
387 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
388
389 // If the original import came from a file explicitly generated by the user,
390 // don't check the diagnostic mappings.
391 // FIXME: currently this is approximated by checking whether this is not a
392 // module import.
393 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
394 // the transitive closure of its imports, since unrelated modules cannot be
395 // imported until after this module finishes validation.
396 ModuleFile *TopImport = *ModuleMgr.rbegin();
397 while (!TopImport->ImportedBy.empty())
398 TopImport = TopImport->ImportedBy[0];
399 if (TopImport->Kind != MK_Module)
400 return false;
401
402 StringRef ModuleName = TopImport->ModuleName;
403 assert(!ModuleName.empty() && "diagnostic options read before module name");
404
405 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
406 assert(M && "missing module");
407
408 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
409 // contains the union of their flags.
410 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
411}
412
Guy Benyei11169dd2012-12-18 14:30:41 +0000413/// \brief Collect the macro definitions provided by the given preprocessor
414/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000415static void
416collectMacroDefinitions(const PreprocessorOptions &PPOpts,
417 MacroDefinitionsMap &Macros,
418 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
420 StringRef Macro = PPOpts.Macros[I].first;
421 bool IsUndef = PPOpts.Macros[I].second;
422
423 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
424 StringRef MacroName = MacroPair.first;
425 StringRef MacroBody = MacroPair.second;
426
427 // For an #undef'd macro, we only care about the name.
428 if (IsUndef) {
429 if (MacroNames && !Macros.count(MacroName))
430 MacroNames->push_back(MacroName);
431
432 Macros[MacroName] = std::make_pair("", true);
433 continue;
434 }
435
436 // For a #define'd macro, figure out the actual definition.
437 if (MacroName.size() == Macro.size())
438 MacroBody = "1";
439 else {
440 // Note: GCC drops anything following an end-of-line character.
441 StringRef::size_type End = MacroBody.find_first_of("\n\r");
442 MacroBody = MacroBody.substr(0, End);
443 }
444
445 if (MacroNames && !Macros.count(MacroName))
446 MacroNames->push_back(MacroName);
447 Macros[MacroName] = std::make_pair(MacroBody, false);
448 }
449}
450
451/// \brief Check the preprocessor options deserialized from the control block
452/// against the preprocessor options in an existing preprocessor.
453///
454/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
455static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
456 const PreprocessorOptions &ExistingPPOpts,
457 DiagnosticsEngine *Diags,
458 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000459 std::string &SuggestedPredefines,
460 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 // Check macro definitions.
462 MacroDefinitionsMap ASTFileMacros;
463 collectMacroDefinitions(PPOpts, ASTFileMacros);
464 MacroDefinitionsMap ExistingMacros;
465 SmallVector<StringRef, 4> ExistingMacroNames;
466 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
467
468 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
469 // Dig out the macro definition in the existing preprocessor options.
470 StringRef MacroName = ExistingMacroNames[I];
471 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
472
473 // Check whether we know anything about this macro name or not.
474 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
475 = ASTFileMacros.find(MacroName);
476 if (Known == ASTFileMacros.end()) {
477 // FIXME: Check whether this identifier was referenced anywhere in the
478 // AST file. If so, we should reject the AST file. Unfortunately, this
479 // information isn't in the control block. What shall we do about it?
480
481 if (Existing.second) {
482 SuggestedPredefines += "#undef ";
483 SuggestedPredefines += MacroName.str();
484 SuggestedPredefines += '\n';
485 } else {
486 SuggestedPredefines += "#define ";
487 SuggestedPredefines += MacroName.str();
488 SuggestedPredefines += ' ';
489 SuggestedPredefines += Existing.first.str();
490 SuggestedPredefines += '\n';
491 }
492 continue;
493 }
494
495 // If the macro was defined in one but undef'd in the other, we have a
496 // conflict.
497 if (Existing.second != Known->second.second) {
498 if (Diags) {
499 Diags->Report(diag::err_pch_macro_def_undef)
500 << MacroName << Known->second.second;
501 }
502 return true;
503 }
504
505 // If the macro was #undef'd in both, or if the macro bodies are identical,
506 // it's fine.
507 if (Existing.second || Existing.first == Known->second.first)
508 continue;
509
510 // The macro bodies differ; complain.
511 if (Diags) {
512 Diags->Report(diag::err_pch_macro_def_conflict)
513 << MacroName << Known->second.first << Existing.first;
514 }
515 return true;
516 }
517
518 // Check whether we're using predefines.
519 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
520 if (Diags) {
521 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
522 }
523 return true;
524 }
525
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000526 // Detailed record is important since it is used for the module cache hash.
527 if (LangOpts.Modules &&
528 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
531 }
532 return true;
533 }
534
Guy Benyei11169dd2012-12-18 14:30:41 +0000535 // Compute the #include and #include_macros lines we need.
536 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
537 StringRef File = ExistingPPOpts.Includes[I];
538 if (File == ExistingPPOpts.ImplicitPCHInclude)
539 continue;
540
541 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
542 != PPOpts.Includes.end())
543 continue;
544
545 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000546 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 SuggestedPredefines += "\"\n";
548 }
549
550 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
551 StringRef File = ExistingPPOpts.MacroIncludes[I];
552 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
553 File)
554 != PPOpts.MacroIncludes.end())
555 continue;
556
557 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000558 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 SuggestedPredefines += "\"\n##\n";
560 }
561
562 return false;
563}
564
565bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
566 bool Complain,
567 std::string &SuggestedPredefines) {
568 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
569
570 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000571 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000573 SuggestedPredefines,
574 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000575}
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
578 PP.setCounterValue(Value);
579}
580
581//===----------------------------------------------------------------------===//
582// AST reader implementation
583//===----------------------------------------------------------------------===//
584
Nico Weber824285e2014-05-08 04:26:47 +0000585void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
586 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000587 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000588 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000589}
590
591
592
593unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
594 return serialization::ComputeHash(Sel);
595}
596
597
598std::pair<unsigned, unsigned>
599ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000600 using namespace llvm::support;
601 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
602 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 return std::make_pair(KeyLen, DataLen);
604}
605
606ASTSelectorLookupTrait::internal_key_type
607ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000608 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
611 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
612 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (N == 0)
614 return SelTable.getNullarySelector(FirstII);
615 else if (N == 1)
616 return SelTable.getUnarySelector(FirstII);
617
618 SmallVector<IdentifierInfo *, 16> Args;
619 Args.push_back(FirstII);
620 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000621 Args.push_back(Reader.getLocalIdentifier(
622 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000623
624 return SelTable.getSelector(N, Args.data());
625}
626
627ASTSelectorLookupTrait::data_type
628ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
629 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000630 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000631
632 data_type Result;
633
Justin Bogner57ba0b22014-03-28 22:03:24 +0000634 Result.ID = Reader.getGlobalSelectorID(
635 F, endian::readNext<uint32_t, little, unaligned>(d));
636 unsigned NumInstanceMethodsAndBits =
637 endian::readNext<uint16_t, little, unaligned>(d);
638 unsigned NumFactoryMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000640 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
641 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
642 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
643 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000644
645 // Load instance methods
646 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
648 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 Result.Instance.push_back(Method);
650 }
651
652 // Load factory methods
653 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000654 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
655 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000656 Result.Factory.push_back(Method);
657 }
658
659 return Result;
660}
661
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000662unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
663 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664}
665
666std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000667ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000668 using namespace llvm::support;
669 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
670 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 return std::make_pair(KeyLen, DataLen);
672}
673
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000674ASTIdentifierLookupTraitBase::internal_key_type
675ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000677 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000678}
679
Douglas Gregordcf25082013-02-11 18:16:18 +0000680/// \brief Whether the given identifier is "interesting".
681static bool isInterestingIdentifier(IdentifierInfo &II) {
682 return II.isPoisoned() ||
683 II.isExtensionToken() ||
684 II.getObjCOrBuiltinID() ||
685 II.hasRevertedTokenIDToIdentifier() ||
686 II.hadMacroDefinition() ||
687 II.getFETokenInfo<void>();
688}
689
Guy Benyei11169dd2012-12-18 14:30:41 +0000690IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
691 const unsigned char* d,
692 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000693 using namespace llvm::support;
694 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695 bool IsInteresting = RawID & 0x01;
696
697 // Wipe out the "is interesting" bit.
698 RawID = RawID >> 1;
699
700 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
701 if (!IsInteresting) {
702 // For uninteresting identifiers, just build the IdentifierInfo
703 // and associate it with the persistent ID.
704 IdentifierInfo *II = KnownII;
705 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000706 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 KnownII = II;
708 }
709 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000710 if (!II->isFromAST()) {
711 bool WasInteresting = isInterestingIdentifier(*II);
712 II->setIsFromAST();
713 if (WasInteresting)
714 II->setChangedSinceDeserialization();
715 }
716 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 return II;
718 }
719
Justin Bogner57ba0b22014-03-28 22:03:24 +0000720 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
721 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 bool CPlusPlusOperatorKeyword = Bits & 0x01;
723 Bits >>= 1;
724 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
725 Bits >>= 1;
726 bool Poisoned = Bits & 0x01;
727 Bits >>= 1;
728 bool ExtensionToken = Bits & 0x01;
729 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000730 bool hasSubmoduleMacros = Bits & 0x01;
731 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 bool hadMacroDefinition = Bits & 0x01;
733 Bits >>= 1;
734
735 assert(Bits == 0 && "Extra bits in the identifier?");
736 DataLen -= 8;
737
738 // Build the IdentifierInfo itself and link the identifier ID with
739 // the new IdentifierInfo.
740 IdentifierInfo *II = KnownII;
741 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000742 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 KnownII = II;
744 }
745 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000746 if (!II->isFromAST()) {
747 bool WasInteresting = isInterestingIdentifier(*II);
748 II->setIsFromAST();
749 if (WasInteresting)
750 II->setChangedSinceDeserialization();
751 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000752
753 // Set or check the various bits in the IdentifierInfo structure.
754 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000755 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000756 II->RevertTokenIDToIdentifier();
757 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
758 assert(II->isExtensionToken() == ExtensionToken &&
759 "Incorrect extension token flag");
760 (void)ExtensionToken;
761 if (Poisoned)
762 II->setIsPoisoned(true);
763 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
764 "Incorrect C++ operator keyword flag");
765 (void)CPlusPlusOperatorKeyword;
766
767 // If this identifier is a macro, deserialize the macro
768 // definition.
769 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 uint32_t MacroDirectivesOffset =
771 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000772 DataLen -= 4;
773 SmallVector<uint32_t, 8> LocalMacroIDs;
774 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000775 while (true) {
776 uint32_t LocalMacroID =
777 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000778 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000779 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 LocalMacroIDs.push_back(LocalMacroID);
781 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000782 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000783
784 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000785 // Macro definitions are stored from newest to oldest, so reverse them
786 // before registering them.
787 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000788 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000789 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
790 unsigned Size = 1;
791
792 static const uint32_t HasOverridesFlag = 0x80000000U;
793 if (I + 1 != E && (I[1] & HasOverridesFlag))
794 Size += 1 + (I[1] & ~HasOverridesFlag);
795
796 MacroSizes.push_back(Size);
797 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000798 }
Richard Smith49f906a2014-03-01 00:08:04 +0000799
800 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
801 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
802 SE = MacroSizes.rend();
803 SI != SE; ++SI) {
804 I -= *SI;
805
806 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000807 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000808 if (*SI != 1)
809 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
810 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
811 }
812 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000813 } else {
814 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
815 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 }
817
818 Reader.SetIdentifierInfo(ID, II);
819
820 // Read all of the declarations visible at global scope with this
821 // name.
822 if (DataLen > 0) {
823 SmallVector<uint32_t, 4> DeclIDs;
824 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 DeclIDs.push_back(Reader.getGlobalDeclID(
826 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 Reader.SetGloballyVisibleDecls(II, DeclIDs);
828 }
829
830 return II;
831}
832
833unsigned
834ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
835 llvm::FoldingSetNodeID ID;
836 ID.AddInteger(Key.Kind);
837
838 switch (Key.Kind) {
839 case DeclarationName::Identifier:
840 case DeclarationName::CXXLiteralOperatorName:
841 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
842 break;
843 case DeclarationName::ObjCZeroArgSelector:
844 case DeclarationName::ObjCOneArgSelector:
845 case DeclarationName::ObjCMultiArgSelector:
846 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
847 break;
848 case DeclarationName::CXXOperatorName:
849 ID.AddInteger((OverloadedOperatorKind)Key.Data);
850 break;
851 case DeclarationName::CXXConstructorName:
852 case DeclarationName::CXXDestructorName:
853 case DeclarationName::CXXConversionFunctionName:
854 case DeclarationName::CXXUsingDirective:
855 break;
856 }
857
858 return ID.ComputeHash();
859}
860
861ASTDeclContextNameLookupTrait::internal_key_type
862ASTDeclContextNameLookupTrait::GetInternalKey(
863 const external_key_type& Name) const {
864 DeclNameKey Key;
865 Key.Kind = Name.getNameKind();
866 switch (Name.getNameKind()) {
867 case DeclarationName::Identifier:
868 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
869 break;
870 case DeclarationName::ObjCZeroArgSelector:
871 case DeclarationName::ObjCOneArgSelector:
872 case DeclarationName::ObjCMultiArgSelector:
873 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
874 break;
875 case DeclarationName::CXXOperatorName:
876 Key.Data = Name.getCXXOverloadedOperator();
877 break;
878 case DeclarationName::CXXLiteralOperatorName:
879 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
880 break;
881 case DeclarationName::CXXConstructorName:
882 case DeclarationName::CXXDestructorName:
883 case DeclarationName::CXXConversionFunctionName:
884 case DeclarationName::CXXUsingDirective:
885 Key.Data = 0;
886 break;
887 }
888
889 return Key;
890}
891
892std::pair<unsigned, unsigned>
893ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000894 using namespace llvm::support;
895 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
896 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 return std::make_pair(KeyLen, DataLen);
898}
899
900ASTDeclContextNameLookupTrait::internal_key_type
901ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000903
904 DeclNameKey Key;
905 Key.Kind = (DeclarationName::NameKind)*d++;
906 switch (Key.Kind) {
907 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 Key.Data = (uint64_t)Reader.getLocalIdentifier(
909 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000910 break;
911 case DeclarationName::ObjCZeroArgSelector:
912 case DeclarationName::ObjCOneArgSelector:
913 case DeclarationName::ObjCMultiArgSelector:
914 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 (uint64_t)Reader.getLocalSelector(
916 F, endian::readNext<uint32_t, little, unaligned>(
917 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 break;
919 case DeclarationName::CXXOperatorName:
920 Key.Data = *d++; // OverloadedOperatorKind
921 break;
922 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 Key.Data = (uint64_t)Reader.getLocalIdentifier(
924 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXConstructorName:
927 case DeclarationName::CXXDestructorName:
928 case DeclarationName::CXXConversionFunctionName:
929 case DeclarationName::CXXUsingDirective:
930 Key.Data = 0;
931 break;
932 }
933
934 return Key;
935}
936
937ASTDeclContextNameLookupTrait::data_type
938ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
939 const unsigned char* d,
940 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 using namespace llvm::support;
942 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000943 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
944 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 return std::make_pair(Start, Start + NumDecls);
946}
947
948bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000949 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 const std::pair<uint64_t, uint64_t> &Offsets,
951 DeclContextInfo &Info) {
952 SavedStreamPosition SavedPosition(Cursor);
953 // First the lexical decls.
954 if (Offsets.first != 0) {
955 Cursor.JumpToBit(Offsets.first);
956
957 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000958 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 if (RecCode != DECL_CONTEXT_LEXICAL) {
962 Error("Expected lexical block");
963 return true;
964 }
965
Chris Lattner0e6c9402013-01-20 02:38:54 +0000966 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
967 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 }
969
970 // Now the lookup table.
971 if (Offsets.second != 0) {
972 Cursor.JumpToBit(Offsets.second);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_VISIBLE) {
979 Error("Expected visible lookup table block");
980 return true;
981 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000982 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
983 (const unsigned char *)Blob.data() + Record[0],
984 (const unsigned char *)Blob.data() + sizeof(uint32_t),
985 (const unsigned char *)Blob.data(),
986 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000987 }
988
989 return false;
990}
991
992void ASTReader::Error(StringRef Msg) {
993 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000994 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
995 Diag(diag::note_module_cache_path)
996 << PP.getHeaderSearchInfo().getModuleCachePath();
997 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000998}
999
1000void ASTReader::Error(unsigned DiagID,
1001 StringRef Arg1, StringRef Arg2) {
1002 if (Diags.isDiagnosticInFlight())
1003 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1004 else
1005 Diag(DiagID) << Arg1 << Arg2;
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// Source Manager Deserialization
1010//===----------------------------------------------------------------------===//
1011
1012/// \brief Read the line table in the source manager block.
1013/// \returns true if there was an error.
1014bool ASTReader::ParseLineTable(ModuleFile &F,
1015 SmallVectorImpl<uint64_t> &Record) {
1016 unsigned Idx = 0;
1017 LineTableInfo &LineTable = SourceMgr.getLineTable();
1018
1019 // Parse the file names
1020 std::map<int, int> FileIDs;
1021 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1022 // Extract the file name
1023 unsigned FilenameLen = Record[Idx++];
1024 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1025 Idx += FilenameLen;
1026 MaybeAddSystemRootToFilename(F, Filename);
1027 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1028 }
1029
1030 // Parse the line entries
1031 std::vector<LineEntry> Entries;
1032 while (Idx < Record.size()) {
1033 int FID = Record[Idx++];
1034 assert(FID >= 0 && "Serialized line entries for non-local file.");
1035 // Remap FileID from 1-based old view.
1036 FID += F.SLocEntryBaseID - 1;
1037
1038 // Extract the line entries
1039 unsigned NumEntries = Record[Idx++];
1040 assert(NumEntries && "Numentries is 00000");
1041 Entries.clear();
1042 Entries.reserve(NumEntries);
1043 for (unsigned I = 0; I != NumEntries; ++I) {
1044 unsigned FileOffset = Record[Idx++];
1045 unsigned LineNo = Record[Idx++];
1046 int FilenameID = FileIDs[Record[Idx++]];
1047 SrcMgr::CharacteristicKind FileKind
1048 = (SrcMgr::CharacteristicKind)Record[Idx++];
1049 unsigned IncludeOffset = Record[Idx++];
1050 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1051 FileKind, IncludeOffset));
1052 }
1053 LineTable.AddEntry(FileID::get(FID), Entries);
1054 }
1055
1056 return false;
1057}
1058
1059/// \brief Read a source manager block
1060bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1061 using namespace SrcMgr;
1062
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001063 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001064
1065 // Set the source-location entry cursor to the current position in
1066 // the stream. This cursor will be used to read the contents of the
1067 // source manager block initially, and then lazily read
1068 // source-location entries as needed.
1069 SLocEntryCursor = F.Stream;
1070
1071 // The stream itself is going to skip over the source manager block.
1072 if (F.Stream.SkipBlock()) {
1073 Error("malformed block record in AST file");
1074 return true;
1075 }
1076
1077 // Enter the source manager block.
1078 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1079 Error("malformed source manager block record in AST file");
1080 return true;
1081 }
1082
1083 RecordData Record;
1084 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001085 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1086
1087 switch (E.Kind) {
1088 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1089 case llvm::BitstreamEntry::Error:
1090 Error("malformed block record in AST file");
1091 return true;
1092 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001094 case llvm::BitstreamEntry::Record:
1095 // The interesting case.
1096 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001101 StringRef Blob;
1102 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 default: // Default behavior: ignore.
1104 break;
1105
1106 case SM_SLOC_FILE_ENTRY:
1107 case SM_SLOC_BUFFER_ENTRY:
1108 case SM_SLOC_EXPANSION_ENTRY:
1109 // Once we hit one of the source location entries, we're done.
1110 return false;
1111 }
1112 }
1113}
1114
1115/// \brief If a header file is not found at the path that we expect it to be
1116/// and the PCH file was moved from its original location, try to resolve the
1117/// file by assuming that header+PCH were moved together and the header is in
1118/// the same place relative to the PCH.
1119static std::string
1120resolveFileRelativeToOriginalDir(const std::string &Filename,
1121 const std::string &OriginalDir,
1122 const std::string &CurrDir) {
1123 assert(OriginalDir != CurrDir &&
1124 "No point trying to resolve the file if the PCH dir didn't change");
1125 using namespace llvm::sys;
1126 SmallString<128> filePath(Filename);
1127 fs::make_absolute(filePath);
1128 assert(path::is_absolute(OriginalDir));
1129 SmallString<128> currPCHPath(CurrDir);
1130
1131 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1132 fileDirE = path::end(path::parent_path(filePath));
1133 path::const_iterator origDirI = path::begin(OriginalDir),
1134 origDirE = path::end(OriginalDir);
1135 // Skip the common path components from filePath and OriginalDir.
1136 while (fileDirI != fileDirE && origDirI != origDirE &&
1137 *fileDirI == *origDirI) {
1138 ++fileDirI;
1139 ++origDirI;
1140 }
1141 for (; origDirI != origDirE; ++origDirI)
1142 path::append(currPCHPath, "..");
1143 path::append(currPCHPath, fileDirI, fileDirE);
1144 path::append(currPCHPath, path::filename(Filename));
1145 return currPCHPath.str();
1146}
1147
1148bool ASTReader::ReadSLocEntry(int ID) {
1149 if (ID == 0)
1150 return false;
1151
1152 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1153 Error("source location entry ID out-of-range for AST file");
1154 return true;
1155 }
1156
1157 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1158 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001159 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 unsigned BaseOffset = F->SLocEntryBaseOffset;
1161
1162 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001163 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1164 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 Error("incorrectly-formatted source location entry in AST file");
1166 return true;
1167 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001170 StringRef Blob;
1171 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 default:
1173 Error("incorrectly-formatted source location entry in AST file");
1174 return true;
1175
1176 case SM_SLOC_FILE_ENTRY: {
1177 // We will detect whether a file changed and return 'Failure' for it, but
1178 // we will also try to fail gracefully by setting up the SLocEntry.
1179 unsigned InputID = Record[4];
1180 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001181 const FileEntry *File = IF.getFile();
1182 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001183
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001184 // Note that we only check if a File was returned. If it was out-of-date
1185 // we have complained but we will continue creating a FileID to recover
1186 // gracefully.
1187 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 return true;
1189
1190 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1191 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1192 // This is the module's main file.
1193 IncludeLoc = getImportLocation(F);
1194 }
1195 SrcMgr::CharacteristicKind
1196 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1197 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1198 ID, BaseOffset + Record[0]);
1199 SrcMgr::FileInfo &FileInfo =
1200 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1201 FileInfo.NumCreatedFIDs = Record[5];
1202 if (Record[3])
1203 FileInfo.setHasLineDirectives();
1204
1205 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1206 unsigned NumFileDecls = Record[7];
1207 if (NumFileDecls) {
1208 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1209 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1210 NumFileDecls));
1211 }
1212
1213 const SrcMgr::ContentCache *ContentCache
1214 = SourceMgr.getOrCreateContentCache(File,
1215 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1216 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1217 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1218 unsigned Code = SLocEntryCursor.ReadCode();
1219 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001220 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001221
1222 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1223 Error("AST record has invalid code");
1224 return true;
1225 }
1226
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001227 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001228 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001229 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 }
1231
1232 break;
1233 }
1234
1235 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001236 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 unsigned Offset = Record[0];
1238 SrcMgr::CharacteristicKind
1239 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1240 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1241 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1242 IncludeLoc = getImportLocation(F);
1243 }
1244 unsigned Code = SLocEntryCursor.ReadCode();
1245 Record.clear();
1246 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001247 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001248
1249 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1250 Error("AST record has invalid code");
1251 return true;
1252 }
1253
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001254 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1255 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001256 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001257 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 break;
1259 }
1260
1261 case SM_SLOC_EXPANSION_ENTRY: {
1262 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1263 SourceMgr.createExpansionLoc(SpellingLoc,
1264 ReadSourceLocation(*F, Record[2]),
1265 ReadSourceLocation(*F, Record[3]),
1266 Record[4],
1267 ID,
1268 BaseOffset + Record[0]);
1269 break;
1270 }
1271 }
1272
1273 return false;
1274}
1275
1276std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1277 if (ID == 0)
1278 return std::make_pair(SourceLocation(), "");
1279
1280 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1281 Error("source location entry ID out-of-range for AST file");
1282 return std::make_pair(SourceLocation(), "");
1283 }
1284
1285 // Find which module file this entry lands in.
1286 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1287 if (M->Kind != MK_Module)
1288 return std::make_pair(SourceLocation(), "");
1289
1290 // FIXME: Can we map this down to a particular submodule? That would be
1291 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001292 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001293}
1294
1295/// \brief Find the location where the module F is imported.
1296SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1297 if (F->ImportLoc.isValid())
1298 return F->ImportLoc;
1299
1300 // Otherwise we have a PCH. It's considered to be "imported" at the first
1301 // location of its includer.
1302 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001303 // Main file is the importer.
1304 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1305 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 return F->ImportedBy[0]->FirstLoc;
1308}
1309
1310/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1311/// specified cursor. Read the abbreviations that are at the top of the block
1312/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001313bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 if (Cursor.EnterSubBlock(BlockID)) {
1315 Error("malformed block record in AST file");
1316 return Failure;
1317 }
1318
1319 while (true) {
1320 uint64_t Offset = Cursor.GetCurrentBitNo();
1321 unsigned Code = Cursor.ReadCode();
1322
1323 // We expect all abbrevs to be at the start of the block.
1324 if (Code != llvm::bitc::DEFINE_ABBREV) {
1325 Cursor.JumpToBit(Offset);
1326 return false;
1327 }
1328 Cursor.ReadAbbrevRecord();
1329 }
1330}
1331
Richard Smithe40f2ba2013-08-07 21:41:30 +00001332Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001333 unsigned &Idx) {
1334 Token Tok;
1335 Tok.startToken();
1336 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1337 Tok.setLength(Record[Idx++]);
1338 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1339 Tok.setIdentifierInfo(II);
1340 Tok.setKind((tok::TokenKind)Record[Idx++]);
1341 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1342 return Tok;
1343}
1344
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001345MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001346 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001347
1348 // Keep track of where we are in the stream, then jump back there
1349 // after reading this macro.
1350 SavedStreamPosition SavedPosition(Stream);
1351
1352 Stream.JumpToBit(Offset);
1353 RecordData Record;
1354 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001355 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001358 // Advance to the next record, but if we get to the end of the block, don't
1359 // pop it (removing all the abbreviations from the cursor) since we want to
1360 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001362 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1363
1364 switch (Entry.Kind) {
1365 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1366 case llvm::BitstreamEntry::Error:
1367 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001368 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001369 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001370 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 case llvm::BitstreamEntry::Record:
1372 // The interesting case.
1373 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 }
1375
1376 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 Record.clear();
1378 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001379 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001381 case PP_MACRO_DIRECTIVE_HISTORY:
1382 return Macro;
1383
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 case PP_MACRO_OBJECT_LIKE:
1385 case PP_MACRO_FUNCTION_LIKE: {
1386 // If we already have a macro, that means that we've hit the end
1387 // of the definition of the macro we were looking for. We're
1388 // done.
1389 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001390 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001391
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 unsigned NextIndex = 1; // Skip identifier ID.
1393 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001395 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001396 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001398 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1401 // Decode function-like macro info.
1402 bool isC99VarArgs = Record[NextIndex++];
1403 bool isGNUVarArgs = Record[NextIndex++];
1404 bool hasCommaPasting = Record[NextIndex++];
1405 MacroArgs.clear();
1406 unsigned NumArgs = Record[NextIndex++];
1407 for (unsigned i = 0; i != NumArgs; ++i)
1408 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1409
1410 // Install function-like macro info.
1411 MI->setIsFunctionLike();
1412 if (isC99VarArgs) MI->setIsC99Varargs();
1413 if (isGNUVarArgs) MI->setIsGNUVarargs();
1414 if (hasCommaPasting) MI->setHasCommaPasting();
1415 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1416 PP.getPreprocessorAllocator());
1417 }
1418
Guy Benyei11169dd2012-12-18 14:30:41 +00001419 // Remember that we saw this macro last so that we add the tokens that
1420 // form its body to it.
1421 Macro = MI;
1422
1423 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1424 Record[NextIndex]) {
1425 // We have a macro definition. Register the association
1426 PreprocessedEntityID
1427 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1428 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001429 PreprocessingRecord::PPEntityID
1430 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1431 MacroDefinition *PPDef =
1432 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1433 if (PPDef)
1434 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 }
1436
1437 ++NumMacrosRead;
1438 break;
1439 }
1440
1441 case PP_TOKEN: {
1442 // If we see a TOKEN before a PP_MACRO_*, then the file is
1443 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001444 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001445
John McCallf413f5e2013-05-03 00:10:13 +00001446 unsigned Idx = 0;
1447 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 Macro->AddTokenToBody(Tok);
1449 break;
1450 }
1451 }
1452 }
1453}
1454
1455PreprocessedEntityID
1456ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1457 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1458 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1459 assert(I != M.PreprocessedEntityRemap.end()
1460 && "Invalid index into preprocessed entity index remap");
1461
1462 return LocalID + I->second;
1463}
1464
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001465unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1466 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001467}
1468
1469HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001470HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1471 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1472 FE->getName() };
1473 return ikey;
1474}
Guy Benyei11169dd2012-12-18 14:30:41 +00001475
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1477 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 return false;
1479
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 if (strcmp(a.Filename, b.Filename) == 0)
1481 return true;
1482
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001484 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1486 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001487 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001488}
1489
1490std::pair<unsigned, unsigned>
1491HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001492 using namespace llvm::support;
1493 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001495 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497
1498HeaderFileInfoTrait::internal_key_type
1499HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001500 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001501 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001502 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1503 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001504 ikey.Filename = (const char *)d;
1505 return ikey;
1506}
1507
Guy Benyei11169dd2012-12-18 14:30:41 +00001508HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001509HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen) {
1511 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001512 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 HeaderFileInfo HFI;
1514 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001515 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1516 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 HFI.isImport = (Flags >> 5) & 0x01;
1518 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1519 HFI.DirInfo = (Flags >> 2) & 0x03;
1520 HFI.Resolved = (Flags >> 1) & 0x01;
1521 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001522 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1523 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1524 M, endian::readNext<uint32_t, little, unaligned>(d));
1525 if (unsigned FrameworkOffset =
1526 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 // The framework offset is 1 greater than the actual offset,
1528 // since 0 is used as an indicator for "no framework name".
1529 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1530 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1531 }
1532
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001533 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001534 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535 if (LocalSMID) {
1536 // This header is part of a module. Associate it with the module to enable
1537 // implicit module import.
1538 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1539 Module *Mod = Reader.getSubmodule(GlobalSMID);
1540 HFI.isModuleHeader = true;
1541 FileManager &FileMgr = Reader.getFileManager();
1542 ModuleMap &ModMap =
1543 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001544 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001545 }
1546 }
1547
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1549 (void)End;
1550
1551 // This HeaderFileInfo was externally loaded.
1552 HFI.External = true;
1553 return HFI;
1554}
1555
Richard Smith49f906a2014-03-01 00:08:04 +00001556void
1557ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1558 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001559 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001561 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001562 if (!Overrides.empty()) {
1563 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1564 OverrideData[0] = Overrides.size();
1565 for (unsigned I = 0; I != Overrides.size(); ++I)
1566 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1567 }
1568 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001569}
1570
1571void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1572 ModuleFile *M,
1573 uint64_t MacroDirectivesOffset) {
1574 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1575 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001576}
1577
1578void ASTReader::ReadDefinedMacros() {
1579 // Note that we are loading defined macros.
1580 Deserializing Macros(this);
1581
1582 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1583 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001584 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001585
1586 // If there was no preprocessor block, skip this file.
1587 if (!MacroCursor.getBitStreamReader())
1588 continue;
1589
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001590 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 Cursor.JumpToBit((*I)->MacroStartOffset);
1592
1593 RecordData Record;
1594 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001595 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1596
1597 switch (E.Kind) {
1598 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1599 case llvm::BitstreamEntry::Error:
1600 Error("malformed block record in AST file");
1601 return;
1602 case llvm::BitstreamEntry::EndBlock:
1603 goto NextCursor;
1604
1605 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001606 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001607 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001608 default: // Default behavior: ignore.
1609 break;
1610
1611 case PP_MACRO_OBJECT_LIKE:
1612 case PP_MACRO_FUNCTION_LIKE:
1613 getLocalIdentifier(**I, Record[0]);
1614 break;
1615
1616 case PP_TOKEN:
1617 // Ignore tokens.
1618 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001620 break;
1621 }
1622 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001623 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 }
1625}
1626
1627namespace {
1628 /// \brief Visitor class used to look up identifirs in an AST file.
1629 class IdentifierLookupVisitor {
1630 StringRef Name;
1631 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001632 unsigned &NumIdentifierLookups;
1633 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001635
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001637 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1638 unsigned &NumIdentifierLookups,
1639 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001640 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 NumIdentifierLookups(NumIdentifierLookups),
1642 NumIdentifierLookupHits(NumIdentifierLookupHits),
1643 Found()
1644 {
1645 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001646
1647 static bool visit(ModuleFile &M, void *UserData) {
1648 IdentifierLookupVisitor *This
1649 = static_cast<IdentifierLookupVisitor *>(UserData);
1650
1651 // If we've already searched this module file, skip it now.
1652 if (M.Generation <= This->PriorGeneration)
1653 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001654
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 ASTIdentifierLookupTable *IdTable
1656 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1657 if (!IdTable)
1658 return false;
1659
1660 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1661 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001662 ++This->NumIdentifierLookups;
1663 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 if (Pos == IdTable->end())
1665 return false;
1666
1667 // Dereferencing the iterator has the effect of building the
1668 // IdentifierInfo node and populating it with the various
1669 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001670 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 This->Found = *Pos;
1672 return true;
1673 }
1674
1675 // \brief Retrieve the identifier info found within the module
1676 // files.
1677 IdentifierInfo *getIdentifierInfo() const { return Found; }
1678 };
1679}
1680
1681void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1682 // Note that we are loading an identifier.
1683 Deserializing AnIdentifier(this);
1684
1685 unsigned PriorGeneration = 0;
1686 if (getContext().getLangOpts().Modules)
1687 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001688
1689 // If there is a global index, look there first to determine which modules
1690 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001691 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001692 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001693 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001694 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1695 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001696 }
1697 }
1698
Douglas Gregor7211ac12013-01-25 23:32:03 +00001699 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001700 NumIdentifierLookups,
1701 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001702 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 markIdentifierUpToDate(&II);
1704}
1705
1706void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1707 if (!II)
1708 return;
1709
1710 II->setOutOfDate(false);
1711
1712 // Update the generation for this identifier.
1713 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001714 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001715}
1716
Richard Smith49f906a2014-03-01 00:08:04 +00001717struct ASTReader::ModuleMacroInfo {
1718 SubmoduleID SubModID;
1719 MacroInfo *MI;
1720 SubmoduleID *Overrides;
1721 // FIXME: Remove this.
1722 ModuleFile *F;
1723
1724 bool isDefine() const { return MI; }
1725
1726 SubmoduleID getSubmoduleID() const { return SubModID; }
1727
Craig Topper00bbdcf2014-06-28 23:22:23 +00001728 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001729 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001730 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001731 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1732 }
1733
Richard Smithdaa69e02014-07-25 04:40:03 +00001734 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001735 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001736 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1737 getOverriddenSubmodules());
1738 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1739 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001740 }
1741};
1742
1743ASTReader::ModuleMacroInfo *
1744ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1745 ModuleMacroInfo Info;
1746
1747 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1748 if (ID & 1) {
1749 // Macro undefinition.
1750 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001751 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001752 } else {
1753 // Macro definition.
1754 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1755 assert(GMacID);
1756
1757 // If this macro has already been loaded, don't do so again.
1758 // FIXME: This is highly dubious. Multiple macro definitions can have the
1759 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1760 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001761 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001762
1763 Info.MI = getMacro(GMacID);
1764 Info.SubModID = Info.MI->getOwningModuleID();
1765 }
1766 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1767 Info.F = PMInfo.M;
1768
1769 return new (Context) ModuleMacroInfo(Info);
1770}
1771
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001772void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1773 const PendingMacroInfo &PMInfo) {
1774 assert(II);
1775
1776 if (PMInfo.M->Kind != MK_Module) {
1777 installPCHMacroDirectives(II, *PMInfo.M,
1778 PMInfo.PCHMacroData.MacroDirectivesOffset);
1779 return;
1780 }
Richard Smith49f906a2014-03-01 00:08:04 +00001781
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001782 // Module Macro.
1783
Richard Smith49f906a2014-03-01 00:08:04 +00001784 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1785 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786 return;
1787
Richard Smith49f906a2014-03-01 00:08:04 +00001788 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1789 if (Owner && Owner->NameVisibility == Module::Hidden) {
1790 // Macros in the owning module are hidden. Just remember this macro to
1791 // install if we make this module visible.
1792 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1793 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001794 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001795 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796}
1797
1798void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1799 ModuleFile &M, uint64_t Offset) {
1800 assert(M.Kind != MK_Module);
1801
1802 BitstreamCursor &Cursor = M.MacroCursor;
1803 SavedStreamPosition SavedPosition(Cursor);
1804 Cursor.JumpToBit(Offset);
1805
1806 llvm::BitstreamEntry Entry =
1807 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1808 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1809 Error("malformed block record in AST file");
1810 return;
1811 }
1812
1813 RecordData Record;
1814 PreprocessorRecordTypes RecType =
1815 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1816 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1817 Error("malformed block record in AST file");
1818 return;
1819 }
1820
1821 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001822 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001823 unsigned Idx = 0, N = Record.size();
1824 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001825 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001826 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001827 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1828 switch (K) {
1829 case MacroDirective::MD_Define: {
1830 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1831 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001832 SubmoduleID ImportedFrom = Record[Idx++];
1833 bool IsAmbiguous = Record[Idx++];
1834 llvm::SmallVector<unsigned, 4> Overrides;
1835 if (ImportedFrom) {
1836 Overrides.insert(Overrides.end(),
1837 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1838 Idx += Overrides.size() + 1;
1839 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001840 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001841 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1842 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001843 MD = DefMD;
1844 break;
1845 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001846 case MacroDirective::MD_Undefine: {
1847 SubmoduleID ImportedFrom = Record[Idx++];
1848 llvm::SmallVector<unsigned, 4> Overrides;
1849 if (ImportedFrom) {
1850 Overrides.insert(Overrides.end(),
1851 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1852 Idx += Overrides.size() + 1;
1853 }
1854 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001855 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001856 }
1857 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001858 bool isPublic = Record[Idx++];
1859 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1860 break;
1861 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862
1863 if (!Latest)
1864 Latest = MD;
1865 if (Earliest)
1866 Earliest->setPrevious(MD);
1867 Earliest = MD;
1868 }
1869
1870 PP.setLoadedMacroDirective(II, Latest);
1871}
1872
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001873/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001874/// modules.
1875static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001876 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001877 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001878 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1880 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001881 SourceManager &SrcMgr = Reader.getSourceManager();
1882 bool PrevInSystem
1883 = PrevOwner? PrevOwner->IsSystem
1884 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1885 bool NewInSystem
1886 = NewOwner? NewOwner->IsSystem
1887 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1888 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001889 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001890 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001891}
1892
Richard Smith49f906a2014-03-01 00:08:04 +00001893void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001894 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001895 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001896 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001897 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1898 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001899
Richard Smith49f906a2014-03-01 00:08:04 +00001900 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001901 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001902 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001903 auto HiddenIt = HiddenNamesMap.find(Owner);
1904 if (HiddenIt != HiddenNamesMap.end()) {
1905 HiddenNames &Hidden = HiddenIt->second;
1906 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1907 if (HI != Hidden.HiddenMacros.end()) {
1908 // Register the macro now so we don't lose it when we re-export.
1909 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001910
Richard Smithbb853c72014-08-13 01:23:33 +00001911 auto SubOverrides = HI->second->getOverriddenSubmodules();
1912 Hidden.HiddenMacros.erase(HI);
1913 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1914 }
Richard Smith49f906a2014-03-01 00:08:04 +00001915 }
1916
1917 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001918 Ambig.erase(
1919 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1920 return MD->getInfo()->getOwningModuleID() == OwnerID;
1921 }),
1922 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001923 }
1924}
1925
1926ASTReader::AmbiguousMacros *
1927ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001928 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001929 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001930 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001931 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001932 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001933
Craig Toppera13603a2014-05-22 05:54:18 +00001934 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1935 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001936 if (PrevDef && PrevDef->isAmbiguous()) {
1937 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1938 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1939 Ambig.push_back(PrevDef);
1940
Richard Smithdaa69e02014-07-25 04:40:03 +00001941 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001942
1943 if (!Ambig.empty())
1944 return &Ambig;
1945
1946 AmbiguousMacroDefs.erase(II);
1947 } else {
1948 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001949 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001950 if (PrevDef)
1951 Ambig.push_back(PrevDef);
1952
Richard Smithdaa69e02014-07-25 04:40:03 +00001953 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001954
1955 if (!Ambig.empty()) {
1956 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001957 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001958 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001959 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001960 }
Richard Smith49f906a2014-03-01 00:08:04 +00001961
1962 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001963 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001964}
1965
1966void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001967 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001968 assert(II && Owner);
1969
1970 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001971 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001972 // FIXME: If we made macros from this module visible but didn't provide a
1973 // source location for the import, we don't have a location for the macro.
1974 // Use the location at which the containing module file was first imported
1975 // for now.
1976 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001977 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001978 }
1979
Benjamin Kramer834652a2014-05-03 18:44:26 +00001980 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001981 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001982
Richard Smith49f906a2014-03-01 00:08:04 +00001983 // Create a synthetic macro definition corresponding to the import (or null
1984 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001985 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1986 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001987
1988 // If there's no ambiguity, just install the macro.
1989 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001990 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001991 return;
1992 }
1993 assert(!Prev->empty());
1994
1995 if (!MD) {
1996 // We imported a #undef that didn't remove all prior definitions. The most
1997 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00001998 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00001999 MacroInfo *NewMI = Prev->back()->getInfo();
2000 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002001 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2002
2003 // Install our #undef first so that we don't lose track of it. We'll replace
2004 // this with whichever macro definition ends up winning.
2005 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002006 }
2007
2008 // We're introducing a macro definition that creates or adds to an ambiguity.
2009 // We can resolve that ambiguity if this macro is token-for-token identical to
2010 // all of the existing definitions.
2011 MacroInfo *NewMI = MD->getInfo();
2012 assert(NewMI && "macro definition with no MacroInfo?");
2013 while (!Prev->empty()) {
2014 MacroInfo *PrevMI = Prev->back()->getInfo();
2015 assert(PrevMI && "macro definition with no MacroInfo?");
2016
2017 // Before marking the macros as ambiguous, check if this is a case where
2018 // both macros are in system headers. If so, we trust that the system
2019 // did not get it wrong. This also handles cases where Clang's own
2020 // headers have a different spelling of certain system macros:
2021 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2022 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2023 //
2024 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2025 // overrides the system limits.h's macros, so there's no conflict here.
2026 if (NewMI != PrevMI &&
2027 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2028 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2029 break;
2030
2031 // The previous definition is the same as this one (or both are defined in
2032 // system modules so we can assume they're equivalent); we don't need to
2033 // track it any more.
2034 Prev->pop_back();
2035 }
2036
2037 if (!Prev->empty())
2038 MD->setAmbiguous(true);
2039
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002040 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002041}
2042
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002043ASTReader::InputFileInfo
2044ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002045 // Go find this input file.
2046 BitstreamCursor &Cursor = F.InputFilesCursor;
2047 SavedStreamPosition SavedPosition(Cursor);
2048 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2049
2050 unsigned Code = Cursor.ReadCode();
2051 RecordData Record;
2052 StringRef Blob;
2053
2054 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2055 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2056 "invalid record type for input file");
2057 (void)Result;
2058
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002059 std::string Filename;
2060 off_t StoredSize;
2061 time_t StoredTime;
2062 bool Overridden;
2063
Ben Langmuir198c1682014-03-07 07:27:49 +00002064 assert(Record[0] == ID && "Bogus stored ID or offset");
2065 StoredSize = static_cast<off_t>(Record[1]);
2066 StoredTime = static_cast<time_t>(Record[2]);
2067 Overridden = static_cast<bool>(Record[3]);
2068 Filename = Blob;
2069 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002070
Hans Wennborg73945142014-03-14 17:45:06 +00002071 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2072 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002073}
2074
2075std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002076 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002077}
2078
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002079InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 // If this ID is bogus, just return an empty input file.
2081 if (ID == 0 || ID > F.InputFilesLoaded.size())
2082 return InputFile();
2083
2084 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002085 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 return F.InputFilesLoaded[ID-1];
2087
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002088 if (F.InputFilesLoaded[ID-1].isNotFound())
2089 return InputFile();
2090
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002092 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 SavedStreamPosition SavedPosition(Cursor);
2094 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2095
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002096 InputFileInfo FI = readInputFileInfo(F, ID);
2097 off_t StoredSize = FI.StoredSize;
2098 time_t StoredTime = FI.StoredTime;
2099 bool Overridden = FI.Overridden;
2100 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002101
Ben Langmuir198c1682014-03-07 07:27:49 +00002102 const FileEntry *File
2103 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2104 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2105
2106 // If we didn't find the file, resolve it relative to the
2107 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002108 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002109 F.OriginalDir != CurrentDir) {
2110 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2111 F.OriginalDir,
2112 CurrentDir);
2113 if (!Resolved.empty())
2114 File = FileMgr.getFile(Resolved);
2115 }
2116
2117 // For an overridden file, create a virtual file with the stored
2118 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002119 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002120 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2121 }
2122
Craig Toppera13603a2014-05-22 05:54:18 +00002123 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002124 if (Complain) {
2125 std::string ErrorStr = "could not find file '";
2126 ErrorStr += Filename;
2127 ErrorStr += "' referenced by AST file";
2128 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002130 // Record that we didn't find the file.
2131 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2132 return InputFile();
2133 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002134
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 // Check if there was a request to override the contents of the file
2136 // that was part of the precompiled header. Overridding such a file
2137 // can lead to problems when lexing using the source locations from the
2138 // PCH.
2139 SourceManager &SM = getSourceManager();
2140 if (!Overridden && SM.isFileOverridden(File)) {
2141 if (Complain)
2142 Error(diag::err_fe_pch_file_overridden, Filename);
2143 // After emitting the diagnostic, recover by disabling the override so
2144 // that the original file will be used.
2145 SM.disableFileContentsOverride(File);
2146 // The FileEntry is a virtual file entry with the size of the contents
2147 // that would override the original contents. Set it to the original's
2148 // size/time.
2149 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2150 StoredSize, StoredTime);
2151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002152
Ben Langmuir198c1682014-03-07 07:27:49 +00002153 bool IsOutOfDate = false;
2154
2155 // For an overridden file, there is nothing to validate.
2156 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002157#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 // In our regression testing, the Windows file system seems to
2159 // have inconsistent modification times that sometimes
2160 // erroneously trigger this error-handling path.
2161 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002162#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002163 )) {
2164 if (Complain) {
2165 // Build a list of the PCH imports that got us here (in reverse).
2166 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2167 while (ImportStack.back()->ImportedBy.size() > 0)
2168 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002169
Ben Langmuir198c1682014-03-07 07:27:49 +00002170 // The top-level PCH is stale.
2171 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2172 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002173
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 // Print the import stack.
2175 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2176 Diag(diag::note_pch_required_by)
2177 << Filename << ImportStack[0]->FileName;
2178 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002179 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002180 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002181 }
2182
Ben Langmuir198c1682014-03-07 07:27:49 +00002183 if (!Diags.isDiagnosticInFlight())
2184 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 }
2186
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 }
2189
Ben Langmuir198c1682014-03-07 07:27:49 +00002190 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2191
2192 // Note that we've loaded this input file.
2193 F.InputFilesLoaded[ID-1] = IF;
2194 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002195}
2196
2197const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2198 ModuleFile &M = ModuleMgr.getPrimaryModule();
2199 std::string Filename = filenameStrRef;
2200 MaybeAddSystemRootToFilename(M, Filename);
2201 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002202 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002203 M.OriginalDir != CurrentDir) {
2204 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2205 M.OriginalDir,
2206 CurrentDir);
2207 if (!resolved.empty())
2208 File = FileMgr.getFile(resolved);
2209 }
2210
2211 return File;
2212}
2213
2214/// \brief If we are loading a relocatable PCH file, and the filename is
2215/// not an absolute path, add the system root to the beginning of the file
2216/// name.
2217void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2218 std::string &Filename) {
2219 // If this is not a relocatable PCH file, there's nothing to do.
2220 if (!M.RelocatablePCH)
2221 return;
2222
2223 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2224 return;
2225
2226 if (isysroot.empty()) {
2227 // If no system root was given, default to '/'
2228 Filename.insert(Filename.begin(), '/');
2229 return;
2230 }
2231
2232 unsigned Length = isysroot.size();
2233 if (isysroot[Length - 1] != '/')
2234 Filename.insert(Filename.begin(), '/');
2235
2236 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2237}
2238
2239ASTReader::ASTReadResult
2240ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002241 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002242 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002244 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002245
2246 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2247 Error("malformed block record in AST file");
2248 return Failure;
2249 }
2250
2251 // Read all of the records and blocks in the control block.
2252 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002253 while (1) {
2254 llvm::BitstreamEntry Entry = Stream.advance();
2255
2256 switch (Entry.Kind) {
2257 case llvm::BitstreamEntry::Error:
2258 Error("malformed block record in AST file");
2259 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002260 case llvm::BitstreamEntry::EndBlock: {
2261 // Validate input files.
2262 const HeaderSearchOptions &HSOpts =
2263 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002264
2265 // All user input files reside at the index range [0, Record[1]), and
2266 // system input files reside at [Record[1], Record[0]).
2267 // Record is the one from INPUT_FILE_OFFSETS.
2268 unsigned NumInputs = Record[0];
2269 unsigned NumUserInputs = Record[1];
2270
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002271 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002272 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002273 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002275
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002276 // If we are reading a module, we will create a verification timestamp,
2277 // so we verify all input files. Otherwise, verify only user input
2278 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002279
2280 unsigned N = NumUserInputs;
2281 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002282 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2283 N = NumInputs;
2284
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002285 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002286 InputFile IF = getInputFile(F, I+1, Complain);
2287 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002289 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002291
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002292 if (Listener)
2293 Listener->visitModuleFile(F.FileName);
2294
Ben Langmuircb69b572014-03-07 06:40:32 +00002295 if (Listener && Listener->needsInputFileVisitation()) {
2296 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2297 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002298 for (unsigned I = 0; I < N; ++I) {
2299 bool IsSystem = I >= NumUserInputs;
2300 InputFileInfo FI = readInputFileInfo(F, I+1);
2301 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2302 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002303 }
2304
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002306 }
2307
Chris Lattnere7b154b2013-01-19 21:39:22 +00002308 case llvm::BitstreamEntry::SubBlock:
2309 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 case INPUT_FILES_BLOCK_ID:
2311 F.InputFilesCursor = Stream;
2312 if (Stream.SkipBlock() || // Skip with the main cursor
2313 // Read the abbreviations
2314 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2315 Error("malformed block record in AST file");
2316 return Failure;
2317 }
2318 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002319
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002321 if (Stream.SkipBlock()) {
2322 Error("malformed block record in AST file");
2323 return Failure;
2324 }
2325 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002327
2328 case llvm::BitstreamEntry::Record:
2329 // The interesting case.
2330 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 }
2332
2333 // Read and process a record.
2334 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002335 StringRef Blob;
2336 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 case METADATA: {
2338 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2339 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002340 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2341 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 return VersionMismatch;
2343 }
2344
2345 bool hasErrors = Record[5];
2346 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2347 Diag(diag::err_pch_with_compiler_errors);
2348 return HadErrors;
2349 }
2350
2351 F.RelocatablePCH = Record[4];
2352
2353 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002354 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2356 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002357 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 return VersionMismatch;
2359 }
2360 break;
2361 }
2362
2363 case IMPORTS: {
2364 // Load each of the imported PCH files.
2365 unsigned Idx = 0, N = Record.size();
2366 while (Idx < N) {
2367 // Read information about the AST file.
2368 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2369 // The import location will be the local one for now; we will adjust
2370 // all import locations of module imports after the global source
2371 // location info are setup.
2372 SourceLocation ImportLoc =
2373 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002374 off_t StoredSize = (off_t)Record[Idx++];
2375 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 unsigned Length = Record[Idx++];
2377 SmallString<128> ImportedFile(Record.begin() + Idx,
2378 Record.begin() + Idx + Length);
2379 Idx += Length;
2380
2381 // Load the AST file.
2382 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002383 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 ClientLoadCapabilities)) {
2385 case Failure: return Failure;
2386 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002387 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 case OutOfDate: return OutOfDate;
2389 case VersionMismatch: return VersionMismatch;
2390 case ConfigurationMismatch: return ConfigurationMismatch;
2391 case HadErrors: return HadErrors;
2392 case Success: break;
2393 }
2394 }
2395 break;
2396 }
2397
2398 case LANGUAGE_OPTIONS: {
2399 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2400 if (Listener && &F == *ModuleMgr.begin() &&
2401 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002402 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 return ConfigurationMismatch;
2404 break;
2405 }
2406
2407 case TARGET_OPTIONS: {
2408 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2409 if (Listener && &F == *ModuleMgr.begin() &&
2410 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002411 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 return ConfigurationMismatch;
2413 break;
2414 }
2415
2416 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002417 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 if (Listener && &F == *ModuleMgr.begin() &&
2419 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002420 !DisableValidation)
2421 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 break;
2423 }
2424
2425 case FILE_SYSTEM_OPTIONS: {
2426 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2427 if (Listener && &F == *ModuleMgr.begin() &&
2428 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002429 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 return ConfigurationMismatch;
2431 break;
2432 }
2433
2434 case HEADER_SEARCH_OPTIONS: {
2435 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2436 if (Listener && &F == *ModuleMgr.begin() &&
2437 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002438 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 return ConfigurationMismatch;
2440 break;
2441 }
2442
2443 case PREPROCESSOR_OPTIONS: {
2444 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2445 if (Listener && &F == *ModuleMgr.begin() &&
2446 ParsePreprocessorOptions(Record, Complain, *Listener,
2447 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002448 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 return ConfigurationMismatch;
2450 break;
2451 }
2452
2453 case ORIGINAL_FILE:
2454 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002455 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2457 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2458 break;
2459
2460 case ORIGINAL_FILE_ID:
2461 F.OriginalSourceFileID = FileID::get(Record[0]);
2462 break;
2463
2464 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002465 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 break;
2467
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002468 case MODULE_NAME:
2469 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002470 if (Listener)
2471 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002472 break;
2473
2474 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002475 if (ASTReadResult Result =
2476 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2477 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002479 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 F.InputFilesLoaded.resize(Record[0]);
2481 break;
2482 }
2483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002484}
2485
Ben Langmuir2c9af442014-04-10 17:57:43 +00002486ASTReader::ASTReadResult
2487ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002488 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002489
2490 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2491 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 }
2494
2495 // Read all of the records and blocks for the AST file.
2496 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002497 while (1) {
2498 llvm::BitstreamEntry Entry = Stream.advance();
2499
2500 switch (Entry.Kind) {
2501 case llvm::BitstreamEntry::Error:
2502 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002503 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002504 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002505 // Outside of C++, we do not store a lookup map for the translation unit.
2506 // Instead, mark it as needing a lookup map to be built if this module
2507 // contains any declarations lexically within it (which it always does!).
2508 // This usually has no cost, since we very rarely need the lookup map for
2509 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002511 if (DC->hasExternalLexicalStorage() &&
2512 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514
Ben Langmuir2c9af442014-04-10 17:57:43 +00002515 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002517 case llvm::BitstreamEntry::SubBlock:
2518 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 case DECLTYPES_BLOCK_ID:
2520 // We lazily load the decls block, but we want to set up the
2521 // DeclsCursor cursor to point into it. Clone our current bitcode
2522 // cursor to it, enter the block and read the abbrevs in that block.
2523 // With the main cursor, we just skip over it.
2524 F.DeclsCursor = Stream;
2525 if (Stream.SkipBlock() || // Skip with the main cursor.
2526 // Read the abbrevs.
2527 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2528 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002529 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 }
2531 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002532
Guy Benyei11169dd2012-12-18 14:30:41 +00002533 case PREPROCESSOR_BLOCK_ID:
2534 F.MacroCursor = Stream;
2535 if (!PP.getExternalSource())
2536 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002537
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 if (Stream.SkipBlock() ||
2539 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2540 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002541 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 }
2543 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2544 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 case PREPROCESSOR_DETAIL_BLOCK_ID:
2547 F.PreprocessorDetailCursor = Stream;
2548 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002551 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002552 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2556
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 if (!PP.getPreprocessingRecord())
2558 PP.createPreprocessingRecord();
2559 if (!PP.getPreprocessingRecord()->getExternalSource())
2560 PP.getPreprocessingRecord()->SetExternalSource(*this);
2561 break;
2562
2563 case SOURCE_MANAGER_BLOCK_ID:
2564 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002565 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002567
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002569 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2570 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002572
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002574 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 if (Stream.SkipBlock() ||
2576 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2577 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 }
2580 CommentsCursors.push_back(std::make_pair(C, &F));
2581 break;
2582 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002583
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 if (Stream.SkipBlock()) {
2586 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002588 }
2589 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 }
2591 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592
2593 case llvm::BitstreamEntry::Record:
2594 // The interesting case.
2595 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 }
2597
2598 // Read and process a record.
2599 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002600 StringRef Blob;
2601 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 default: // Default behavior: ignore.
2603 break;
2604
2605 case TYPE_OFFSET: {
2606 if (F.LocalNumTypes != 0) {
2607 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002608 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002610 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 F.LocalNumTypes = Record[0];
2612 unsigned LocalBaseTypeIndex = Record[1];
2613 F.BaseTypeIndex = getTotalNumTypes();
2614
2615 if (F.LocalNumTypes > 0) {
2616 // Introduce the global -> local mapping for types within this module.
2617 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2618
2619 // Introduce the local -> global mapping for types within this module.
2620 F.TypeRemap.insertOrReplace(
2621 std::make_pair(LocalBaseTypeIndex,
2622 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002623
2624 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626 break;
2627 }
2628
2629 case DECL_OFFSET: {
2630 if (F.LocalNumDecls != 0) {
2631 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002632 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002634 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 F.LocalNumDecls = Record[0];
2636 unsigned LocalBaseDeclID = Record[1];
2637 F.BaseDeclID = getTotalNumDecls();
2638
2639 if (F.LocalNumDecls > 0) {
2640 // Introduce the global -> local mapping for declarations within this
2641 // module.
2642 GlobalDeclMap.insert(
2643 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2644
2645 // Introduce the local -> global mapping for declarations within this
2646 // module.
2647 F.DeclRemap.insertOrReplace(
2648 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2649
2650 // Introduce the global -> local mapping for declarations within this
2651 // module.
2652 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002653
Ben Langmuir52ca6782014-10-20 16:27:32 +00002654 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 break;
2657 }
2658
2659 case TU_UPDATE_LEXICAL: {
2660 DeclContext *TU = Context.getTranslationUnitDecl();
2661 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002662 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002664 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 TU->setHasExternalLexicalStorage(true);
2666 break;
2667 }
2668
2669 case UPDATE_VISIBLE: {
2670 unsigned Idx = 0;
2671 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2672 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002673 ASTDeclContextNameLookupTable::Create(
2674 (const unsigned char *)Blob.data() + Record[Idx++],
2675 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2676 (const unsigned char *)Blob.data(),
2677 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002678 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002679 auto *DC = cast<DeclContext>(D);
2680 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002681 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2682 delete LookupTable;
2683 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 } else
2685 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2686 break;
2687 }
2688
2689 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002692 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2693 (const unsigned char *)F.IdentifierTableData + Record[0],
2694 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2695 (const unsigned char *)F.IdentifierTableData,
2696 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002697
2698 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2699 }
2700 break;
2701
2702 case IDENTIFIER_OFFSET: {
2703 if (F.LocalNumIdentifiers != 0) {
2704 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002705 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002707 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 F.LocalNumIdentifiers = Record[0];
2709 unsigned LocalBaseIdentifierID = Record[1];
2710 F.BaseIdentifierID = getTotalNumIdentifiers();
2711
2712 if (F.LocalNumIdentifiers > 0) {
2713 // Introduce the global -> local mapping for identifiers within this
2714 // module.
2715 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2716 &F));
2717
2718 // Introduce the local -> global mapping for identifiers within this
2719 // module.
2720 F.IdentifierRemap.insertOrReplace(
2721 std::make_pair(LocalBaseIdentifierID,
2722 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002723
Ben Langmuir52ca6782014-10-20 16:27:32 +00002724 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2725 + F.LocalNumIdentifiers);
2726 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 break;
2728 }
2729
Ben Langmuir332aafe2014-01-31 01:06:56 +00002730 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002732 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 break;
2734
2735 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002736 if (SpecialTypes.empty()) {
2737 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2738 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2739 break;
2740 }
2741
2742 if (SpecialTypes.size() != Record.size()) {
2743 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002744 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002745 }
2746
2747 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2748 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2749 if (!SpecialTypes[I])
2750 SpecialTypes[I] = ID;
2751 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2752 // merge step?
2753 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 break;
2755
2756 case STATISTICS:
2757 TotalNumStatements += Record[0];
2758 TotalNumMacros += Record[1];
2759 TotalLexicalDeclContexts += Record[2];
2760 TotalVisibleDeclContexts += Record[3];
2761 break;
2762
2763 case UNUSED_FILESCOPED_DECLS:
2764 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2765 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2766 break;
2767
2768 case DELEGATING_CTORS:
2769 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2770 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2771 break;
2772
2773 case WEAK_UNDECLARED_IDENTIFIERS:
2774 if (Record.size() % 4 != 0) {
2775 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002776 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 }
2778
2779 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2780 // files. This isn't the way to do it :)
2781 WeakUndeclaredIdentifiers.clear();
2782
2783 // Translate the weak, undeclared identifiers into global IDs.
2784 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2785 WeakUndeclaredIdentifiers.push_back(
2786 getGlobalIdentifierID(F, Record[I++]));
2787 WeakUndeclaredIdentifiers.push_back(
2788 getGlobalIdentifierID(F, Record[I++]));
2789 WeakUndeclaredIdentifiers.push_back(
2790 ReadSourceLocation(F, Record, I).getRawEncoding());
2791 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2792 }
2793 break;
2794
Richard Smith78165b52013-01-10 23:43:47 +00002795 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002796 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002797 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 break;
2799
2800 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002801 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 F.LocalNumSelectors = Record[0];
2803 unsigned LocalBaseSelectorID = Record[1];
2804 F.BaseSelectorID = getTotalNumSelectors();
2805
2806 if (F.LocalNumSelectors > 0) {
2807 // Introduce the global -> local mapping for selectors within this
2808 // module.
2809 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2810
2811 // Introduce the local -> global mapping for selectors within this
2812 // module.
2813 F.SelectorRemap.insertOrReplace(
2814 std::make_pair(LocalBaseSelectorID,
2815 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002816
2817 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 }
2819 break;
2820 }
2821
2822 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002823 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 if (Record[0])
2825 F.SelectorLookupTable
2826 = ASTSelectorLookupTable::Create(
2827 F.SelectorLookupTableData + Record[0],
2828 F.SelectorLookupTableData,
2829 ASTSelectorLookupTrait(*this, F));
2830 TotalNumMethodPoolEntries += Record[1];
2831 break;
2832
2833 case REFERENCED_SELECTOR_POOL:
2834 if (!Record.empty()) {
2835 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2836 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2837 Record[Idx++]));
2838 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2839 getRawEncoding());
2840 }
2841 }
2842 break;
2843
2844 case PP_COUNTER_VALUE:
2845 if (!Record.empty() && Listener)
2846 Listener->ReadCounter(F, Record[0]);
2847 break;
2848
2849 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002850 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 F.NumFileSortedDecls = Record[0];
2852 break;
2853
2854 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002855 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 F.LocalNumSLocEntries = Record[0];
2857 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002858 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002859 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 SLocSpaceSize);
2861 // Make our entry in the range map. BaseID is negative and growing, so
2862 // we invert it. Because we invert it, though, we need the other end of
2863 // the range.
2864 unsigned RangeStart =
2865 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2866 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2867 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2868
2869 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2870 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2871 GlobalSLocOffsetMap.insert(
2872 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2873 - SLocSpaceSize,&F));
2874
2875 // Initialize the remapping table.
2876 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002877 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002879 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2881
2882 TotalNumSLocEntries += F.LocalNumSLocEntries;
2883 break;
2884 }
2885
2886 case MODULE_OFFSET_MAP: {
2887 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002888 const unsigned char *Data = (const unsigned char*)Blob.data();
2889 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002890
2891 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2892 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2893 F.SLocRemap.insert(std::make_pair(0U, 0));
2894 F.SLocRemap.insert(std::make_pair(2U, 1));
2895 }
2896
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002898 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2899 RemapBuilder;
2900 RemapBuilder SLocRemap(F.SLocRemap);
2901 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2902 RemapBuilder MacroRemap(F.MacroRemap);
2903 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2904 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2905 RemapBuilder SelectorRemap(F.SelectorRemap);
2906 RemapBuilder DeclRemap(F.DeclRemap);
2907 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002908
2909 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002910 using namespace llvm::support;
2911 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 StringRef Name = StringRef((const char*)Data, Len);
2913 Data += Len;
2914 ModuleFile *OM = ModuleMgr.lookup(Name);
2915 if (!OM) {
2916 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919
Justin Bogner57ba0b22014-03-28 22:03:24 +00002920 uint32_t SLocOffset =
2921 endian::readNext<uint32_t, little, unaligned>(Data);
2922 uint32_t IdentifierIDOffset =
2923 endian::readNext<uint32_t, little, unaligned>(Data);
2924 uint32_t MacroIDOffset =
2925 endian::readNext<uint32_t, little, unaligned>(Data);
2926 uint32_t PreprocessedEntityIDOffset =
2927 endian::readNext<uint32_t, little, unaligned>(Data);
2928 uint32_t SubmoduleIDOffset =
2929 endian::readNext<uint32_t, little, unaligned>(Data);
2930 uint32_t SelectorIDOffset =
2931 endian::readNext<uint32_t, little, unaligned>(Data);
2932 uint32_t DeclIDOffset =
2933 endian::readNext<uint32_t, little, unaligned>(Data);
2934 uint32_t TypeIndexOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936
Ben Langmuir785180e2014-10-20 16:27:30 +00002937 uint32_t None = std::numeric_limits<uint32_t>::max();
2938
2939 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2940 RemapBuilder &Remap) {
2941 if (Offset != None)
2942 Remap.insert(std::make_pair(Offset,
2943 static_cast<int>(BaseOffset - Offset)));
2944 };
2945 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2946 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2947 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2948 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2949 PreprocessedEntityRemap);
2950 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2951 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2952 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2953 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002954
2955 // Global -> local mappings.
2956 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2957 }
2958 break;
2959 }
2960
2961 case SOURCE_MANAGER_LINE_TABLE:
2962 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002963 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 break;
2965
2966 case SOURCE_LOCATION_PRELOADS: {
2967 // Need to transform from the local view (1-based IDs) to the global view,
2968 // which is based off F.SLocEntryBaseID.
2969 if (!F.PreloadSLocEntries.empty()) {
2970 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002971 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 }
2973
2974 F.PreloadSLocEntries.swap(Record);
2975 break;
2976 }
2977
2978 case EXT_VECTOR_DECLS:
2979 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2980 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2981 break;
2982
2983 case VTABLE_USES:
2984 if (Record.size() % 3 != 0) {
2985 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 }
2988
2989 // Later tables overwrite earlier ones.
2990 // FIXME: Modules will have some trouble with this. This is clearly not
2991 // the right way to do this.
2992 VTableUses.clear();
2993
2994 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2995 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2996 VTableUses.push_back(
2997 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2998 VTableUses.push_back(Record[Idx++]);
2999 }
3000 break;
3001
3002 case DYNAMIC_CLASSES:
3003 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3004 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3005 break;
3006
3007 case PENDING_IMPLICIT_INSTANTIATIONS:
3008 if (PendingInstantiations.size() % 2 != 0) {
3009 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003010 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 }
3012
3013 if (Record.size() % 2 != 0) {
3014 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003015 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 }
3017
3018 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3019 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3020 PendingInstantiations.push_back(
3021 ReadSourceLocation(F, Record, I).getRawEncoding());
3022 }
3023 break;
3024
3025 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003026 if (Record.size() != 2) {
3027 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003028 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003029 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3031 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3032 break;
3033
3034 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003035 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3036 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3037 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003038
3039 unsigned LocalBasePreprocessedEntityID = Record[0];
3040
3041 unsigned StartingID;
3042 if (!PP.getPreprocessingRecord())
3043 PP.createPreprocessingRecord();
3044 if (!PP.getPreprocessingRecord()->getExternalSource())
3045 PP.getPreprocessingRecord()->SetExternalSource(*this);
3046 StartingID
3047 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003048 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 F.BasePreprocessedEntityID = StartingID;
3050
3051 if (F.NumPreprocessedEntities > 0) {
3052 // Introduce the global -> local mapping for preprocessed entities in
3053 // this module.
3054 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3055
3056 // Introduce the local -> global mapping for preprocessed entities in
3057 // this module.
3058 F.PreprocessedEntityRemap.insertOrReplace(
3059 std::make_pair(LocalBasePreprocessedEntityID,
3060 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3061 }
3062
3063 break;
3064 }
3065
3066 case DECL_UPDATE_OFFSETS: {
3067 if (Record.size() % 2 != 0) {
3068 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003069 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003071 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3072 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3073 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3074
3075 // If we've already loaded the decl, perform the updates when we finish
3076 // loading this block.
3077 if (Decl *D = GetExistingDecl(ID))
3078 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 break;
3081 }
3082
3083 case DECL_REPLACEMENTS: {
3084 if (Record.size() % 3 != 0) {
3085 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 }
3088 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3089 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3090 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3091 break;
3092 }
3093
3094 case OBJC_CATEGORIES_MAP: {
3095 if (F.LocalNumObjCCategoriesInMap != 0) {
3096 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003097 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
3099
3100 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003101 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 break;
3103 }
3104
3105 case OBJC_CATEGORIES:
3106 F.ObjCCategories.swap(Record);
3107 break;
3108
3109 case CXX_BASE_SPECIFIER_OFFSETS: {
3110 if (F.LocalNumCXXBaseSpecifiers != 0) {
3111 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003112 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 }
3114
3115 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003116 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3118 break;
3119 }
3120
3121 case DIAG_PRAGMA_MAPPINGS:
3122 if (F.PragmaDiagMappings.empty())
3123 F.PragmaDiagMappings.swap(Record);
3124 else
3125 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3126 Record.begin(), Record.end());
3127 break;
3128
3129 case CUDA_SPECIAL_DECL_REFS:
3130 // Later tables overwrite earlier ones.
3131 // FIXME: Modules will have trouble with this.
3132 CUDASpecialDeclRefs.clear();
3133 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3134 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3135 break;
3136
3137 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003138 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 if (Record[0]) {
3141 F.HeaderFileInfoTable
3142 = HeaderFileInfoLookupTable::Create(
3143 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3144 (const unsigned char *)F.HeaderFileInfoTableData,
3145 HeaderFileInfoTrait(*this, F,
3146 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003147 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003148
3149 PP.getHeaderSearchInfo().SetExternalSource(this);
3150 if (!PP.getHeaderSearchInfo().getExternalLookup())
3151 PP.getHeaderSearchInfo().SetExternalLookup(this);
3152 }
3153 break;
3154 }
3155
3156 case FP_PRAGMA_OPTIONS:
3157 // Later tables overwrite earlier ones.
3158 FPPragmaOptions.swap(Record);
3159 break;
3160
3161 case OPENCL_EXTENSIONS:
3162 // Later tables overwrite earlier ones.
3163 OpenCLExtensions.swap(Record);
3164 break;
3165
3166 case TENTATIVE_DEFINITIONS:
3167 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3168 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3169 break;
3170
3171 case KNOWN_NAMESPACES:
3172 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3173 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3174 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003175
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003176 case UNDEFINED_BUT_USED:
3177 if (UndefinedButUsed.size() % 2 != 0) {
3178 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003179 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003180 }
3181
3182 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003183 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003184 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003185 }
3186 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003187 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3188 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003189 ReadSourceLocation(F, Record, I).getRawEncoding());
3190 }
3191 break;
3192
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 case IMPORTED_MODULES: {
3194 if (F.Kind != MK_Module) {
3195 // If we aren't loading a module (which has its own exports), make
3196 // all of the imported modules visible.
3197 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003198 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3199 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3200 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3201 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003202 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 }
3204 }
3205 break;
3206 }
3207
3208 case LOCAL_REDECLARATIONS: {
3209 F.RedeclarationChains.swap(Record);
3210 break;
3211 }
3212
3213 case LOCAL_REDECLARATIONS_MAP: {
3214 if (F.LocalNumRedeclarationsInMap != 0) {
3215 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003216 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003217 }
3218
3219 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003220 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 break;
3222 }
3223
3224 case MERGED_DECLARATIONS: {
3225 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3226 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3227 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3228 for (unsigned N = Record[Idx++]; N > 0; --N)
3229 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3230 }
3231 break;
3232 }
3233
3234 case MACRO_OFFSET: {
3235 if (F.LocalNumMacros != 0) {
3236 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003237 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003239 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 F.LocalNumMacros = Record[0];
3241 unsigned LocalBaseMacroID = Record[1];
3242 F.BaseMacroID = getTotalNumMacros();
3243
3244 if (F.LocalNumMacros > 0) {
3245 // Introduce the global -> local mapping for macros within this module.
3246 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3247
3248 // Introduce the local -> global mapping for macros within this module.
3249 F.MacroRemap.insertOrReplace(
3250 std::make_pair(LocalBaseMacroID,
3251 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003252
3253 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 }
3255 break;
3256 }
3257
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003258 case MACRO_TABLE: {
3259 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 break;
3261 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003262
3263 case LATE_PARSED_TEMPLATE: {
3264 LateParsedTemplates.append(Record.begin(), Record.end());
3265 break;
3266 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003267
3268 case OPTIMIZE_PRAGMA_OPTIONS:
3269 if (Record.size() != 1) {
3270 Error("invalid pragma optimize record");
3271 return Failure;
3272 }
3273 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3274 break;
Nico Weber72889432014-09-06 01:25:55 +00003275
3276 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3277 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3278 UnusedLocalTypedefNameCandidates.push_back(
3279 getGlobalDeclID(F, Record[I]));
3280 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 }
3282 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003283}
3284
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003285ASTReader::ASTReadResult
3286ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3287 const ModuleFile *ImportedBy,
3288 unsigned ClientLoadCapabilities) {
3289 unsigned Idx = 0;
3290 F.ModuleMapPath = ReadString(Record, Idx);
3291
3292 // Try to resolve ModuleName in the current header search context and
3293 // verify that it is found in the same module map file as we saved. If the
3294 // top-level AST file is a main file, skip this check because there is no
3295 // usable header search context.
3296 assert(!F.ModuleName.empty() &&
3297 "MODULE_NAME should come before MOUDLE_MAP_FILE");
3298 if (F.Kind == MK_Module && (*ModuleMgr.begin())->Kind != MK_MainFile) {
3299 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3300 if (!M) {
3301 assert(ImportedBy && "top-level import should be verified");
3302 if ((ClientLoadCapabilities & ARR_Missing) == 0)
3303 Diag(diag::err_imported_module_not_found)
3304 << F.ModuleName << ImportedBy->FileName;
3305 return Missing;
3306 }
3307
3308 // Check the primary module map file.
3309 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3310 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3311 const FileEntry *ModMap = Map.getModuleMapFileForUniquing(M);
3312 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3313 assert(ModMap && "found module is missing module map file");
3314 assert(M->Name == F.ModuleName && "found module with different name");
3315 assert(ImportedBy && "top-level import should be verified");
3316 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3317 Diag(diag::err_imported_module_modmap_changed)
3318 << F.ModuleName << ImportedBy->FileName
3319 << ModMap->getName() << F.ModuleMapPath;
3320 return OutOfDate;
3321 }
3322
3323 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3324 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3325 // FIXME: we should use input files rather than storing names.
3326 std::string Filename = ReadString(Record, Idx);
3327 const FileEntry *F =
3328 FileMgr.getFile(Filename, false, false);
3329 if (F == nullptr) {
3330 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3331 Error("could not find file '" + Filename +"' referenced by AST file");
3332 return OutOfDate;
3333 }
3334 AdditionalStoredMaps.insert(F);
3335 }
3336
3337 // Check any additional module map files (e.g. module.private.modulemap)
3338 // that are not in the pcm.
3339 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3340 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3341 // Remove files that match
3342 // Note: SmallPtrSet::erase is really remove
3343 if (!AdditionalStoredMaps.erase(ModMap)) {
3344 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3345 Diag(diag::err_module_different_modmap)
3346 << F.ModuleName << /*new*/0 << ModMap->getName();
3347 return OutOfDate;
3348 }
3349 }
3350 }
3351
3352 // Check any additional module map files that are in the pcm, but not
3353 // found in header search. Cases that match are already removed.
3354 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3355 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3356 Diag(diag::err_module_different_modmap)
3357 << F.ModuleName << /*not new*/1 << ModMap->getName();
3358 return OutOfDate;
3359 }
3360 }
3361
3362 if (Listener)
3363 Listener->ReadModuleMapFile(F.ModuleMapPath);
3364 return Success;
3365}
3366
3367
Douglas Gregorc1489562013-02-12 23:36:21 +00003368/// \brief Move the given method to the back of the global list of methods.
3369static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3370 // Find the entry for this selector in the method pool.
3371 Sema::GlobalMethodPool::iterator Known
3372 = S.MethodPool.find(Method->getSelector());
3373 if (Known == S.MethodPool.end())
3374 return;
3375
3376 // Retrieve the appropriate method list.
3377 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3378 : Known->second.second;
3379 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003380 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003381 if (!Found) {
3382 if (List->Method == Method) {
3383 Found = true;
3384 } else {
3385 // Keep searching.
3386 continue;
3387 }
3388 }
3389
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003390 if (List->getNext())
3391 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003392 else
3393 List->Method = Method;
3394 }
3395}
3396
Richard Smithe657bbd2014-07-18 22:13:40 +00003397void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3398 bool FromFinalization) {
3399 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003400 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003401 bool wasHidden = D->Hidden;
3402 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003403
Richard Smith49f906a2014-03-01 00:08:04 +00003404 if (wasHidden && SemaObj) {
3405 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3406 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003407 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 }
3409 }
Richard Smith49f906a2014-03-01 00:08:04 +00003410
Richard Smithe657bbd2014-07-18 22:13:40 +00003411 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3412 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003413 for (const auto &Macro : Names.HiddenMacros) {
3414 if (FromFinalization)
3415 PP.appendMacroDirective(Macro.first,
3416 Macro.second->import(PP, SourceLocation()));
3417 else
3418 installImportedMacro(Macro.first, Macro.second, Owner);
3419 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003420}
3421
Richard Smith49f906a2014-03-01 00:08:04 +00003422void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003423 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003424 SourceLocation ImportLoc,
3425 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003426 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003427 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003428 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003430 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003431
3432 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003433 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 // there is nothing more to do.
3435 continue;
3436 }
Richard Smith49f906a2014-03-01 00:08:04 +00003437
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 if (!Mod->isAvailable()) {
3439 // Modules that aren't available cannot be made visible.
3440 continue;
3441 }
3442
3443 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003444 if (NameVisibility >= Module::MacrosVisible &&
3445 Mod->NameVisibility < Module::MacrosVisible)
3446 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003448
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 // If we've already deserialized any names from this module,
3450 // mark them as visible.
3451 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3452 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003453 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003454 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003455 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3456 /*FromFinalization*/false);
3457 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3458 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003460
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003462 SmallVector<Module *, 16> Exports;
3463 Mod->getExportedModules(Exports);
3464 for (SmallVectorImpl<Module *>::iterator
3465 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3466 Module *Exported = *I;
3467 if (Visited.insert(Exported))
3468 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003470
3471 // Detect any conflicts.
3472 if (Complain) {
3473 assert(ImportLoc.isValid() && "Missing import location");
3474 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3475 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3476 Diag(ImportLoc, diag::warn_module_conflict)
3477 << Mod->getFullModuleName()
3478 << Mod->Conflicts[I].Other->getFullModuleName()
3479 << Mod->Conflicts[I].Message;
3480 // FIXME: Need note where the other module was imported.
3481 }
3482 }
3483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 }
3485}
3486
Douglas Gregore060e572013-01-25 01:03:03 +00003487bool ASTReader::loadGlobalIndex() {
3488 if (GlobalIndex)
3489 return false;
3490
3491 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3492 !Context.getLangOpts().Modules)
3493 return true;
3494
3495 // Try to load the global index.
3496 TriedLoadingGlobalIndex = true;
3497 StringRef ModuleCachePath
3498 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3499 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003500 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003501 if (!Result.first)
3502 return true;
3503
3504 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003505 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003506 return false;
3507}
3508
3509bool ASTReader::isGlobalIndexUnavailable() const {
3510 return Context.getLangOpts().Modules && UseGlobalIndex &&
3511 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3512}
3513
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003514static void updateModuleTimestamp(ModuleFile &MF) {
3515 // Overwrite the timestamp file contents so that file's mtime changes.
3516 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003517 std::error_code EC;
3518 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3519 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003520 return;
3521 OS << "Timestamp file\n";
3522}
3523
Guy Benyei11169dd2012-12-18 14:30:41 +00003524ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3525 ModuleKind Type,
3526 SourceLocation ImportLoc,
3527 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003528 llvm::SaveAndRestore<SourceLocation>
3529 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3530
Richard Smithd1c46742014-04-30 02:24:17 +00003531 // Defer any pending actions until we get to the end of reading the AST file.
3532 Deserializing AnASTFile(this);
3533
Guy Benyei11169dd2012-12-18 14:30:41 +00003534 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003535 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003536
3537 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003538 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003540 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003541 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 ClientLoadCapabilities)) {
3543 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003544 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 case OutOfDate:
3546 case VersionMismatch:
3547 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003548 case HadErrors: {
3549 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3550 for (const ImportedModule &IM : Loaded)
3551 LoadedSet.insert(IM.Mod);
3552
Douglas Gregor7029ce12013-03-19 00:28:20 +00003553 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003554 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003555 Context.getLangOpts().Modules
3556 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003557 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003558
3559 // If we find that any modules are unusable, the global index is going
3560 // to be out-of-date. Just remove it.
3561 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003562 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003564 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 case Success:
3566 break;
3567 }
3568
3569 // Here comes stuff that we only do once the entire chain is loaded.
3570
3571 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003572 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3573 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 M != MEnd; ++M) {
3575 ModuleFile &F = *M->Mod;
3576
3577 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003578 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3579 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003580
3581 // Once read, set the ModuleFile bit base offset and update the size in
3582 // bits of all files we've seen.
3583 F.GlobalBitOffset = TotalModulesSizeInBits;
3584 TotalModulesSizeInBits += F.SizeInBits;
3585 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3586
3587 // Preload SLocEntries.
3588 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3589 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3590 // Load it through the SourceManager and don't call ReadSLocEntry()
3591 // directly because the entry may have already been loaded in which case
3592 // calling ReadSLocEntry() directly would trigger an assertion in
3593 // SourceManager.
3594 SourceMgr.getLoadedSLocEntryByID(Index);
3595 }
3596 }
3597
Douglas Gregor603cd862013-03-22 18:50:14 +00003598 // Setup the import locations and notify the module manager that we've
3599 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003600 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3601 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003602 M != MEnd; ++M) {
3603 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003604
3605 ModuleMgr.moduleFileAccepted(&F);
3606
3607 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003608 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 if (!M->ImportedBy)
3610 F.ImportLoc = M->ImportLoc;
3611 else
3612 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3613 M->ImportLoc.getRawEncoding());
3614 }
3615
3616 // Mark all of the identifiers in the identifier table as being out of date,
3617 // so that various accessors know to check the loaded modules when the
3618 // identifier is used.
3619 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3620 IdEnd = PP.getIdentifierTable().end();
3621 Id != IdEnd; ++Id)
3622 Id->second->setOutOfDate(true);
3623
3624 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003625 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3626 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3628 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003629
3630 switch (Unresolved.Kind) {
3631 case UnresolvedModuleRef::Conflict:
3632 if (ResolvedMod) {
3633 Module::Conflict Conflict;
3634 Conflict.Other = ResolvedMod;
3635 Conflict.Message = Unresolved.String.str();
3636 Unresolved.Mod->Conflicts.push_back(Conflict);
3637 }
3638 continue;
3639
3640 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 if (ResolvedMod)
3642 Unresolved.Mod->Imports.push_back(ResolvedMod);
3643 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003644
Douglas Gregorfb912652013-03-20 21:10:35 +00003645 case UnresolvedModuleRef::Export:
3646 if (ResolvedMod || Unresolved.IsWildcard)
3647 Unresolved.Mod->Exports.push_back(
3648 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3649 continue;
3650 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003652 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003653
3654 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3655 // Might be unnecessary as use declarations are only used to build the
3656 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003657
3658 InitializeContext();
3659
Richard Smith3d8e97e2013-10-18 06:54:39 +00003660 if (SemaObj)
3661 UpdateSema();
3662
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 if (DeserializationListener)
3664 DeserializationListener->ReaderInitialized(this);
3665
3666 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3667 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3668 PrimaryModule.OriginalSourceFileID
3669 = FileID::get(PrimaryModule.SLocEntryBaseID
3670 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3671
3672 // If this AST file is a precompiled preamble, then set the
3673 // preamble file ID of the source manager to the file source file
3674 // from which the preamble was built.
3675 if (Type == MK_Preamble) {
3676 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3677 } else if (Type == MK_MainFile) {
3678 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3679 }
3680 }
3681
3682 // For any Objective-C class definitions we have already loaded, make sure
3683 // that we load any additional categories.
3684 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3685 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3686 ObjCClassesLoaded[I],
3687 PreviousGeneration);
3688 }
Douglas Gregore060e572013-01-25 01:03:03 +00003689
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003690 if (PP.getHeaderSearchInfo()
3691 .getHeaderSearchOpts()
3692 .ModulesValidateOncePerBuildSession) {
3693 // Now we are certain that the module and all modules it depends on are
3694 // up to date. Create or update timestamp files for modules that are
3695 // located in the module cache (not for PCH files that could be anywhere
3696 // in the filesystem).
3697 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3698 ImportedModule &M = Loaded[I];
3699 if (M.Mod->Kind == MK_Module) {
3700 updateModuleTimestamp(*M.Mod);
3701 }
3702 }
3703 }
3704
Guy Benyei11169dd2012-12-18 14:30:41 +00003705 return Success;
3706}
3707
3708ASTReader::ASTReadResult
3709ASTReader::ReadASTCore(StringRef FileName,
3710 ModuleKind Type,
3711 SourceLocation ImportLoc,
3712 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003713 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003714 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 unsigned ClientLoadCapabilities) {
3716 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003718 ModuleManager::AddModuleResult AddResult
3719 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003720 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003721 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003722
Douglas Gregor7029ce12013-03-19 00:28:20 +00003723 switch (AddResult) {
3724 case ModuleManager::AlreadyLoaded:
3725 return Success;
3726
3727 case ModuleManager::NewlyLoaded:
3728 // Load module file below.
3729 break;
3730
3731 case ModuleManager::Missing:
3732 // The module file was missing; if the client handle handle, that, return
3733 // it.
3734 if (ClientLoadCapabilities & ARR_Missing)
3735 return Missing;
3736
3737 // Otherwise, return an error.
3738 {
3739 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3740 + ErrorStr;
3741 Error(Msg);
3742 }
3743 return Failure;
3744
3745 case ModuleManager::OutOfDate:
3746 // We couldn't load the module file because it is out-of-date. If the
3747 // client can handle out-of-date, return it.
3748 if (ClientLoadCapabilities & ARR_OutOfDate)
3749 return OutOfDate;
3750
3751 // Otherwise, return an error.
3752 {
3753 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3754 + ErrorStr;
3755 Error(Msg);
3756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 return Failure;
3758 }
3759
Douglas Gregor7029ce12013-03-19 00:28:20 +00003760 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003761
3762 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3763 // module?
3764 if (FileName != "-") {
3765 CurrentDir = llvm::sys::path::parent_path(FileName);
3766 if (CurrentDir.empty()) CurrentDir = ".";
3767 }
3768
3769 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003770 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 Stream.init(F.StreamFile);
3772 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3773
3774 // Sniff for the signature.
3775 if (Stream.Read(8) != 'C' ||
3776 Stream.Read(8) != 'P' ||
3777 Stream.Read(8) != 'C' ||
3778 Stream.Read(8) != 'H') {
3779 Diag(diag::err_not_a_pch_file) << FileName;
3780 return Failure;
3781 }
3782
3783 // This is used for compatibility with older PCH formats.
3784 bool HaveReadControlBlock = false;
3785
Chris Lattnerefa77172013-01-20 00:00:22 +00003786 while (1) {
3787 llvm::BitstreamEntry Entry = Stream.advance();
3788
3789 switch (Entry.Kind) {
3790 case llvm::BitstreamEntry::Error:
3791 case llvm::BitstreamEntry::EndBlock:
3792 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003793 Error("invalid record at top-level of AST file");
3794 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003795
3796 case llvm::BitstreamEntry::SubBlock:
3797 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 }
3799
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003801 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003802 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3803 if (Stream.ReadBlockInfoBlock()) {
3804 Error("malformed BlockInfoBlock in AST file");
3805 return Failure;
3806 }
3807 break;
3808 case CONTROL_BLOCK_ID:
3809 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003810 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003811 case Success:
3812 break;
3813
3814 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003815 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 case OutOfDate: return OutOfDate;
3817 case VersionMismatch: return VersionMismatch;
3818 case ConfigurationMismatch: return ConfigurationMismatch;
3819 case HadErrors: return HadErrors;
3820 }
3821 break;
3822 case AST_BLOCK_ID:
3823 if (!HaveReadControlBlock) {
3824 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003825 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 return VersionMismatch;
3827 }
3828
3829 // Record that we've loaded this module.
3830 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3831 return Success;
3832
3833 default:
3834 if (Stream.SkipBlock()) {
3835 Error("malformed block record in AST file");
3836 return Failure;
3837 }
3838 break;
3839 }
3840 }
3841
3842 return Success;
3843}
3844
3845void ASTReader::InitializeContext() {
3846 // If there's a listener, notify them that we "read" the translation unit.
3847 if (DeserializationListener)
3848 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3849 Context.getTranslationUnitDecl());
3850
Guy Benyei11169dd2012-12-18 14:30:41 +00003851 // FIXME: Find a better way to deal with collisions between these
3852 // built-in types. Right now, we just ignore the problem.
3853
3854 // Load the special types.
3855 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3856 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3857 if (!Context.CFConstantStringTypeDecl)
3858 Context.setCFConstantStringType(GetType(String));
3859 }
3860
3861 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3862 QualType FileType = GetType(File);
3863 if (FileType.isNull()) {
3864 Error("FILE type is NULL");
3865 return;
3866 }
3867
3868 if (!Context.FILEDecl) {
3869 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3870 Context.setFILEDecl(Typedef->getDecl());
3871 else {
3872 const TagType *Tag = FileType->getAs<TagType>();
3873 if (!Tag) {
3874 Error("Invalid FILE type in AST file");
3875 return;
3876 }
3877 Context.setFILEDecl(Tag->getDecl());
3878 }
3879 }
3880 }
3881
3882 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3883 QualType Jmp_bufType = GetType(Jmp_buf);
3884 if (Jmp_bufType.isNull()) {
3885 Error("jmp_buf type is NULL");
3886 return;
3887 }
3888
3889 if (!Context.jmp_bufDecl) {
3890 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3891 Context.setjmp_bufDecl(Typedef->getDecl());
3892 else {
3893 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3894 if (!Tag) {
3895 Error("Invalid jmp_buf type in AST file");
3896 return;
3897 }
3898 Context.setjmp_bufDecl(Tag->getDecl());
3899 }
3900 }
3901 }
3902
3903 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3904 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3905 if (Sigjmp_bufType.isNull()) {
3906 Error("sigjmp_buf type is NULL");
3907 return;
3908 }
3909
3910 if (!Context.sigjmp_bufDecl) {
3911 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3912 Context.setsigjmp_bufDecl(Typedef->getDecl());
3913 else {
3914 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3915 assert(Tag && "Invalid sigjmp_buf type in AST file");
3916 Context.setsigjmp_bufDecl(Tag->getDecl());
3917 }
3918 }
3919 }
3920
3921 if (unsigned ObjCIdRedef
3922 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3923 if (Context.ObjCIdRedefinitionType.isNull())
3924 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3925 }
3926
3927 if (unsigned ObjCClassRedef
3928 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3929 if (Context.ObjCClassRedefinitionType.isNull())
3930 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3931 }
3932
3933 if (unsigned ObjCSelRedef
3934 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3935 if (Context.ObjCSelRedefinitionType.isNull())
3936 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3937 }
3938
3939 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3940 QualType Ucontext_tType = GetType(Ucontext_t);
3941 if (Ucontext_tType.isNull()) {
3942 Error("ucontext_t type is NULL");
3943 return;
3944 }
3945
3946 if (!Context.ucontext_tDecl) {
3947 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3948 Context.setucontext_tDecl(Typedef->getDecl());
3949 else {
3950 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3951 assert(Tag && "Invalid ucontext_t type in AST file");
3952 Context.setucontext_tDecl(Tag->getDecl());
3953 }
3954 }
3955 }
3956 }
3957
3958 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3959
3960 // If there were any CUDA special declarations, deserialize them.
3961 if (!CUDASpecialDeclRefs.empty()) {
3962 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3963 Context.setcudaConfigureCallDecl(
3964 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3965 }
Richard Smith56be7542014-03-21 00:33:59 +00003966
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003968 // FIXME: This does not make macro-only imports visible again. It also doesn't
3969 // make #includes mapped to module imports visible.
3970 for (auto &Import : ImportedModules) {
3971 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003972 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003973 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003974 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 }
3976 ImportedModules.clear();
3977}
3978
3979void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00003980 while (!HiddenNamesMap.empty()) {
3981 auto HiddenNames = std::move(*HiddenNamesMap.begin());
3982 HiddenNamesMap.erase(HiddenNamesMap.begin());
3983 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3984 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00003985 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003986}
3987
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003988/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3989/// cursor into the start of the given block ID, returning false on success and
3990/// true on failure.
3991static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003992 while (1) {
3993 llvm::BitstreamEntry Entry = Cursor.advance();
3994 switch (Entry.Kind) {
3995 case llvm::BitstreamEntry::Error:
3996 case llvm::BitstreamEntry::EndBlock:
3997 return true;
3998
3999 case llvm::BitstreamEntry::Record:
4000 // Ignore top-level records.
4001 Cursor.skipRecord(Entry.ID);
4002 break;
4003
4004 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004005 if (Entry.ID == BlockID) {
4006 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004007 return true;
4008 // Found it!
4009 return false;
4010 }
4011
4012 if (Cursor.SkipBlock())
4013 return true;
4014 }
4015 }
4016}
4017
Guy Benyei11169dd2012-12-18 14:30:41 +00004018/// \brief Retrieve the name of the original source file name
4019/// directly from the AST file, without actually loading the AST
4020/// file.
4021std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4022 FileManager &FileMgr,
4023 DiagnosticsEngine &Diags) {
4024 // Open the AST file.
4025 std::string ErrStr;
Rafael Espindola6406f7b2014-08-26 19:54:40 +00004026 std::unique_ptr<llvm::MemoryBuffer> Buffer =
4027 FileMgr.getBufferForFile(ASTFileName, &ErrStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 if (!Buffer) {
4029 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
4030 return std::string();
4031 }
4032
4033 // Initialize the stream
4034 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004035 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4037 (const unsigned char *)Buffer->getBufferEnd());
4038 Stream.init(StreamFile);
4039
4040 // Sniff for the signature.
4041 if (Stream.Read(8) != 'C' ||
4042 Stream.Read(8) != 'P' ||
4043 Stream.Read(8) != 'C' ||
4044 Stream.Read(8) != 'H') {
4045 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4046 return std::string();
4047 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004048
Chris Lattnere7b154b2013-01-19 21:39:22 +00004049 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004050 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004051 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4052 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004053 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004055 // Scan for ORIGINAL_FILE inside the control block.
4056 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004057 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004058 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004059 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4060 return std::string();
4061
4062 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4063 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4064 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004066
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004068 StringRef Blob;
4069 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4070 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004072}
4073
4074namespace {
4075 class SimplePCHValidator : public ASTReaderListener {
4076 const LangOptions &ExistingLangOpts;
4077 const TargetOptions &ExistingTargetOpts;
4078 const PreprocessorOptions &ExistingPPOpts;
4079 FileManager &FileMgr;
4080
4081 public:
4082 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4083 const TargetOptions &ExistingTargetOpts,
4084 const PreprocessorOptions &ExistingPPOpts,
4085 FileManager &FileMgr)
4086 : ExistingLangOpts(ExistingLangOpts),
4087 ExistingTargetOpts(ExistingTargetOpts),
4088 ExistingPPOpts(ExistingPPOpts),
4089 FileMgr(FileMgr)
4090 {
4091 }
4092
Craig Topper3e89dfe2014-03-13 02:13:41 +00004093 bool ReadLanguageOptions(const LangOptions &LangOpts,
4094 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004095 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004097 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4098 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004099 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004101 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4102 bool Complain,
4103 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004104 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004105 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 }
4107 };
4108}
4109
4110bool ASTReader::readASTFileControlBlock(StringRef Filename,
4111 FileManager &FileMgr,
4112 ASTReaderListener &Listener) {
4113 // Open the AST file.
4114 std::string ErrStr;
Rafael Espindola6406f7b2014-08-26 19:54:40 +00004115 std::unique_ptr<llvm::MemoryBuffer> Buffer =
4116 FileMgr.getBufferForFile(Filename, &ErrStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 if (!Buffer) {
4118 return true;
4119 }
4120
4121 // Initialize the stream
4122 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004123 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4125 (const unsigned char *)Buffer->getBufferEnd());
4126 Stream.init(StreamFile);
4127
4128 // Sniff for the signature.
4129 if (Stream.Read(8) != 'C' ||
4130 Stream.Read(8) != 'P' ||
4131 Stream.Read(8) != 'C' ||
4132 Stream.Read(8) != 'H') {
4133 return true;
4134 }
4135
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004136 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004137 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004138 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004139
4140 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004141 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004142 BitstreamCursor InputFilesCursor;
4143 if (NeedsInputFiles) {
4144 InputFilesCursor = Stream;
4145 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4146 return true;
4147
4148 // Read the abbreviations
4149 while (true) {
4150 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4151 unsigned Code = InputFilesCursor.ReadCode();
4152
4153 // We expect all abbrevs to be at the start of the block.
4154 if (Code != llvm::bitc::DEFINE_ABBREV) {
4155 InputFilesCursor.JumpToBit(Offset);
4156 break;
4157 }
4158 InputFilesCursor.ReadAbbrevRecord();
4159 }
4160 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004161
4162 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004164 while (1) {
4165 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4166 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4167 return false;
4168
4169 if (Entry.Kind != llvm::BitstreamEntry::Record)
4170 return true;
4171
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004173 StringRef Blob;
4174 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004175 switch ((ControlRecordTypes)RecCode) {
4176 case METADATA: {
4177 if (Record[0] != VERSION_MAJOR)
4178 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004179
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004180 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004181 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004182
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004183 break;
4184 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004185 case MODULE_NAME:
4186 Listener.ReadModuleName(Blob);
4187 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004188 case MODULE_MAP_FILE: {
4189 unsigned Idx = 0;
4190 Listener.ReadModuleMapFile(ReadString(Record, Idx));
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004191 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004192 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004193 case LANGUAGE_OPTIONS:
4194 if (ParseLanguageOptions(Record, false, Listener))
4195 return true;
4196 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004198 case TARGET_OPTIONS:
4199 if (ParseTargetOptions(Record, false, Listener))
4200 return true;
4201 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004202
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004203 case DIAGNOSTIC_OPTIONS:
4204 if (ParseDiagnosticOptions(Record, false, Listener))
4205 return true;
4206 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004207
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004208 case FILE_SYSTEM_OPTIONS:
4209 if (ParseFileSystemOptions(Record, false, Listener))
4210 return true;
4211 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004212
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004213 case HEADER_SEARCH_OPTIONS:
4214 if (ParseHeaderSearchOptions(Record, false, Listener))
4215 return true;
4216 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004218 case PREPROCESSOR_OPTIONS: {
4219 std::string IgnoredSuggestedPredefines;
4220 if (ParsePreprocessorOptions(Record, false, Listener,
4221 IgnoredSuggestedPredefines))
4222 return true;
4223 break;
4224 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004225
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004226 case INPUT_FILE_OFFSETS: {
4227 if (!NeedsInputFiles)
4228 break;
4229
4230 unsigned NumInputFiles = Record[0];
4231 unsigned NumUserFiles = Record[1];
4232 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4233 for (unsigned I = 0; I != NumInputFiles; ++I) {
4234 // Go find this input file.
4235 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004236
4237 if (isSystemFile && !NeedsSystemInputFiles)
4238 break; // the rest are system input files
4239
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004240 BitstreamCursor &Cursor = InputFilesCursor;
4241 SavedStreamPosition SavedPosition(Cursor);
4242 Cursor.JumpToBit(InputFileOffs[I]);
4243
4244 unsigned Code = Cursor.ReadCode();
4245 RecordData Record;
4246 StringRef Blob;
4247 bool shouldContinue = false;
4248 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4249 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004250 bool Overridden = static_cast<bool>(Record[3]);
4251 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004252 break;
4253 }
4254 if (!shouldContinue)
4255 break;
4256 }
4257 break;
4258 }
4259
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004260 default:
4261 // No other validation to perform.
4262 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 }
4264 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004265}
4266
4267
4268bool ASTReader::isAcceptableASTFile(StringRef Filename,
4269 FileManager &FileMgr,
4270 const LangOptions &LangOpts,
4271 const TargetOptions &TargetOpts,
4272 const PreprocessorOptions &PPOpts) {
4273 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4274 return !readASTFileControlBlock(Filename, FileMgr, validator);
4275}
4276
Ben Langmuir2c9af442014-04-10 17:57:43 +00004277ASTReader::ASTReadResult
4278ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 // Enter the submodule block.
4280 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4281 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004282 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 }
4284
4285 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4286 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004287 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 RecordData Record;
4289 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004290 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4291
4292 switch (Entry.Kind) {
4293 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4294 case llvm::BitstreamEntry::Error:
4295 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004296 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004297 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004298 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004299 case llvm::BitstreamEntry::Record:
4300 // The interesting case.
4301 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004303
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004305 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004307 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 default: // Default behavior: ignore.
4309 break;
4310
4311 case SUBMODULE_DEFINITION: {
4312 if (First) {
4313 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004314 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 }
4316
Douglas Gregor8d932422013-03-20 03:59:18 +00004317 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004318 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004319 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 }
4321
Chris Lattner0e6c9402013-01-20 02:38:54 +00004322 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004323 unsigned Idx = 0;
4324 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4325 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4326 bool IsFramework = Record[Idx++];
4327 bool IsExplicit = Record[Idx++];
4328 bool IsSystem = Record[Idx++];
4329 bool IsExternC = Record[Idx++];
4330 bool InferSubmodules = Record[Idx++];
4331 bool InferExplicitSubmodules = Record[Idx++];
4332 bool InferExportWildcard = Record[Idx++];
4333 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004334
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004335 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004336 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004338
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 // Retrieve this (sub)module from the module map, creating it if
4340 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004341 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004343
4344 // FIXME: set the definition loc for CurrentModule, or call
4345 // ModMap.setInferredModuleAllowedBy()
4346
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4348 if (GlobalIndex >= SubmodulesLoaded.size() ||
4349 SubmodulesLoaded[GlobalIndex]) {
4350 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004351 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004353
Douglas Gregor7029ce12013-03-19 00:28:20 +00004354 if (!ParentModule) {
4355 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4356 if (CurFile != F.File) {
4357 if (!Diags.isDiagnosticInFlight()) {
4358 Diag(diag::err_module_file_conflict)
4359 << CurrentModule->getTopLevelModuleName()
4360 << CurFile->getName()
4361 << F.File->getName();
4362 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004363 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004364 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004365 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004366
4367 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004368 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004369
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 CurrentModule->IsFromModuleFile = true;
4371 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004372 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 CurrentModule->InferSubmodules = InferSubmodules;
4374 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4375 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004376 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 if (DeserializationListener)
4378 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4379
4380 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004381
Douglas Gregorfb912652013-03-20 21:10:35 +00004382 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004383 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004384 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004385 CurrentModule->UnresolvedConflicts.clear();
4386 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 break;
4388 }
4389
4390 case SUBMODULE_UMBRELLA_HEADER: {
4391 if (First) {
4392 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395
4396 if (!CurrentModule)
4397 break;
4398
Chris Lattner0e6c9402013-01-20 02:38:54 +00004399 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 if (!CurrentModule->getUmbrellaHeader())
4401 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4402 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004403 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4404 Error("mismatched umbrella headers in submodule");
4405 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 }
4407 }
4408 break;
4409 }
4410
4411 case SUBMODULE_HEADER: {
4412 if (First) {
4413 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004414 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 }
4416
4417 if (!CurrentModule)
4418 break;
4419
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004420 // We lazily associate headers with their modules via the HeaderInfoTable.
4421 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4422 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 break;
4424 }
4425
4426 case SUBMODULE_EXCLUDED_HEADER: {
4427 if (First) {
4428 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004429 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 }
4431
4432 if (!CurrentModule)
4433 break;
4434
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004435 // We lazily associate headers with their modules via the HeaderInfoTable.
4436 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4437 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 break;
4439 }
4440
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004441 case SUBMODULE_PRIVATE_HEADER: {
4442 if (First) {
4443 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004444 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004445 }
4446
4447 if (!CurrentModule)
4448 break;
4449
4450 // We lazily associate headers with their modules via the HeaderInfoTable.
4451 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4452 // of complete filenames or remove it entirely.
4453 break;
4454 }
4455
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 case SUBMODULE_TOPHEADER: {
4457 if (First) {
4458 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004459 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461
4462 if (!CurrentModule)
4463 break;
4464
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004465 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 break;
4467 }
4468
4469 case SUBMODULE_UMBRELLA_DIR: {
4470 if (First) {
4471 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004472 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
4475 if (!CurrentModule)
4476 break;
4477
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004479 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 if (!CurrentModule->getUmbrellaDir())
4481 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4482 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004483 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4484 Error("mismatched umbrella directories in submodule");
4485 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 }
4487 }
4488 break;
4489 }
4490
4491 case SUBMODULE_METADATA: {
4492 if (!First) {
4493 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004494 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 }
4496 First = false;
4497
4498 F.BaseSubmoduleID = getTotalNumSubmodules();
4499 F.LocalNumSubmodules = Record[0];
4500 unsigned LocalBaseSubmoduleID = Record[1];
4501 if (F.LocalNumSubmodules > 0) {
4502 // Introduce the global -> local mapping for submodules within this
4503 // module.
4504 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4505
4506 // Introduce the local -> global mapping for submodules within this
4507 // module.
4508 F.SubmoduleRemap.insertOrReplace(
4509 std::make_pair(LocalBaseSubmoduleID,
4510 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004511
Ben Langmuir52ca6782014-10-20 16:27:32 +00004512 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4513 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 break;
4515 }
4516
4517 case SUBMODULE_IMPORTS: {
4518 if (First) {
4519 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004520 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
4523 if (!CurrentModule)
4524 break;
4525
4526 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004527 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 Unresolved.File = &F;
4529 Unresolved.Mod = CurrentModule;
4530 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004531 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004533 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535 break;
4536 }
4537
4538 case SUBMODULE_EXPORTS: {
4539 if (First) {
4540 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004541 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 }
4543
4544 if (!CurrentModule)
4545 break;
4546
4547 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004548 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 Unresolved.File = &F;
4550 Unresolved.Mod = CurrentModule;
4551 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004552 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004554 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 }
4556
4557 // Once we've loaded the set of exports, there's no reason to keep
4558 // the parsed, unresolved exports around.
4559 CurrentModule->UnresolvedExports.clear();
4560 break;
4561 }
4562 case SUBMODULE_REQUIRES: {
4563 if (First) {
4564 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004565 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 }
4567
4568 if (!CurrentModule)
4569 break;
4570
Richard Smitha3feee22013-10-28 22:18:19 +00004571 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 Context.getTargetInfo());
4573 break;
4574 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004575
4576 case SUBMODULE_LINK_LIBRARY:
4577 if (First) {
4578 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004579 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004580 }
4581
4582 if (!CurrentModule)
4583 break;
4584
4585 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004586 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004587 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004588
4589 case SUBMODULE_CONFIG_MACRO:
4590 if (First) {
4591 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004592 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004593 }
4594
4595 if (!CurrentModule)
4596 break;
4597
4598 CurrentModule->ConfigMacros.push_back(Blob.str());
4599 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004600
4601 case SUBMODULE_CONFLICT: {
4602 if (First) {
4603 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004604 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004605 }
4606
4607 if (!CurrentModule)
4608 break;
4609
4610 UnresolvedModuleRef Unresolved;
4611 Unresolved.File = &F;
4612 Unresolved.Mod = CurrentModule;
4613 Unresolved.ID = Record[0];
4614 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4615 Unresolved.IsWildcard = false;
4616 Unresolved.String = Blob;
4617 UnresolvedModuleRefs.push_back(Unresolved);
4618 break;
4619 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 }
4621 }
4622}
4623
4624/// \brief Parse the record that corresponds to a LangOptions data
4625/// structure.
4626///
4627/// This routine parses the language options from the AST file and then gives
4628/// them to the AST listener if one is set.
4629///
4630/// \returns true if the listener deems the file unacceptable, false otherwise.
4631bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4632 bool Complain,
4633 ASTReaderListener &Listener) {
4634 LangOptions LangOpts;
4635 unsigned Idx = 0;
4636#define LANGOPT(Name, Bits, Default, Description) \
4637 LangOpts.Name = Record[Idx++];
4638#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4639 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4640#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004641#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4642#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004643
4644 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4645 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4646 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4647
4648 unsigned Length = Record[Idx++];
4649 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4650 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004651
4652 Idx += Length;
4653
4654 // Comment options.
4655 for (unsigned N = Record[Idx++]; N; --N) {
4656 LangOpts.CommentOpts.BlockCommandNames.push_back(
4657 ReadString(Record, Idx));
4658 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004659 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004660
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 return Listener.ReadLanguageOptions(LangOpts, Complain);
4662}
4663
4664bool ASTReader::ParseTargetOptions(const RecordData &Record,
4665 bool Complain,
4666 ASTReaderListener &Listener) {
4667 unsigned Idx = 0;
4668 TargetOptions TargetOpts;
4669 TargetOpts.Triple = ReadString(Record, Idx);
4670 TargetOpts.CPU = ReadString(Record, Idx);
4671 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 for (unsigned N = Record[Idx++]; N; --N) {
4673 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4674 }
4675 for (unsigned N = Record[Idx++]; N; --N) {
4676 TargetOpts.Features.push_back(ReadString(Record, Idx));
4677 }
4678
4679 return Listener.ReadTargetOptions(TargetOpts, Complain);
4680}
4681
4682bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4683 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004684 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004686#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004687#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004688 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004689#include "clang/Basic/DiagnosticOptions.def"
4690
Richard Smith3be1cb22014-08-07 00:24:21 +00004691 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004692 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004693 for (unsigned N = Record[Idx++]; N; --N)
4694 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004695
4696 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4697}
4698
4699bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4700 ASTReaderListener &Listener) {
4701 FileSystemOptions FSOpts;
4702 unsigned Idx = 0;
4703 FSOpts.WorkingDir = ReadString(Record, Idx);
4704 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4705}
4706
4707bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4708 bool Complain,
4709 ASTReaderListener &Listener) {
4710 HeaderSearchOptions HSOpts;
4711 unsigned Idx = 0;
4712 HSOpts.Sysroot = ReadString(Record, Idx);
4713
4714 // Include entries.
4715 for (unsigned N = Record[Idx++]; N; --N) {
4716 std::string Path = ReadString(Record, Idx);
4717 frontend::IncludeDirGroup Group
4718 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 bool IsFramework = Record[Idx++];
4720 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004722 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 }
4724
4725 // System header prefixes.
4726 for (unsigned N = Record[Idx++]; N; --N) {
4727 std::string Prefix = ReadString(Record, Idx);
4728 bool IsSystemHeader = Record[Idx++];
4729 HSOpts.SystemHeaderPrefixes.push_back(
4730 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4731 }
4732
4733 HSOpts.ResourceDir = ReadString(Record, Idx);
4734 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004735 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 HSOpts.DisableModuleHash = Record[Idx++];
4737 HSOpts.UseBuiltinIncludes = Record[Idx++];
4738 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4739 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4740 HSOpts.UseLibcxx = Record[Idx++];
4741
4742 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4743}
4744
4745bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4746 bool Complain,
4747 ASTReaderListener &Listener,
4748 std::string &SuggestedPredefines) {
4749 PreprocessorOptions PPOpts;
4750 unsigned Idx = 0;
4751
4752 // Macro definitions/undefs
4753 for (unsigned N = Record[Idx++]; N; --N) {
4754 std::string Macro = ReadString(Record, Idx);
4755 bool IsUndef = Record[Idx++];
4756 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4757 }
4758
4759 // Includes
4760 for (unsigned N = Record[Idx++]; N; --N) {
4761 PPOpts.Includes.push_back(ReadString(Record, Idx));
4762 }
4763
4764 // Macro Includes
4765 for (unsigned N = Record[Idx++]; N; --N) {
4766 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4767 }
4768
4769 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004770 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4772 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4773 PPOpts.ObjCXXARCStandardLibrary =
4774 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4775 SuggestedPredefines.clear();
4776 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4777 SuggestedPredefines);
4778}
4779
4780std::pair<ModuleFile *, unsigned>
4781ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4782 GlobalPreprocessedEntityMapType::iterator
4783 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4784 assert(I != GlobalPreprocessedEntityMap.end() &&
4785 "Corrupted global preprocessed entity map");
4786 ModuleFile *M = I->second;
4787 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4788 return std::make_pair(M, LocalIndex);
4789}
4790
4791std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4792ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4793 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4794 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4795 Mod.NumPreprocessedEntities);
4796
4797 return std::make_pair(PreprocessingRecord::iterator(),
4798 PreprocessingRecord::iterator());
4799}
4800
4801std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4802ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4803 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4804 ModuleDeclIterator(this, &Mod,
4805 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4806}
4807
4808PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4809 PreprocessedEntityID PPID = Index+1;
4810 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4811 ModuleFile &M = *PPInfo.first;
4812 unsigned LocalIndex = PPInfo.second;
4813 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4814
Guy Benyei11169dd2012-12-18 14:30:41 +00004815 if (!PP.getPreprocessingRecord()) {
4816 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004817 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 }
4819
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004820 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4821 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4822
4823 llvm::BitstreamEntry Entry =
4824 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4825 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004826 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004827
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 // Read the record.
4829 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4830 ReadSourceLocation(M, PPOffs.End));
4831 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004832 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 RecordData Record;
4834 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004835 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4836 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 switch (RecType) {
4838 case PPD_MACRO_EXPANSION: {
4839 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004840 IdentifierInfo *Name = nullptr;
4841 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 if (isBuiltin)
4843 Name = getLocalIdentifier(M, Record[1]);
4844 else {
4845 PreprocessedEntityID
4846 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4847 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4848 }
4849
4850 MacroExpansion *ME;
4851 if (isBuiltin)
4852 ME = new (PPRec) MacroExpansion(Name, Range);
4853 else
4854 ME = new (PPRec) MacroExpansion(Def, Range);
4855
4856 return ME;
4857 }
4858
4859 case PPD_MACRO_DEFINITION: {
4860 // Decode the identifier info and then check again; if the macro is
4861 // still defined and associated with the identifier,
4862 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4863 MacroDefinition *MD
4864 = new (PPRec) MacroDefinition(II, Range);
4865
4866 if (DeserializationListener)
4867 DeserializationListener->MacroDefinitionRead(PPID, MD);
4868
4869 return MD;
4870 }
4871
4872 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004873 const char *FullFileNameStart = Blob.data() + Record[0];
4874 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004875 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 if (!FullFileName.empty())
4877 File = PP.getFileManager().getFile(FullFileName);
4878
4879 // FIXME: Stable encoding
4880 InclusionDirective::InclusionKind Kind
4881 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4882 InclusionDirective *ID
4883 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004884 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 Record[1], Record[3],
4886 File,
4887 Range);
4888 return ID;
4889 }
4890 }
4891
4892 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4893}
4894
4895/// \brief \arg SLocMapI points at a chunk of a module that contains no
4896/// preprocessed entities or the entities it contains are not the ones we are
4897/// looking for. Find the next module that contains entities and return the ID
4898/// of the first entry.
4899PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4900 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4901 ++SLocMapI;
4902 for (GlobalSLocOffsetMapType::const_iterator
4903 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4904 ModuleFile &M = *SLocMapI->second;
4905 if (M.NumPreprocessedEntities)
4906 return M.BasePreprocessedEntityID;
4907 }
4908
4909 return getTotalNumPreprocessedEntities();
4910}
4911
4912namespace {
4913
4914template <unsigned PPEntityOffset::*PPLoc>
4915struct PPEntityComp {
4916 const ASTReader &Reader;
4917 ModuleFile &M;
4918
4919 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4920
4921 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4922 SourceLocation LHS = getLoc(L);
4923 SourceLocation RHS = getLoc(R);
4924 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4925 }
4926
4927 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4928 SourceLocation LHS = getLoc(L);
4929 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4930 }
4931
4932 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4933 SourceLocation RHS = getLoc(R);
4934 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4935 }
4936
4937 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4938 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4939 }
4940};
4941
4942}
4943
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004944PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4945 bool EndsAfter) const {
4946 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 return getTotalNumPreprocessedEntities();
4948
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004949 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4950 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4952 "Corrupted global sloc offset map");
4953
4954 if (SLocMapI->second->NumPreprocessedEntities == 0)
4955 return findNextPreprocessedEntity(SLocMapI);
4956
4957 ModuleFile &M = *SLocMapI->second;
4958 typedef const PPEntityOffset *pp_iterator;
4959 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4960 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4961
4962 size_t Count = M.NumPreprocessedEntities;
4963 size_t Half;
4964 pp_iterator First = pp_begin;
4965 pp_iterator PPI;
4966
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004967 if (EndsAfter) {
4968 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4969 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4970 } else {
4971 // Do a binary search manually instead of using std::lower_bound because
4972 // The end locations of entities may be unordered (when a macro expansion
4973 // is inside another macro argument), but for this case it is not important
4974 // whether we get the first macro expansion or its containing macro.
4975 while (Count > 0) {
4976 Half = Count / 2;
4977 PPI = First;
4978 std::advance(PPI, Half);
4979 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4980 Loc)) {
4981 First = PPI;
4982 ++First;
4983 Count = Count - Half - 1;
4984 } else
4985 Count = Half;
4986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 }
4988
4989 if (PPI == pp_end)
4990 return findNextPreprocessedEntity(SLocMapI);
4991
4992 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4993}
4994
Guy Benyei11169dd2012-12-18 14:30:41 +00004995/// \brief Returns a pair of [Begin, End) indices of preallocated
4996/// preprocessed entities that \arg Range encompasses.
4997std::pair<unsigned, unsigned>
4998 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4999 if (Range.isInvalid())
5000 return std::make_pair(0,0);
5001 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5002
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005003 PreprocessedEntityID BeginID =
5004 findPreprocessedEntity(Range.getBegin(), false);
5005 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 return std::make_pair(BeginID, EndID);
5007}
5008
5009/// \brief Optionally returns true or false if the preallocated preprocessed
5010/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005011Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 FileID FID) {
5013 if (FID.isInvalid())
5014 return false;
5015
5016 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5017 ModuleFile &M = *PPInfo.first;
5018 unsigned LocalIndex = PPInfo.second;
5019 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5020
5021 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5022 if (Loc.isInvalid())
5023 return false;
5024
5025 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5026 return true;
5027 else
5028 return false;
5029}
5030
5031namespace {
5032 /// \brief Visitor used to search for information about a header file.
5033 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 const FileEntry *FE;
5035
David Blaikie05785d12013-02-20 22:23:23 +00005036 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005037
5038 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005039 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5040 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005041
5042 static bool visit(ModuleFile &M, void *UserData) {
5043 HeaderFileInfoVisitor *This
5044 = static_cast<HeaderFileInfoVisitor *>(UserData);
5045
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 HeaderFileInfoLookupTable *Table
5047 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5048 if (!Table)
5049 return false;
5050
5051 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005052 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005053 if (Pos == Table->end())
5054 return false;
5055
5056 This->HFI = *Pos;
5057 return true;
5058 }
5059
David Blaikie05785d12013-02-20 22:23:23 +00005060 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 };
5062}
5063
5064HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005065 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005067 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005069
5070 return HeaderFileInfo();
5071}
5072
5073void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5074 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005075 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5077 ModuleFile &F = *(*I);
5078 unsigned Idx = 0;
5079 DiagStates.clear();
5080 assert(!Diag.DiagStates.empty());
5081 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5082 while (Idx < F.PragmaDiagMappings.size()) {
5083 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5084 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5085 if (DiagStateID != 0) {
5086 Diag.DiagStatePoints.push_back(
5087 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5088 FullSourceLoc(Loc, SourceMgr)));
5089 continue;
5090 }
5091
5092 assert(DiagStateID == 0);
5093 // A new DiagState was created here.
5094 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5095 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5096 DiagStates.push_back(NewState);
5097 Diag.DiagStatePoints.push_back(
5098 DiagnosticsEngine::DiagStatePoint(NewState,
5099 FullSourceLoc(Loc, SourceMgr)));
5100 while (1) {
5101 assert(Idx < F.PragmaDiagMappings.size() &&
5102 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5103 if (Idx >= F.PragmaDiagMappings.size()) {
5104 break; // Something is messed up but at least avoid infinite loop in
5105 // release build.
5106 }
5107 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5108 if (DiagID == (unsigned)-1) {
5109 break; // no more diag/map pairs for this location.
5110 }
Alp Tokerc726c362014-06-10 09:31:37 +00005111 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5112 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5113 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 }
5115 }
5116 }
5117}
5118
5119/// \brief Get the correct cursor and offset for loading a type.
5120ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5121 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5122 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5123 ModuleFile *M = I->second;
5124 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5125}
5126
5127/// \brief Read and return the type with the given index..
5128///
5129/// The index is the type ID, shifted and minus the number of predefs. This
5130/// routine actually reads the record corresponding to the type at the given
5131/// location. It is a helper routine for GetType, which deals with reading type
5132/// IDs.
5133QualType ASTReader::readTypeRecord(unsigned Index) {
5134 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005135 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005136
5137 // Keep track of where we are in the stream, then jump back there
5138 // after reading this type.
5139 SavedStreamPosition SavedPosition(DeclsCursor);
5140
5141 ReadingKindTracker ReadingKind(Read_Type, *this);
5142
5143 // Note that we are loading a type record.
5144 Deserializing AType(this);
5145
5146 unsigned Idx = 0;
5147 DeclsCursor.JumpToBit(Loc.Offset);
5148 RecordData Record;
5149 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005150 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case TYPE_EXT_QUAL: {
5152 if (Record.size() != 2) {
5153 Error("Incorrect encoding of extended qualifier type");
5154 return QualType();
5155 }
5156 QualType Base = readType(*Loc.F, Record, Idx);
5157 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5158 return Context.getQualifiedType(Base, Quals);
5159 }
5160
5161 case TYPE_COMPLEX: {
5162 if (Record.size() != 1) {
5163 Error("Incorrect encoding of complex type");
5164 return QualType();
5165 }
5166 QualType ElemType = readType(*Loc.F, Record, Idx);
5167 return Context.getComplexType(ElemType);
5168 }
5169
5170 case TYPE_POINTER: {
5171 if (Record.size() != 1) {
5172 Error("Incorrect encoding of pointer type");
5173 return QualType();
5174 }
5175 QualType PointeeType = readType(*Loc.F, Record, Idx);
5176 return Context.getPointerType(PointeeType);
5177 }
5178
Reid Kleckner8a365022013-06-24 17:51:48 +00005179 case TYPE_DECAYED: {
5180 if (Record.size() != 1) {
5181 Error("Incorrect encoding of decayed type");
5182 return QualType();
5183 }
5184 QualType OriginalType = readType(*Loc.F, Record, Idx);
5185 QualType DT = Context.getAdjustedParameterType(OriginalType);
5186 if (!isa<DecayedType>(DT))
5187 Error("Decayed type does not decay");
5188 return DT;
5189 }
5190
Reid Kleckner0503a872013-12-05 01:23:43 +00005191 case TYPE_ADJUSTED: {
5192 if (Record.size() != 2) {
5193 Error("Incorrect encoding of adjusted type");
5194 return QualType();
5195 }
5196 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5197 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5198 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5199 }
5200
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 case TYPE_BLOCK_POINTER: {
5202 if (Record.size() != 1) {
5203 Error("Incorrect encoding of block pointer type");
5204 return QualType();
5205 }
5206 QualType PointeeType = readType(*Loc.F, Record, Idx);
5207 return Context.getBlockPointerType(PointeeType);
5208 }
5209
5210 case TYPE_LVALUE_REFERENCE: {
5211 if (Record.size() != 2) {
5212 Error("Incorrect encoding of lvalue reference type");
5213 return QualType();
5214 }
5215 QualType PointeeType = readType(*Loc.F, Record, Idx);
5216 return Context.getLValueReferenceType(PointeeType, Record[1]);
5217 }
5218
5219 case TYPE_RVALUE_REFERENCE: {
5220 if (Record.size() != 1) {
5221 Error("Incorrect encoding of rvalue reference type");
5222 return QualType();
5223 }
5224 QualType PointeeType = readType(*Loc.F, Record, Idx);
5225 return Context.getRValueReferenceType(PointeeType);
5226 }
5227
5228 case TYPE_MEMBER_POINTER: {
5229 if (Record.size() != 2) {
5230 Error("Incorrect encoding of member pointer type");
5231 return QualType();
5232 }
5233 QualType PointeeType = readType(*Loc.F, Record, Idx);
5234 QualType ClassType = readType(*Loc.F, Record, Idx);
5235 if (PointeeType.isNull() || ClassType.isNull())
5236 return QualType();
5237
5238 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5239 }
5240
5241 case TYPE_CONSTANT_ARRAY: {
5242 QualType ElementType = readType(*Loc.F, Record, Idx);
5243 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5244 unsigned IndexTypeQuals = Record[2];
5245 unsigned Idx = 3;
5246 llvm::APInt Size = ReadAPInt(Record, Idx);
5247 return Context.getConstantArrayType(ElementType, Size,
5248 ASM, IndexTypeQuals);
5249 }
5250
5251 case TYPE_INCOMPLETE_ARRAY: {
5252 QualType ElementType = readType(*Loc.F, Record, Idx);
5253 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5254 unsigned IndexTypeQuals = Record[2];
5255 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5256 }
5257
5258 case TYPE_VARIABLE_ARRAY: {
5259 QualType ElementType = readType(*Loc.F, Record, Idx);
5260 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5261 unsigned IndexTypeQuals = Record[2];
5262 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5263 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5264 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5265 ASM, IndexTypeQuals,
5266 SourceRange(LBLoc, RBLoc));
5267 }
5268
5269 case TYPE_VECTOR: {
5270 if (Record.size() != 3) {
5271 Error("incorrect encoding of vector type in AST file");
5272 return QualType();
5273 }
5274
5275 QualType ElementType = readType(*Loc.F, Record, Idx);
5276 unsigned NumElements = Record[1];
5277 unsigned VecKind = Record[2];
5278 return Context.getVectorType(ElementType, NumElements,
5279 (VectorType::VectorKind)VecKind);
5280 }
5281
5282 case TYPE_EXT_VECTOR: {
5283 if (Record.size() != 3) {
5284 Error("incorrect encoding of extended vector type in AST file");
5285 return QualType();
5286 }
5287
5288 QualType ElementType = readType(*Loc.F, Record, Idx);
5289 unsigned NumElements = Record[1];
5290 return Context.getExtVectorType(ElementType, NumElements);
5291 }
5292
5293 case TYPE_FUNCTION_NO_PROTO: {
5294 if (Record.size() != 6) {
5295 Error("incorrect encoding of no-proto function type");
5296 return QualType();
5297 }
5298 QualType ResultType = readType(*Loc.F, Record, Idx);
5299 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5300 (CallingConv)Record[4], Record[5]);
5301 return Context.getFunctionNoProtoType(ResultType, Info);
5302 }
5303
5304 case TYPE_FUNCTION_PROTO: {
5305 QualType ResultType = readType(*Loc.F, Record, Idx);
5306
5307 FunctionProtoType::ExtProtoInfo EPI;
5308 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5309 /*hasregparm*/ Record[2],
5310 /*regparm*/ Record[3],
5311 static_cast<CallingConv>(Record[4]),
5312 /*produces*/ Record[5]);
5313
5314 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005315
5316 EPI.Variadic = Record[Idx++];
5317 EPI.HasTrailingReturn = Record[Idx++];
5318 EPI.TypeQuals = Record[Idx++];
5319 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005320 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005321 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005322
5323 unsigned NumParams = Record[Idx++];
5324 SmallVector<QualType, 16> ParamTypes;
5325 for (unsigned I = 0; I != NumParams; ++I)
5326 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5327
Jordan Rose5c382722013-03-08 21:51:21 +00005328 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 }
5330
5331 case TYPE_UNRESOLVED_USING: {
5332 unsigned Idx = 0;
5333 return Context.getTypeDeclType(
5334 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5335 }
5336
5337 case TYPE_TYPEDEF: {
5338 if (Record.size() != 2) {
5339 Error("incorrect encoding of typedef type");
5340 return QualType();
5341 }
5342 unsigned Idx = 0;
5343 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5344 QualType Canonical = readType(*Loc.F, Record, Idx);
5345 if (!Canonical.isNull())
5346 Canonical = Context.getCanonicalType(Canonical);
5347 return Context.getTypedefType(Decl, Canonical);
5348 }
5349
5350 case TYPE_TYPEOF_EXPR:
5351 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5352
5353 case TYPE_TYPEOF: {
5354 if (Record.size() != 1) {
5355 Error("incorrect encoding of typeof(type) in AST file");
5356 return QualType();
5357 }
5358 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5359 return Context.getTypeOfType(UnderlyingType);
5360 }
5361
5362 case TYPE_DECLTYPE: {
5363 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5364 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5365 }
5366
5367 case TYPE_UNARY_TRANSFORM: {
5368 QualType BaseType = readType(*Loc.F, Record, Idx);
5369 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5370 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5371 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5372 }
5373
Richard Smith74aeef52013-04-26 16:15:35 +00005374 case TYPE_AUTO: {
5375 QualType Deduced = readType(*Loc.F, Record, Idx);
5376 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005377 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005378 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005379 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005380
5381 case TYPE_RECORD: {
5382 if (Record.size() != 2) {
5383 Error("incorrect encoding of record type");
5384 return QualType();
5385 }
5386 unsigned Idx = 0;
5387 bool IsDependent = Record[Idx++];
5388 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5389 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5390 QualType T = Context.getRecordType(RD);
5391 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5392 return T;
5393 }
5394
5395 case TYPE_ENUM: {
5396 if (Record.size() != 2) {
5397 Error("incorrect encoding of enum type");
5398 return QualType();
5399 }
5400 unsigned Idx = 0;
5401 bool IsDependent = Record[Idx++];
5402 QualType T
5403 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5404 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5405 return T;
5406 }
5407
5408 case TYPE_ATTRIBUTED: {
5409 if (Record.size() != 3) {
5410 Error("incorrect encoding of attributed type");
5411 return QualType();
5412 }
5413 QualType modifiedType = readType(*Loc.F, Record, Idx);
5414 QualType equivalentType = readType(*Loc.F, Record, Idx);
5415 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5416 return Context.getAttributedType(kind, modifiedType, equivalentType);
5417 }
5418
5419 case TYPE_PAREN: {
5420 if (Record.size() != 1) {
5421 Error("incorrect encoding of paren type");
5422 return QualType();
5423 }
5424 QualType InnerType = readType(*Loc.F, Record, Idx);
5425 return Context.getParenType(InnerType);
5426 }
5427
5428 case TYPE_PACK_EXPANSION: {
5429 if (Record.size() != 2) {
5430 Error("incorrect encoding of pack expansion type");
5431 return QualType();
5432 }
5433 QualType Pattern = readType(*Loc.F, Record, Idx);
5434 if (Pattern.isNull())
5435 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005436 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005437 if (Record[1])
5438 NumExpansions = Record[1] - 1;
5439 return Context.getPackExpansionType(Pattern, NumExpansions);
5440 }
5441
5442 case TYPE_ELABORATED: {
5443 unsigned Idx = 0;
5444 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5445 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5446 QualType NamedType = readType(*Loc.F, Record, Idx);
5447 return Context.getElaboratedType(Keyword, NNS, NamedType);
5448 }
5449
5450 case TYPE_OBJC_INTERFACE: {
5451 unsigned Idx = 0;
5452 ObjCInterfaceDecl *ItfD
5453 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5454 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5455 }
5456
5457 case TYPE_OBJC_OBJECT: {
5458 unsigned Idx = 0;
5459 QualType Base = readType(*Loc.F, Record, Idx);
5460 unsigned NumProtos = Record[Idx++];
5461 SmallVector<ObjCProtocolDecl*, 4> Protos;
5462 for (unsigned I = 0; I != NumProtos; ++I)
5463 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5464 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5465 }
5466
5467 case TYPE_OBJC_OBJECT_POINTER: {
5468 unsigned Idx = 0;
5469 QualType Pointee = readType(*Loc.F, Record, Idx);
5470 return Context.getObjCObjectPointerType(Pointee);
5471 }
5472
5473 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5474 unsigned Idx = 0;
5475 QualType Parm = readType(*Loc.F, Record, Idx);
5476 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005477 return Context.getSubstTemplateTypeParmType(
5478 cast<TemplateTypeParmType>(Parm),
5479 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005480 }
5481
5482 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5483 unsigned Idx = 0;
5484 QualType Parm = readType(*Loc.F, Record, Idx);
5485 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5486 return Context.getSubstTemplateTypeParmPackType(
5487 cast<TemplateTypeParmType>(Parm),
5488 ArgPack);
5489 }
5490
5491 case TYPE_INJECTED_CLASS_NAME: {
5492 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5493 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5494 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5495 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005496 const Type *T;
5497 if (const Type *Existing = D->getTypeForDecl())
5498 T = Existing;
5499 else if (auto *Prev = D->getPreviousDecl())
5500 T = Prev->getTypeForDecl();
5501 else
5502 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5503 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 }
5505
5506 case TYPE_TEMPLATE_TYPE_PARM: {
5507 unsigned Idx = 0;
5508 unsigned Depth = Record[Idx++];
5509 unsigned Index = Record[Idx++];
5510 bool Pack = Record[Idx++];
5511 TemplateTypeParmDecl *D
5512 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5513 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5514 }
5515
5516 case TYPE_DEPENDENT_NAME: {
5517 unsigned Idx = 0;
5518 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5519 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5520 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5521 QualType Canon = readType(*Loc.F, Record, Idx);
5522 if (!Canon.isNull())
5523 Canon = Context.getCanonicalType(Canon);
5524 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5525 }
5526
5527 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5528 unsigned Idx = 0;
5529 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5530 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5531 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5532 unsigned NumArgs = Record[Idx++];
5533 SmallVector<TemplateArgument, 8> Args;
5534 Args.reserve(NumArgs);
5535 while (NumArgs--)
5536 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5537 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5538 Args.size(), Args.data());
5539 }
5540
5541 case TYPE_DEPENDENT_SIZED_ARRAY: {
5542 unsigned Idx = 0;
5543
5544 // ArrayType
5545 QualType ElementType = readType(*Loc.F, Record, Idx);
5546 ArrayType::ArraySizeModifier ASM
5547 = (ArrayType::ArraySizeModifier)Record[Idx++];
5548 unsigned IndexTypeQuals = Record[Idx++];
5549
5550 // DependentSizedArrayType
5551 Expr *NumElts = ReadExpr(*Loc.F);
5552 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5553
5554 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5555 IndexTypeQuals, Brackets);
5556 }
5557
5558 case TYPE_TEMPLATE_SPECIALIZATION: {
5559 unsigned Idx = 0;
5560 bool IsDependent = Record[Idx++];
5561 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5562 SmallVector<TemplateArgument, 8> Args;
5563 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5564 QualType Underlying = readType(*Loc.F, Record, Idx);
5565 QualType T;
5566 if (Underlying.isNull())
5567 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5568 Args.size());
5569 else
5570 T = Context.getTemplateSpecializationType(Name, Args.data(),
5571 Args.size(), Underlying);
5572 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5573 return T;
5574 }
5575
5576 case TYPE_ATOMIC: {
5577 if (Record.size() != 1) {
5578 Error("Incorrect encoding of atomic type");
5579 return QualType();
5580 }
5581 QualType ValueType = readType(*Loc.F, Record, Idx);
5582 return Context.getAtomicType(ValueType);
5583 }
5584 }
5585 llvm_unreachable("Invalid TypeCode!");
5586}
5587
Richard Smith564417a2014-03-20 21:47:22 +00005588void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5589 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005590 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005591 const RecordData &Record, unsigned &Idx) {
5592 ExceptionSpecificationType EST =
5593 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005594 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005595 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005596 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005597 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005598 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005599 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005600 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005601 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005602 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5603 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005604 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005605 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005606 }
5607}
5608
Guy Benyei11169dd2012-12-18 14:30:41 +00005609class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5610 ASTReader &Reader;
5611 ModuleFile &F;
5612 const ASTReader::RecordData &Record;
5613 unsigned &Idx;
5614
5615 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5616 unsigned &I) {
5617 return Reader.ReadSourceLocation(F, R, I);
5618 }
5619
5620 template<typename T>
5621 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5622 return Reader.ReadDeclAs<T>(F, Record, Idx);
5623 }
5624
5625public:
5626 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5627 const ASTReader::RecordData &Record, unsigned &Idx)
5628 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5629 { }
5630
5631 // We want compile-time assurance that we've enumerated all of
5632 // these, so unfortunately we have to declare them first, then
5633 // define them out-of-line.
5634#define ABSTRACT_TYPELOC(CLASS, PARENT)
5635#define TYPELOC(CLASS, PARENT) \
5636 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5637#include "clang/AST/TypeLocNodes.def"
5638
5639 void VisitFunctionTypeLoc(FunctionTypeLoc);
5640 void VisitArrayTypeLoc(ArrayTypeLoc);
5641};
5642
5643void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5644 // nothing to do
5645}
5646void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5647 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5648 if (TL.needsExtraLocalData()) {
5649 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5650 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5651 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5652 TL.setModeAttr(Record[Idx++]);
5653 }
5654}
5655void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5656 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5657}
5658void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5659 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5660}
Reid Kleckner8a365022013-06-24 17:51:48 +00005661void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5662 // nothing to do
5663}
Reid Kleckner0503a872013-12-05 01:23:43 +00005664void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5665 // nothing to do
5666}
Guy Benyei11169dd2012-12-18 14:30:41 +00005667void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5668 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5669}
5670void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5671 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5672}
5673void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5674 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5677 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5678 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5679}
5680void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5681 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5682 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5683 if (Record[Idx++])
5684 TL.setSizeExpr(Reader.ReadExpr(F));
5685 else
Craig Toppera13603a2014-05-22 05:54:18 +00005686 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005687}
5688void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5689 VisitArrayTypeLoc(TL);
5690}
5691void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5692 VisitArrayTypeLoc(TL);
5693}
5694void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5695 VisitArrayTypeLoc(TL);
5696}
5697void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5698 DependentSizedArrayTypeLoc TL) {
5699 VisitArrayTypeLoc(TL);
5700}
5701void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5702 DependentSizedExtVectorTypeLoc TL) {
5703 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5704}
5705void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5706 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5707}
5708void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5709 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5710}
5711void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5712 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5713 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5714 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5715 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005716 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5717 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005718 }
5719}
5720void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5721 VisitFunctionTypeLoc(TL);
5722}
5723void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5724 VisitFunctionTypeLoc(TL);
5725}
5726void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5727 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5730 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5731}
5732void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5733 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5734 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5735 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5736}
5737void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5738 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5739 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5740 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5741 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5742}
5743void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5744 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5745}
5746void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5747 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5748 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5749 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5750 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5751}
5752void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5756 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5759 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5760}
5761void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5762 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5763 if (TL.hasAttrOperand()) {
5764 SourceRange range;
5765 range.setBegin(ReadSourceLocation(Record, Idx));
5766 range.setEnd(ReadSourceLocation(Record, Idx));
5767 TL.setAttrOperandParensRange(range);
5768 }
5769 if (TL.hasAttrExprOperand()) {
5770 if (Record[Idx++])
5771 TL.setAttrExprOperand(Reader.ReadExpr(F));
5772 else
Craig Toppera13603a2014-05-22 05:54:18 +00005773 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 } else if (TL.hasAttrEnumOperand())
5775 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5776}
5777void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5778 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5781 SubstTemplateTypeParmTypeLoc TL) {
5782 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5783}
5784void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5785 SubstTemplateTypeParmPackTypeLoc TL) {
5786 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5787}
5788void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5789 TemplateSpecializationTypeLoc TL) {
5790 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5791 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5792 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5793 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5794 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5795 TL.setArgLocInfo(i,
5796 Reader.GetTemplateArgumentLocInfo(F,
5797 TL.getTypePtr()->getArg(i).getKind(),
5798 Record, Idx));
5799}
5800void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5801 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5802 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5803}
5804void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5805 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5806 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5807}
5808void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810}
5811void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5812 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5813 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5814 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5815}
5816void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5817 DependentTemplateSpecializationTypeLoc TL) {
5818 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5819 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5820 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5821 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5822 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5823 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5824 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5825 TL.setArgLocInfo(I,
5826 Reader.GetTemplateArgumentLocInfo(F,
5827 TL.getTypePtr()->getArg(I).getKind(),
5828 Record, Idx));
5829}
5830void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5831 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5832}
5833void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5835}
5836void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5837 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5838 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5839 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5840 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5841 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5842}
5843void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5844 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5845}
5846void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5847 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5848 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5849 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5850}
5851
5852TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5853 const RecordData &Record,
5854 unsigned &Idx) {
5855 QualType InfoTy = readType(F, Record, Idx);
5856 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005857 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005858
5859 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5860 TypeLocReader TLR(*this, F, Record, Idx);
5861 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5862 TLR.Visit(TL);
5863 return TInfo;
5864}
5865
5866QualType ASTReader::GetType(TypeID ID) {
5867 unsigned FastQuals = ID & Qualifiers::FastMask;
5868 unsigned Index = ID >> Qualifiers::FastWidth;
5869
5870 if (Index < NUM_PREDEF_TYPE_IDS) {
5871 QualType T;
5872 switch ((PredefinedTypeIDs)Index) {
5873 case PREDEF_TYPE_NULL_ID: return QualType();
5874 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5875 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5876
5877 case PREDEF_TYPE_CHAR_U_ID:
5878 case PREDEF_TYPE_CHAR_S_ID:
5879 // FIXME: Check that the signedness of CharTy is correct!
5880 T = Context.CharTy;
5881 break;
5882
5883 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5884 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5885 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5886 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5887 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5888 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5889 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5890 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5891 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5892 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5893 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5894 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5895 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5896 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5897 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5898 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5899 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5900 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5901 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5902 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5903 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5904 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5905 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5906 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5907 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5908 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5909 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5910 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005911 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5912 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5913 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5914 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5915 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5916 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005917 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005918 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005919 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5920
5921 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5922 T = Context.getAutoRRefDeductType();
5923 break;
5924
5925 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5926 T = Context.ARCUnbridgedCastTy;
5927 break;
5928
5929 case PREDEF_TYPE_VA_LIST_TAG:
5930 T = Context.getVaListTagType();
5931 break;
5932
5933 case PREDEF_TYPE_BUILTIN_FN:
5934 T = Context.BuiltinFnTy;
5935 break;
5936 }
5937
5938 assert(!T.isNull() && "Unknown predefined type");
5939 return T.withFastQualifiers(FastQuals);
5940 }
5941
5942 Index -= NUM_PREDEF_TYPE_IDS;
5943 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5944 if (TypesLoaded[Index].isNull()) {
5945 TypesLoaded[Index] = readTypeRecord(Index);
5946 if (TypesLoaded[Index].isNull())
5947 return QualType();
5948
5949 TypesLoaded[Index]->setFromAST();
5950 if (DeserializationListener)
5951 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5952 TypesLoaded[Index]);
5953 }
5954
5955 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5956}
5957
5958QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5959 return GetType(getGlobalTypeID(F, LocalID));
5960}
5961
5962serialization::TypeID
5963ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5964 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5965 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5966
5967 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5968 return LocalID;
5969
5970 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5971 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5972 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5973
5974 unsigned GlobalIndex = LocalIndex + I->second;
5975 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5976}
5977
5978TemplateArgumentLocInfo
5979ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5980 TemplateArgument::ArgKind Kind,
5981 const RecordData &Record,
5982 unsigned &Index) {
5983 switch (Kind) {
5984 case TemplateArgument::Expression:
5985 return ReadExpr(F);
5986 case TemplateArgument::Type:
5987 return GetTypeSourceInfo(F, Record, Index);
5988 case TemplateArgument::Template: {
5989 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5990 Index);
5991 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5992 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5993 SourceLocation());
5994 }
5995 case TemplateArgument::TemplateExpansion: {
5996 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5997 Index);
5998 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5999 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6000 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6001 EllipsisLoc);
6002 }
6003 case TemplateArgument::Null:
6004 case TemplateArgument::Integral:
6005 case TemplateArgument::Declaration:
6006 case TemplateArgument::NullPtr:
6007 case TemplateArgument::Pack:
6008 // FIXME: Is this right?
6009 return TemplateArgumentLocInfo();
6010 }
6011 llvm_unreachable("unexpected template argument loc");
6012}
6013
6014TemplateArgumentLoc
6015ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6016 const RecordData &Record, unsigned &Index) {
6017 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6018
6019 if (Arg.getKind() == TemplateArgument::Expression) {
6020 if (Record[Index++]) // bool InfoHasSameExpr.
6021 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6022 }
6023 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6024 Record, Index));
6025}
6026
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006027const ASTTemplateArgumentListInfo*
6028ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6029 const RecordData &Record,
6030 unsigned &Index) {
6031 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6032 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6033 unsigned NumArgsAsWritten = Record[Index++];
6034 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6035 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6036 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6037 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6038}
6039
Guy Benyei11169dd2012-12-18 14:30:41 +00006040Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6041 return GetDecl(ID);
6042}
6043
Richard Smith053f6c62014-05-16 23:01:30 +00006044void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006045 if (NumCurrentElementsDeserializing) {
6046 // We arrange to not care about the complete redeclaration chain while we're
6047 // deserializing. Just remember that the AST has marked this one as complete
6048 // but that it's not actually complete yet, so we know we still need to
6049 // complete it later.
6050 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6051 return;
6052 }
6053
Richard Smith053f6c62014-05-16 23:01:30 +00006054 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6055
Richard Smith053f6c62014-05-16 23:01:30 +00006056 // If this is a named declaration, complete it by looking it up
6057 // within its context.
6058 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006059 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006060 // all mergeable entities within it.
6061 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6062 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6063 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6064 auto *II = Name.getAsIdentifierInfo();
6065 if (isa<TranslationUnitDecl>(DC) && II) {
6066 // Outside of C++, we don't have a lookup table for the TU, so update
6067 // the identifier instead. In C++, either way should work fine.
6068 if (II->isOutOfDate())
6069 updateOutOfDateIdentifier(*II);
6070 } else
6071 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006072 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6073 // FIXME: It'd be nice to do something a bit more targeted here.
6074 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006075 }
6076 }
6077}
6078
Richard Smithcd45dbc2014-04-19 03:48:30 +00006079uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6080 const RecordData &Record,
6081 unsigned &Idx) {
6082 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6083 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006085 }
6086
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 unsigned LocalID = Record[Idx++];
6088 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6089}
6090
6091CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6092 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006093 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006094 SavedStreamPosition SavedPosition(Cursor);
6095 Cursor.JumpToBit(Loc.Offset);
6096 ReadingKindTracker ReadingKind(Read_Decl, *this);
6097 RecordData Record;
6098 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006099 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006101 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006102 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006103 }
6104
6105 unsigned Idx = 0;
6106 unsigned NumBases = Record[Idx++];
6107 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6108 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6109 for (unsigned I = 0; I != NumBases; ++I)
6110 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6111 return Bases;
6112}
6113
6114serialization::DeclID
6115ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6116 if (LocalID < NUM_PREDEF_DECL_IDS)
6117 return LocalID;
6118
6119 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6120 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6121 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6122
6123 return LocalID + I->second;
6124}
6125
6126bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6127 ModuleFile &M) const {
6128 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6129 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6130 return &M == I->second;
6131}
6132
Douglas Gregor9f782892013-01-21 15:25:38 +00006133ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006135 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6137 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6138 return I->second;
6139}
6140
6141SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6142 if (ID < NUM_PREDEF_DECL_IDS)
6143 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006144
Guy Benyei11169dd2012-12-18 14:30:41 +00006145 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6146
6147 if (Index > DeclsLoaded.size()) {
6148 Error("declaration ID out-of-range for AST file");
6149 return SourceLocation();
6150 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006151
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 if (Decl *D = DeclsLoaded[Index])
6153 return D->getLocation();
6154
6155 unsigned RawLocation = 0;
6156 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6157 return ReadSourceLocation(*Rec.F, RawLocation);
6158}
6159
Richard Smithcd45dbc2014-04-19 03:48:30 +00006160Decl *ASTReader::GetExistingDecl(DeclID ID) {
6161 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006162 switch ((PredefinedDeclIDs)ID) {
6163 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006164 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006165
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6167 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006168
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 case PREDEF_DECL_OBJC_ID_ID:
6170 return Context.getObjCIdDecl();
6171
6172 case PREDEF_DECL_OBJC_SEL_ID:
6173 return Context.getObjCSelDecl();
6174
6175 case PREDEF_DECL_OBJC_CLASS_ID:
6176 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006177
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6179 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006180
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 case PREDEF_DECL_INT_128_ID:
6182 return Context.getInt128Decl();
6183
6184 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6185 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006186
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6188 return Context.getObjCInstanceTypeDecl();
6189
6190 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6191 return Context.getBuiltinVaListDecl();
6192 }
6193 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006194
Guy Benyei11169dd2012-12-18 14:30:41 +00006195 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6196
6197 if (Index >= DeclsLoaded.size()) {
6198 assert(0 && "declaration ID out-of-range for AST file");
6199 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006200 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006201 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006202
6203 return DeclsLoaded[Index];
6204}
6205
6206Decl *ASTReader::GetDecl(DeclID ID) {
6207 if (ID < NUM_PREDEF_DECL_IDS)
6208 return GetExistingDecl(ID);
6209
6210 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6211
6212 if (Index >= DeclsLoaded.size()) {
6213 assert(0 && "declaration ID out-of-range for AST file");
6214 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006215 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006216 }
6217
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 if (!DeclsLoaded[Index]) {
6219 ReadDeclRecord(ID);
6220 if (DeserializationListener)
6221 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6222 }
6223
6224 return DeclsLoaded[Index];
6225}
6226
6227DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6228 DeclID GlobalID) {
6229 if (GlobalID < NUM_PREDEF_DECL_IDS)
6230 return GlobalID;
6231
6232 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6233 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6234 ModuleFile *Owner = I->second;
6235
6236 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6237 = M.GlobalToLocalDeclIDs.find(Owner);
6238 if (Pos == M.GlobalToLocalDeclIDs.end())
6239 return 0;
6240
6241 return GlobalID - Owner->BaseDeclID + Pos->second;
6242}
6243
6244serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6245 const RecordData &Record,
6246 unsigned &Idx) {
6247 if (Idx >= Record.size()) {
6248 Error("Corrupted AST file");
6249 return 0;
6250 }
6251
6252 return getGlobalDeclID(F, Record[Idx++]);
6253}
6254
6255/// \brief Resolve the offset of a statement into a statement.
6256///
6257/// This operation will read a new statement from the external
6258/// source each time it is called, and is meant to be used via a
6259/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6260Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6261 // Switch case IDs are per Decl.
6262 ClearSwitchCaseIDs();
6263
6264 // Offset here is a global offset across the entire chain.
6265 RecordLocation Loc = getLocalBitOffset(Offset);
6266 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6267 return ReadStmtFromStream(*Loc.F);
6268}
6269
6270namespace {
6271 class FindExternalLexicalDeclsVisitor {
6272 ASTReader &Reader;
6273 const DeclContext *DC;
6274 bool (*isKindWeWant)(Decl::Kind);
6275
6276 SmallVectorImpl<Decl*> &Decls;
6277 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6278
6279 public:
6280 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6281 bool (*isKindWeWant)(Decl::Kind),
6282 SmallVectorImpl<Decl*> &Decls)
6283 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6284 {
6285 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6286 PredefsVisited[I] = false;
6287 }
6288
6289 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6290 if (Preorder)
6291 return false;
6292
6293 FindExternalLexicalDeclsVisitor *This
6294 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6295
6296 ModuleFile::DeclContextInfosMap::iterator Info
6297 = M.DeclContextInfos.find(This->DC);
6298 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6299 return false;
6300
6301 // Load all of the declaration IDs
6302 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6303 *IDE = ID + Info->second.NumLexicalDecls;
6304 ID != IDE; ++ID) {
6305 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6306 continue;
6307
6308 // Don't add predefined declarations to the lexical context more
6309 // than once.
6310 if (ID->second < NUM_PREDEF_DECL_IDS) {
6311 if (This->PredefsVisited[ID->second])
6312 continue;
6313
6314 This->PredefsVisited[ID->second] = true;
6315 }
6316
6317 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6318 if (!This->DC->isDeclInLexicalTraversal(D))
6319 This->Decls.push_back(D);
6320 }
6321 }
6322
6323 return false;
6324 }
6325 };
6326}
6327
6328ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6329 bool (*isKindWeWant)(Decl::Kind),
6330 SmallVectorImpl<Decl*> &Decls) {
6331 // There might be lexical decls in multiple modules, for the TU at
6332 // least. Walk all of the modules in the order they were loaded.
6333 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6334 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6335 ++NumLexicalDeclContextsRead;
6336 return ELR_Success;
6337}
6338
6339namespace {
6340
6341class DeclIDComp {
6342 ASTReader &Reader;
6343 ModuleFile &Mod;
6344
6345public:
6346 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6347
6348 bool operator()(LocalDeclID L, LocalDeclID R) const {
6349 SourceLocation LHS = getLocation(L);
6350 SourceLocation RHS = getLocation(R);
6351 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6352 }
6353
6354 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6355 SourceLocation RHS = getLocation(R);
6356 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6357 }
6358
6359 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6360 SourceLocation LHS = getLocation(L);
6361 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6362 }
6363
6364 SourceLocation getLocation(LocalDeclID ID) const {
6365 return Reader.getSourceManager().getFileLoc(
6366 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6367 }
6368};
6369
6370}
6371
6372void ASTReader::FindFileRegionDecls(FileID File,
6373 unsigned Offset, unsigned Length,
6374 SmallVectorImpl<Decl *> &Decls) {
6375 SourceManager &SM = getSourceManager();
6376
6377 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6378 if (I == FileDeclIDs.end())
6379 return;
6380
6381 FileDeclsInfo &DInfo = I->second;
6382 if (DInfo.Decls.empty())
6383 return;
6384
6385 SourceLocation
6386 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6387 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6388
6389 DeclIDComp DIDComp(*this, *DInfo.Mod);
6390 ArrayRef<serialization::LocalDeclID>::iterator
6391 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6392 BeginLoc, DIDComp);
6393 if (BeginIt != DInfo.Decls.begin())
6394 --BeginIt;
6395
6396 // If we are pointing at a top-level decl inside an objc container, we need
6397 // to backtrack until we find it otherwise we will fail to report that the
6398 // region overlaps with an objc container.
6399 while (BeginIt != DInfo.Decls.begin() &&
6400 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6401 ->isTopLevelDeclInObjCContainer())
6402 --BeginIt;
6403
6404 ArrayRef<serialization::LocalDeclID>::iterator
6405 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6406 EndLoc, DIDComp);
6407 if (EndIt != DInfo.Decls.end())
6408 ++EndIt;
6409
6410 for (ArrayRef<serialization::LocalDeclID>::iterator
6411 DIt = BeginIt; DIt != EndIt; ++DIt)
6412 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6413}
6414
6415namespace {
6416 /// \brief ModuleFile visitor used to perform name lookup into a
6417 /// declaration context.
6418 class DeclContextNameLookupVisitor {
6419 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006420 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 DeclarationName Name;
6422 SmallVectorImpl<NamedDecl *> &Decls;
6423
6424 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006425 DeclContextNameLookupVisitor(ASTReader &Reader,
6426 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 DeclarationName Name,
6428 SmallVectorImpl<NamedDecl *> &Decls)
6429 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6430
6431 static bool visit(ModuleFile &M, void *UserData) {
6432 DeclContextNameLookupVisitor *This
6433 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6434
6435 // Check whether we have any visible declaration information for
6436 // this context in this module.
6437 ModuleFile::DeclContextInfosMap::iterator Info;
6438 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006439 for (auto *DC : This->Contexts) {
6440 Info = M.DeclContextInfos.find(DC);
6441 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 Info->second.NameLookupTableData) {
6443 FoundInfo = true;
6444 break;
6445 }
6446 }
6447
6448 if (!FoundInfo)
6449 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006450
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006452 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006453 Info->second.NameLookupTableData;
6454 ASTDeclContextNameLookupTable::iterator Pos
6455 = LookupTable->find(This->Name);
6456 if (Pos == LookupTable->end())
6457 return false;
6458
6459 bool FoundAnything = false;
6460 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6461 for (; Data.first != Data.second; ++Data.first) {
6462 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6463 if (!ND)
6464 continue;
6465
6466 if (ND->getDeclName() != This->Name) {
6467 // A name might be null because the decl's redeclarable part is
6468 // currently read before reading its name. The lookup is triggered by
6469 // building that decl (likely indirectly), and so it is later in the
6470 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006471 // FIXME: This should not happen; deserializing declarations should
6472 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006473 continue;
6474 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006475
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 // Record this declaration.
6477 FoundAnything = true;
6478 This->Decls.push_back(ND);
6479 }
6480
6481 return FoundAnything;
6482 }
6483 };
6484}
6485
Douglas Gregor9f782892013-01-21 15:25:38 +00006486/// \brief Retrieve the "definitive" module file for the definition of the
6487/// given declaration context, if there is one.
6488///
6489/// The "definitive" module file is the only place where we need to look to
6490/// find information about the declarations within the given declaration
6491/// context. For example, C++ and Objective-C classes, C structs/unions, and
6492/// Objective-C protocols, categories, and extensions are all defined in a
6493/// single place in the source code, so they have definitive module files
6494/// associated with them. C++ namespaces, on the other hand, can have
6495/// definitions in multiple different module files.
6496///
6497/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6498/// NDEBUG checking.
6499static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6500 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006501 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6502 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006503
Craig Toppera13603a2014-05-22 05:54:18 +00006504 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006505}
6506
Richard Smith9ce12e32013-02-07 03:30:24 +00006507bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006508ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6509 DeclarationName Name) {
6510 assert(DC->hasExternalVisibleStorage() &&
6511 "DeclContext has no visible decls in storage");
6512 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006513 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006514
Richard Smith8c913ec2014-08-14 02:21:01 +00006515 Deserializing LookupResults(this);
6516
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 SmallVector<NamedDecl *, 64> Decls;
Richard Smith8c913ec2014-08-14 02:21:01 +00006518
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 // Compute the declaration contexts we need to look into. Multiple such
6520 // declaration contexts occur when two declaration contexts from disjoint
6521 // modules get merged, e.g., when two namespaces with the same name are
6522 // independently defined in separate modules.
6523 SmallVector<const DeclContext *, 2> Contexts;
6524 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006525
Guy Benyei11169dd2012-12-18 14:30:41 +00006526 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006527 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 if (Merged != MergedDecls.end()) {
6529 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6530 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6531 }
6532 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006533
6534 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6535 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6536
6537 // If we can definitively determine which module file to look into,
6538 // only look there. Otherwise, look in all module files.
6539 ModuleFile *Definitive;
6540 if (Contexts.size() == 1 &&
6541 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6542 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6543 } else {
6544 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6545 }
6546 };
6547
6548 LookUpInContexts(Contexts);
6549
6550 // If this might be an implicit special member function, then also search
6551 // all merged definitions of the surrounding class. We need to search them
6552 // individually, because finding an entity in one of them doesn't imply that
6553 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006554 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006555 auto Kind = Name.getNameKind();
6556 if (Kind == DeclarationName::CXXConstructorName ||
6557 Kind == DeclarationName::CXXDestructorName ||
6558 (Kind == DeclarationName::CXXOperatorName &&
6559 Name.getCXXOverloadedOperator() == OO_Equal)) {
6560 auto Merged = MergedLookups.find(DC);
6561 if (Merged != MergedLookups.end())
6562 for (auto *MergedDC : Merged->second)
6563 LookUpInContexts(MergedDC);
6564 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006565 }
6566
Guy Benyei11169dd2012-12-18 14:30:41 +00006567 ++NumVisibleDeclContextsRead;
6568 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006569 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006570}
6571
6572namespace {
6573 /// \brief ModuleFile visitor used to retrieve all visible names in a
6574 /// declaration context.
6575 class DeclContextAllNamesVisitor {
6576 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006577 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006578 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006579 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006580
6581 public:
6582 DeclContextAllNamesVisitor(ASTReader &Reader,
6583 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006584 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006585 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006586
6587 static bool visit(ModuleFile &M, void *UserData) {
6588 DeclContextAllNamesVisitor *This
6589 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6590
6591 // Check whether we have any visible declaration information for
6592 // this context in this module.
6593 ModuleFile::DeclContextInfosMap::iterator Info;
6594 bool FoundInfo = false;
6595 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6596 Info = M.DeclContextInfos.find(This->Contexts[I]);
6597 if (Info != M.DeclContextInfos.end() &&
6598 Info->second.NameLookupTableData) {
6599 FoundInfo = true;
6600 break;
6601 }
6602 }
6603
6604 if (!FoundInfo)
6605 return false;
6606
Richard Smith52e3fba2014-03-11 07:17:35 +00006607 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 Info->second.NameLookupTableData;
6609 bool FoundAnything = false;
6610 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006611 I = LookupTable->data_begin(), E = LookupTable->data_end();
6612 I != E;
6613 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 ASTDeclContextNameLookupTrait::data_type Data = *I;
6615 for (; Data.first != Data.second; ++Data.first) {
6616 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6617 *Data.first);
6618 if (!ND)
6619 continue;
6620
6621 // Record this declaration.
6622 FoundAnything = true;
6623 This->Decls[ND->getDeclName()].push_back(ND);
6624 }
6625 }
6626
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006627 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 }
6629 };
6630}
6631
6632void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6633 if (!DC->hasExternalVisibleStorage())
6634 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006635 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006636
6637 // Compute the declaration contexts we need to look into. Multiple such
6638 // declaration contexts occur when two declaration contexts from disjoint
6639 // modules get merged, e.g., when two namespaces with the same name are
6640 // independently defined in separate modules.
6641 SmallVector<const DeclContext *, 2> Contexts;
6642 Contexts.push_back(DC);
6643
6644 if (DC->isNamespace()) {
6645 MergedDeclsMap::iterator Merged
6646 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6647 if (Merged != MergedDecls.end()) {
6648 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6649 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6650 }
6651 }
6652
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006653 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6654 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6656 ++NumVisibleDeclContextsRead;
6657
Craig Topper79be4cd2013-07-05 04:33:53 +00006658 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006659 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6660 }
6661 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6662}
6663
6664/// \brief Under non-PCH compilation the consumer receives the objc methods
6665/// before receiving the implementation, and codegen depends on this.
6666/// We simulate this by deserializing and passing to consumer the methods of the
6667/// implementation before passing the deserialized implementation decl.
6668static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6669 ASTConsumer *Consumer) {
6670 assert(ImplD && Consumer);
6671
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006672 for (auto *I : ImplD->methods())
6673 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006674
6675 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6676}
6677
6678void ASTReader::PassInterestingDeclsToConsumer() {
6679 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006680
6681 if (PassingDeclsToConsumer)
6682 return;
6683
6684 // Guard variable to avoid recursively redoing the process of passing
6685 // decls to consumer.
6686 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6687 true);
6688
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 while (!InterestingDecls.empty()) {
6690 Decl *D = InterestingDecls.front();
6691 InterestingDecls.pop_front();
6692
6693 PassInterestingDeclToConsumer(D);
6694 }
6695}
6696
6697void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6698 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6699 PassObjCImplDeclToConsumer(ImplD, Consumer);
6700 else
6701 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6702}
6703
6704void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6705 this->Consumer = Consumer;
6706
6707 if (!Consumer)
6708 return;
6709
Ben Langmuir332aafe2014-01-31 01:06:56 +00006710 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 // Force deserialization of this decl, which will cause it to be queued for
6712 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006713 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006715 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006716
6717 PassInterestingDeclsToConsumer();
6718}
6719
6720void ASTReader::PrintStats() {
6721 std::fprintf(stderr, "*** AST File Statistics:\n");
6722
6723 unsigned NumTypesLoaded
6724 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6725 QualType());
6726 unsigned NumDeclsLoaded
6727 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006728 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006729 unsigned NumIdentifiersLoaded
6730 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6731 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006732 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 unsigned NumMacrosLoaded
6734 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6735 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006736 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 unsigned NumSelectorsLoaded
6738 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6739 SelectorsLoaded.end(),
6740 Selector());
6741
6742 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6743 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6744 NumSLocEntriesRead, TotalNumSLocEntries,
6745 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6746 if (!TypesLoaded.empty())
6747 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6748 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6749 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6750 if (!DeclsLoaded.empty())
6751 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6752 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6753 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6754 if (!IdentifiersLoaded.empty())
6755 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6756 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6757 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6758 if (!MacrosLoaded.empty())
6759 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6760 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6761 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6762 if (!SelectorsLoaded.empty())
6763 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6764 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6765 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6766 if (TotalNumStatements)
6767 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6768 NumStatementsRead, TotalNumStatements,
6769 ((float)NumStatementsRead/TotalNumStatements * 100));
6770 if (TotalNumMacros)
6771 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6772 NumMacrosRead, TotalNumMacros,
6773 ((float)NumMacrosRead/TotalNumMacros * 100));
6774 if (TotalLexicalDeclContexts)
6775 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6776 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6777 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6778 * 100));
6779 if (TotalVisibleDeclContexts)
6780 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6781 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6782 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6783 * 100));
6784 if (TotalNumMethodPoolEntries) {
6785 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6786 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6787 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6788 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006790 if (NumMethodPoolLookups) {
6791 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6792 NumMethodPoolHits, NumMethodPoolLookups,
6793 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6794 }
6795 if (NumMethodPoolTableLookups) {
6796 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6797 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6798 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6799 * 100.0));
6800 }
6801
Douglas Gregor00a50f72013-01-25 00:38:33 +00006802 if (NumIdentifierLookupHits) {
6803 std::fprintf(stderr,
6804 " %u / %u identifier table lookups succeeded (%f%%)\n",
6805 NumIdentifierLookupHits, NumIdentifierLookups,
6806 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6807 }
6808
Douglas Gregore060e572013-01-25 01:03:03 +00006809 if (GlobalIndex) {
6810 std::fprintf(stderr, "\n");
6811 GlobalIndex->printStats();
6812 }
6813
Guy Benyei11169dd2012-12-18 14:30:41 +00006814 std::fprintf(stderr, "\n");
6815 dump();
6816 std::fprintf(stderr, "\n");
6817}
6818
6819template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6820static void
6821dumpModuleIDMap(StringRef Name,
6822 const ContinuousRangeMap<Key, ModuleFile *,
6823 InitialCapacity> &Map) {
6824 if (Map.begin() == Map.end())
6825 return;
6826
6827 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6828 llvm::errs() << Name << ":\n";
6829 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6830 I != IEnd; ++I) {
6831 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6832 << "\n";
6833 }
6834}
6835
6836void ASTReader::dump() {
6837 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6838 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6839 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6840 dumpModuleIDMap("Global type map", GlobalTypeMap);
6841 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6842 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6843 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6844 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6845 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6846 dumpModuleIDMap("Global preprocessed entity map",
6847 GlobalPreprocessedEntityMap);
6848
6849 llvm::errs() << "\n*** PCH/Modules Loaded:";
6850 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6851 MEnd = ModuleMgr.end();
6852 M != MEnd; ++M)
6853 (*M)->dump();
6854}
6855
6856/// Return the amount of memory used by memory buffers, breaking down
6857/// by heap-backed versus mmap'ed memory.
6858void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6859 for (ModuleConstIterator I = ModuleMgr.begin(),
6860 E = ModuleMgr.end(); I != E; ++I) {
6861 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6862 size_t bytes = buf->getBufferSize();
6863 switch (buf->getBufferKind()) {
6864 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6865 sizes.malloc_bytes += bytes;
6866 break;
6867 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6868 sizes.mmap_bytes += bytes;
6869 break;
6870 }
6871 }
6872 }
6873}
6874
6875void ASTReader::InitializeSema(Sema &S) {
6876 SemaObj = &S;
6877 S.addExternalSource(this);
6878
6879 // Makes sure any declarations that were deserialized "too early"
6880 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006881 for (uint64_t ID : PreloadedDeclIDs) {
6882 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6883 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006885 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006886
Richard Smith3d8e97e2013-10-18 06:54:39 +00006887 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006888 if (!FPPragmaOptions.empty()) {
6889 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6890 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6891 }
6892
Richard Smith3d8e97e2013-10-18 06:54:39 +00006893 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 if (!OpenCLExtensions.empty()) {
6895 unsigned I = 0;
6896#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6897#include "clang/Basic/OpenCLExtensions.def"
6898
6899 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6900 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006901
6902 UpdateSema();
6903}
6904
6905void ASTReader::UpdateSema() {
6906 assert(SemaObj && "no Sema to update");
6907
6908 // Load the offsets of the declarations that Sema references.
6909 // They will be lazily deserialized when needed.
6910 if (!SemaDeclRefs.empty()) {
6911 assert(SemaDeclRefs.size() % 2 == 0);
6912 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6913 if (!SemaObj->StdNamespace)
6914 SemaObj->StdNamespace = SemaDeclRefs[I];
6915 if (!SemaObj->StdBadAlloc)
6916 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6917 }
6918 SemaDeclRefs.clear();
6919 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006920
6921 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6922 // encountered the pragma in the source.
6923 if(OptimizeOffPragmaLocation.isValid())
6924 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006925}
6926
6927IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6928 // Note that we are loading an identifier.
6929 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006930 StringRef Name(NameStart, NameEnd - NameStart);
6931
6932 // If there is a global index, look there first to determine which modules
6933 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006934 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006935 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006936 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006937 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6938 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006939 }
6940 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006941 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006942 NumIdentifierLookups,
6943 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006944 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 IdentifierInfo *II = Visitor.getIdentifierInfo();
6946 markIdentifierUpToDate(II);
6947 return II;
6948}
6949
6950namespace clang {
6951 /// \brief An identifier-lookup iterator that enumerates all of the
6952 /// identifiers stored within a set of AST files.
6953 class ASTIdentifierIterator : public IdentifierIterator {
6954 /// \brief The AST reader whose identifiers are being enumerated.
6955 const ASTReader &Reader;
6956
6957 /// \brief The current index into the chain of AST files stored in
6958 /// the AST reader.
6959 unsigned Index;
6960
6961 /// \brief The current position within the identifier lookup table
6962 /// of the current AST file.
6963 ASTIdentifierLookupTable::key_iterator Current;
6964
6965 /// \brief The end position within the identifier lookup table of
6966 /// the current AST file.
6967 ASTIdentifierLookupTable::key_iterator End;
6968
6969 public:
6970 explicit ASTIdentifierIterator(const ASTReader &Reader);
6971
Craig Topper3e89dfe2014-03-13 02:13:41 +00006972 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006973 };
6974}
6975
6976ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6977 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6978 ASTIdentifierLookupTable *IdTable
6979 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6980 Current = IdTable->key_begin();
6981 End = IdTable->key_end();
6982}
6983
6984StringRef ASTIdentifierIterator::Next() {
6985 while (Current == End) {
6986 // If we have exhausted all of our AST files, we're done.
6987 if (Index == 0)
6988 return StringRef();
6989
6990 --Index;
6991 ASTIdentifierLookupTable *IdTable
6992 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6993 IdentifierLookupTable;
6994 Current = IdTable->key_begin();
6995 End = IdTable->key_end();
6996 }
6997
6998 // We have any identifiers remaining in the current AST file; return
6999 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007000 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007001 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007002 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007003}
7004
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007005IdentifierIterator *ASTReader::getIdentifiers() {
7006 if (!loadGlobalIndex())
7007 return GlobalIndex->createIdentifierIterator();
7008
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 return new ASTIdentifierIterator(*this);
7010}
7011
7012namespace clang { namespace serialization {
7013 class ReadMethodPoolVisitor {
7014 ASTReader &Reader;
7015 Selector Sel;
7016 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007017 unsigned InstanceBits;
7018 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007019 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7020 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007021
7022 public:
7023 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7024 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007025 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7026 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00007027
7028 static bool visit(ModuleFile &M, void *UserData) {
7029 ReadMethodPoolVisitor *This
7030 = static_cast<ReadMethodPoolVisitor *>(UserData);
7031
7032 if (!M.SelectorLookupTable)
7033 return false;
7034
7035 // If we've already searched this module file, skip it now.
7036 if (M.Generation <= This->PriorGeneration)
7037 return true;
7038
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007039 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 ASTSelectorLookupTable *PoolTable
7041 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7042 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7043 if (Pos == PoolTable->end())
7044 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007045
7046 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007047 ++This->Reader.NumSelectorsRead;
7048 // FIXME: Not quite happy with the statistics here. We probably should
7049 // disable this tracking when called via LoadSelector.
7050 // Also, should entries without methods count as misses?
7051 ++This->Reader.NumMethodPoolEntriesRead;
7052 ASTSelectorLookupTrait::data_type Data = *Pos;
7053 if (This->Reader.DeserializationListener)
7054 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7055 This->Sel);
7056
7057 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7058 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007059 This->InstanceBits = Data.InstanceBits;
7060 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007061 return true;
7062 }
7063
7064 /// \brief Retrieve the instance methods found by this visitor.
7065 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7066 return InstanceMethods;
7067 }
7068
7069 /// \brief Retrieve the instance methods found by this visitor.
7070 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7071 return FactoryMethods;
7072 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007073
7074 unsigned getInstanceBits() const { return InstanceBits; }
7075 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007076 };
7077} } // end namespace clang::serialization
7078
7079/// \brief Add the given set of methods to the method list.
7080static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7081 ObjCMethodList &List) {
7082 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7083 S.addMethodToGlobalList(&List, Methods[I]);
7084 }
7085}
7086
7087void ASTReader::ReadMethodPool(Selector Sel) {
7088 // Get the selector generation and update it to the current generation.
7089 unsigned &Generation = SelectorGeneration[Sel];
7090 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007091 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007092
7093 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007094 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007095 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7096 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7097
7098 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007099 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007100 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007101
7102 ++NumMethodPoolHits;
7103
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 if (!getSema())
7105 return;
7106
7107 Sema &S = *getSema();
7108 Sema::GlobalMethodPool::iterator Pos
7109 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7110
7111 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7112 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007113 Pos->second.first.setBits(Visitor.getInstanceBits());
7114 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007115}
7116
7117void ASTReader::ReadKnownNamespaces(
7118 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7119 Namespaces.clear();
7120
7121 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7122 if (NamespaceDecl *Namespace
7123 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7124 Namespaces.push_back(Namespace);
7125 }
7126}
7127
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007128void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007129 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007130 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7131 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007132 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007133 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007134 Undefined.insert(std::make_pair(D, Loc));
7135 }
7136}
Nick Lewycky8334af82013-01-26 00:35:08 +00007137
Guy Benyei11169dd2012-12-18 14:30:41 +00007138void ASTReader::ReadTentativeDefinitions(
7139 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7140 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7141 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7142 if (Var)
7143 TentativeDefs.push_back(Var);
7144 }
7145 TentativeDefinitions.clear();
7146}
7147
7148void ASTReader::ReadUnusedFileScopedDecls(
7149 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7150 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7151 DeclaratorDecl *D
7152 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7153 if (D)
7154 Decls.push_back(D);
7155 }
7156 UnusedFileScopedDecls.clear();
7157}
7158
7159void ASTReader::ReadDelegatingConstructors(
7160 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7161 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7162 CXXConstructorDecl *D
7163 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7164 if (D)
7165 Decls.push_back(D);
7166 }
7167 DelegatingCtorDecls.clear();
7168}
7169
7170void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7171 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7172 TypedefNameDecl *D
7173 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7174 if (D)
7175 Decls.push_back(D);
7176 }
7177 ExtVectorDecls.clear();
7178}
7179
7180void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7181 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7182 CXXRecordDecl *D
7183 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7184 if (D)
7185 Decls.push_back(D);
7186 }
7187 DynamicClasses.clear();
7188}
7189
Nico Weber72889432014-09-06 01:25:55 +00007190void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7191 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7192 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7193 ++I) {
7194 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7195 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7196 if (D)
7197 Decls.insert(D);
7198 }
7199 UnusedLocalTypedefNameCandidates.clear();
7200}
7201
Guy Benyei11169dd2012-12-18 14:30:41 +00007202void
Richard Smith78165b52013-01-10 23:43:47 +00007203ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7204 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7205 NamedDecl *D
7206 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007207 if (D)
7208 Decls.push_back(D);
7209 }
Richard Smith78165b52013-01-10 23:43:47 +00007210 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007211}
7212
7213void ASTReader::ReadReferencedSelectors(
7214 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7215 if (ReferencedSelectorsData.empty())
7216 return;
7217
7218 // If there are @selector references added them to its pool. This is for
7219 // implementation of -Wselector.
7220 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7221 unsigned I = 0;
7222 while (I < DataSize) {
7223 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7224 SourceLocation SelLoc
7225 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7226 Sels.push_back(std::make_pair(Sel, SelLoc));
7227 }
7228 ReferencedSelectorsData.clear();
7229}
7230
7231void ASTReader::ReadWeakUndeclaredIdentifiers(
7232 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7233 if (WeakUndeclaredIdentifiers.empty())
7234 return;
7235
7236 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7237 IdentifierInfo *WeakId
7238 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7239 IdentifierInfo *AliasId
7240 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7241 SourceLocation Loc
7242 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7243 bool Used = WeakUndeclaredIdentifiers[I++];
7244 WeakInfo WI(AliasId, Loc);
7245 WI.setUsed(Used);
7246 WeakIDs.push_back(std::make_pair(WeakId, WI));
7247 }
7248 WeakUndeclaredIdentifiers.clear();
7249}
7250
7251void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7252 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7253 ExternalVTableUse VT;
7254 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7255 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7256 VT.DefinitionRequired = VTableUses[Idx++];
7257 VTables.push_back(VT);
7258 }
7259
7260 VTableUses.clear();
7261}
7262
7263void ASTReader::ReadPendingInstantiations(
7264 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7265 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7266 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7267 SourceLocation Loc
7268 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7269
7270 Pending.push_back(std::make_pair(D, Loc));
7271 }
7272 PendingInstantiations.clear();
7273}
7274
Richard Smithe40f2ba2013-08-07 21:41:30 +00007275void ASTReader::ReadLateParsedTemplates(
7276 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7277 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7278 /* In loop */) {
7279 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7280
7281 LateParsedTemplate *LT = new LateParsedTemplate;
7282 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7283
7284 ModuleFile *F = getOwningModuleFile(LT->D);
7285 assert(F && "No module");
7286
7287 unsigned TokN = LateParsedTemplates[Idx++];
7288 LT->Toks.reserve(TokN);
7289 for (unsigned T = 0; T < TokN; ++T)
7290 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7291
7292 LPTMap[FD] = LT;
7293 }
7294
7295 LateParsedTemplates.clear();
7296}
7297
Guy Benyei11169dd2012-12-18 14:30:41 +00007298void ASTReader::LoadSelector(Selector Sel) {
7299 // It would be complicated to avoid reading the methods anyway. So don't.
7300 ReadMethodPool(Sel);
7301}
7302
7303void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7304 assert(ID && "Non-zero identifier ID required");
7305 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7306 IdentifiersLoaded[ID - 1] = II;
7307 if (DeserializationListener)
7308 DeserializationListener->IdentifierRead(ID, II);
7309}
7310
7311/// \brief Set the globally-visible declarations associated with the given
7312/// identifier.
7313///
7314/// If the AST reader is currently in a state where the given declaration IDs
7315/// cannot safely be resolved, they are queued until it is safe to resolve
7316/// them.
7317///
7318/// \param II an IdentifierInfo that refers to one or more globally-visible
7319/// declarations.
7320///
7321/// \param DeclIDs the set of declaration IDs with the name @p II that are
7322/// visible at global scope.
7323///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007324/// \param Decls if non-null, this vector will be populated with the set of
7325/// deserialized declarations. These declarations will not be pushed into
7326/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007327void
7328ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7329 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007330 SmallVectorImpl<Decl *> *Decls) {
7331 if (NumCurrentElementsDeserializing && !Decls) {
7332 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 return;
7334 }
7335
7336 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007337 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007338 // Queue this declaration so that it will be added to the
7339 // translation unit scope and identifier's declaration chain
7340 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007341 PreloadedDeclIDs.push_back(DeclIDs[I]);
7342 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007344
7345 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7346
7347 // If we're simply supposed to record the declarations, do so now.
7348 if (Decls) {
7349 Decls->push_back(D);
7350 continue;
7351 }
7352
7353 // Introduce this declaration into the translation-unit scope
7354 // and add it to the declaration chain for this identifier, so
7355 // that (unqualified) name lookup will find it.
7356 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007357 }
7358}
7359
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007360IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007361 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007362 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007363
7364 if (IdentifiersLoaded.empty()) {
7365 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007366 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 }
7368
7369 ID -= 1;
7370 if (!IdentifiersLoaded[ID]) {
7371 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7372 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7373 ModuleFile *M = I->second;
7374 unsigned Index = ID - M->BaseIdentifierID;
7375 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7376
7377 // All of the strings in the AST file are preceded by a 16-bit length.
7378 // Extract that 16-bit length to avoid having to execute strlen().
7379 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7380 // unsigned integers. This is important to avoid integer overflow when
7381 // we cast them to 'unsigned'.
7382 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7383 unsigned StrLen = (((unsigned) StrLenPtr[0])
7384 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007385 IdentifiersLoaded[ID]
7386 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 if (DeserializationListener)
7388 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7389 }
7390
7391 return IdentifiersLoaded[ID];
7392}
7393
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007394IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7395 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007396}
7397
7398IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7399 if (LocalID < NUM_PREDEF_IDENT_IDS)
7400 return LocalID;
7401
7402 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7403 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7404 assert(I != M.IdentifierRemap.end()
7405 && "Invalid index into identifier index remap");
7406
7407 return LocalID + I->second;
7408}
7409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007410MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007412 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007413
7414 if (MacrosLoaded.empty()) {
7415 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007416 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 }
7418
7419 ID -= NUM_PREDEF_MACRO_IDS;
7420 if (!MacrosLoaded[ID]) {
7421 GlobalMacroMapType::iterator I
7422 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7423 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7424 ModuleFile *M = I->second;
7425 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007426 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7427
7428 if (DeserializationListener)
7429 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7430 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 }
7432
7433 return MacrosLoaded[ID];
7434}
7435
7436MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7437 if (LocalID < NUM_PREDEF_MACRO_IDS)
7438 return LocalID;
7439
7440 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7441 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7442 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7443
7444 return LocalID + I->second;
7445}
7446
7447serialization::SubmoduleID
7448ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7449 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7450 return LocalID;
7451
7452 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7453 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7454 assert(I != M.SubmoduleRemap.end()
7455 && "Invalid index into submodule index remap");
7456
7457 return LocalID + I->second;
7458}
7459
7460Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7461 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7462 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007463 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 }
7465
7466 if (GlobalID > SubmodulesLoaded.size()) {
7467 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007468 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 }
7470
7471 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7472}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007473
7474Module *ASTReader::getModule(unsigned ID) {
7475 return getSubmodule(ID);
7476}
7477
Guy Benyei11169dd2012-12-18 14:30:41 +00007478Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7479 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7480}
7481
7482Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7483 if (ID == 0)
7484 return Selector();
7485
7486 if (ID > SelectorsLoaded.size()) {
7487 Error("selector ID out of range in AST file");
7488 return Selector();
7489 }
7490
Craig Toppera13603a2014-05-22 05:54:18 +00007491 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 // Load this selector from the selector table.
7493 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7494 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7495 ModuleFile &M = *I->second;
7496 ASTSelectorLookupTrait Trait(*this, M);
7497 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7498 SelectorsLoaded[ID - 1] =
7499 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7500 if (DeserializationListener)
7501 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7502 }
7503
7504 return SelectorsLoaded[ID - 1];
7505}
7506
7507Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7508 return DecodeSelector(ID);
7509}
7510
7511uint32_t ASTReader::GetNumExternalSelectors() {
7512 // ID 0 (the null selector) is considered an external selector.
7513 return getTotalNumSelectors() + 1;
7514}
7515
7516serialization::SelectorID
7517ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7518 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7519 return LocalID;
7520
7521 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7522 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7523 assert(I != M.SelectorRemap.end()
7524 && "Invalid index into selector index remap");
7525
7526 return LocalID + I->second;
7527}
7528
7529DeclarationName
7530ASTReader::ReadDeclarationName(ModuleFile &F,
7531 const RecordData &Record, unsigned &Idx) {
7532 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7533 switch (Kind) {
7534 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007535 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007536
7537 case DeclarationName::ObjCZeroArgSelector:
7538 case DeclarationName::ObjCOneArgSelector:
7539 case DeclarationName::ObjCMultiArgSelector:
7540 return DeclarationName(ReadSelector(F, Record, Idx));
7541
7542 case DeclarationName::CXXConstructorName:
7543 return Context.DeclarationNames.getCXXConstructorName(
7544 Context.getCanonicalType(readType(F, Record, Idx)));
7545
7546 case DeclarationName::CXXDestructorName:
7547 return Context.DeclarationNames.getCXXDestructorName(
7548 Context.getCanonicalType(readType(F, Record, Idx)));
7549
7550 case DeclarationName::CXXConversionFunctionName:
7551 return Context.DeclarationNames.getCXXConversionFunctionName(
7552 Context.getCanonicalType(readType(F, Record, Idx)));
7553
7554 case DeclarationName::CXXOperatorName:
7555 return Context.DeclarationNames.getCXXOperatorName(
7556 (OverloadedOperatorKind)Record[Idx++]);
7557
7558 case DeclarationName::CXXLiteralOperatorName:
7559 return Context.DeclarationNames.getCXXLiteralOperatorName(
7560 GetIdentifierInfo(F, Record, Idx));
7561
7562 case DeclarationName::CXXUsingDirective:
7563 return DeclarationName::getUsingDirectiveName();
7564 }
7565
7566 llvm_unreachable("Invalid NameKind!");
7567}
7568
7569void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7570 DeclarationNameLoc &DNLoc,
7571 DeclarationName Name,
7572 const RecordData &Record, unsigned &Idx) {
7573 switch (Name.getNameKind()) {
7574 case DeclarationName::CXXConstructorName:
7575 case DeclarationName::CXXDestructorName:
7576 case DeclarationName::CXXConversionFunctionName:
7577 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7578 break;
7579
7580 case DeclarationName::CXXOperatorName:
7581 DNLoc.CXXOperatorName.BeginOpNameLoc
7582 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7583 DNLoc.CXXOperatorName.EndOpNameLoc
7584 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7585 break;
7586
7587 case DeclarationName::CXXLiteralOperatorName:
7588 DNLoc.CXXLiteralOperatorName.OpNameLoc
7589 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7590 break;
7591
7592 case DeclarationName::Identifier:
7593 case DeclarationName::ObjCZeroArgSelector:
7594 case DeclarationName::ObjCOneArgSelector:
7595 case DeclarationName::ObjCMultiArgSelector:
7596 case DeclarationName::CXXUsingDirective:
7597 break;
7598 }
7599}
7600
7601void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7602 DeclarationNameInfo &NameInfo,
7603 const RecordData &Record, unsigned &Idx) {
7604 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7605 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7606 DeclarationNameLoc DNLoc;
7607 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7608 NameInfo.setInfo(DNLoc);
7609}
7610
7611void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7612 const RecordData &Record, unsigned &Idx) {
7613 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7614 unsigned NumTPLists = Record[Idx++];
7615 Info.NumTemplParamLists = NumTPLists;
7616 if (NumTPLists) {
7617 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7618 for (unsigned i=0; i != NumTPLists; ++i)
7619 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7620 }
7621}
7622
7623TemplateName
7624ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7625 unsigned &Idx) {
7626 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7627 switch (Kind) {
7628 case TemplateName::Template:
7629 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7630
7631 case TemplateName::OverloadedTemplate: {
7632 unsigned size = Record[Idx++];
7633 UnresolvedSet<8> Decls;
7634 while (size--)
7635 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7636
7637 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7638 }
7639
7640 case TemplateName::QualifiedTemplate: {
7641 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7642 bool hasTemplKeyword = Record[Idx++];
7643 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7644 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7645 }
7646
7647 case TemplateName::DependentTemplate: {
7648 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7649 if (Record[Idx++]) // isIdentifier
7650 return Context.getDependentTemplateName(NNS,
7651 GetIdentifierInfo(F, Record,
7652 Idx));
7653 return Context.getDependentTemplateName(NNS,
7654 (OverloadedOperatorKind)Record[Idx++]);
7655 }
7656
7657 case TemplateName::SubstTemplateTemplateParm: {
7658 TemplateTemplateParmDecl *param
7659 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7660 if (!param) return TemplateName();
7661 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7662 return Context.getSubstTemplateTemplateParm(param, replacement);
7663 }
7664
7665 case TemplateName::SubstTemplateTemplateParmPack: {
7666 TemplateTemplateParmDecl *Param
7667 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7668 if (!Param)
7669 return TemplateName();
7670
7671 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7672 if (ArgPack.getKind() != TemplateArgument::Pack)
7673 return TemplateName();
7674
7675 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7676 }
7677 }
7678
7679 llvm_unreachable("Unhandled template name kind!");
7680}
7681
7682TemplateArgument
7683ASTReader::ReadTemplateArgument(ModuleFile &F,
7684 const RecordData &Record, unsigned &Idx) {
7685 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7686 switch (Kind) {
7687 case TemplateArgument::Null:
7688 return TemplateArgument();
7689 case TemplateArgument::Type:
7690 return TemplateArgument(readType(F, Record, Idx));
7691 case TemplateArgument::Declaration: {
7692 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007693 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 }
7695 case TemplateArgument::NullPtr:
7696 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7697 case TemplateArgument::Integral: {
7698 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7699 QualType T = readType(F, Record, Idx);
7700 return TemplateArgument(Context, Value, T);
7701 }
7702 case TemplateArgument::Template:
7703 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7704 case TemplateArgument::TemplateExpansion: {
7705 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007706 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 if (unsigned NumExpansions = Record[Idx++])
7708 NumTemplateExpansions = NumExpansions - 1;
7709 return TemplateArgument(Name, NumTemplateExpansions);
7710 }
7711 case TemplateArgument::Expression:
7712 return TemplateArgument(ReadExpr(F));
7713 case TemplateArgument::Pack: {
7714 unsigned NumArgs = Record[Idx++];
7715 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7716 for (unsigned I = 0; I != NumArgs; ++I)
7717 Args[I] = ReadTemplateArgument(F, Record, Idx);
7718 return TemplateArgument(Args, NumArgs);
7719 }
7720 }
7721
7722 llvm_unreachable("Unhandled template argument kind!");
7723}
7724
7725TemplateParameterList *
7726ASTReader::ReadTemplateParameterList(ModuleFile &F,
7727 const RecordData &Record, unsigned &Idx) {
7728 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7729 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7730 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7731
7732 unsigned NumParams = Record[Idx++];
7733 SmallVector<NamedDecl *, 16> Params;
7734 Params.reserve(NumParams);
7735 while (NumParams--)
7736 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7737
7738 TemplateParameterList* TemplateParams =
7739 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7740 Params.data(), Params.size(), RAngleLoc);
7741 return TemplateParams;
7742}
7743
7744void
7745ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007746ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007747 ModuleFile &F, const RecordData &Record,
7748 unsigned &Idx) {
7749 unsigned NumTemplateArgs = Record[Idx++];
7750 TemplArgs.reserve(NumTemplateArgs);
7751 while (NumTemplateArgs--)
7752 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7753}
7754
7755/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007756void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007757 const RecordData &Record, unsigned &Idx) {
7758 unsigned NumDecls = Record[Idx++];
7759 Set.reserve(Context, NumDecls);
7760 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007761 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007762 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007763 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007764 }
7765}
7766
7767CXXBaseSpecifier
7768ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7769 const RecordData &Record, unsigned &Idx) {
7770 bool isVirtual = static_cast<bool>(Record[Idx++]);
7771 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7772 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7773 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7774 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7775 SourceRange Range = ReadSourceRange(F, Record, Idx);
7776 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7777 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7778 EllipsisLoc);
7779 Result.setInheritConstructors(inheritConstructors);
7780 return Result;
7781}
7782
7783std::pair<CXXCtorInitializer **, unsigned>
7784ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7785 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007786 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 unsigned NumInitializers = Record[Idx++];
7788 if (NumInitializers) {
7789 CtorInitializers
7790 = new (Context) CXXCtorInitializer*[NumInitializers];
7791 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007792 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007794 FieldDecl *Member = nullptr;
7795 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007796
7797 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7798 switch (Type) {
7799 case CTOR_INITIALIZER_BASE:
7800 TInfo = GetTypeSourceInfo(F, Record, Idx);
7801 IsBaseVirtual = Record[Idx++];
7802 break;
7803
7804 case CTOR_INITIALIZER_DELEGATING:
7805 TInfo = GetTypeSourceInfo(F, Record, Idx);
7806 break;
7807
7808 case CTOR_INITIALIZER_MEMBER:
7809 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7810 break;
7811
7812 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7813 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7814 break;
7815 }
7816
7817 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7818 Expr *Init = ReadExpr(F);
7819 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7820 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7821 bool IsWritten = Record[Idx++];
7822 unsigned SourceOrderOrNumArrayIndices;
7823 SmallVector<VarDecl *, 8> Indices;
7824 if (IsWritten) {
7825 SourceOrderOrNumArrayIndices = Record[Idx++];
7826 } else {
7827 SourceOrderOrNumArrayIndices = Record[Idx++];
7828 Indices.reserve(SourceOrderOrNumArrayIndices);
7829 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7830 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7831 }
7832
7833 CXXCtorInitializer *BOMInit;
7834 if (Type == CTOR_INITIALIZER_BASE) {
7835 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7836 LParenLoc, Init, RParenLoc,
7837 MemberOrEllipsisLoc);
7838 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7839 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7840 Init, RParenLoc);
7841 } else if (IsWritten) {
7842 if (Member)
7843 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7844 LParenLoc, Init, RParenLoc);
7845 else
7846 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7847 MemberOrEllipsisLoc, LParenLoc,
7848 Init, RParenLoc);
7849 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007850 if (IndirectMember) {
7851 assert(Indices.empty() && "Indirect field improperly initialized");
7852 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7853 MemberOrEllipsisLoc, LParenLoc,
7854 Init, RParenLoc);
7855 } else {
7856 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7857 LParenLoc, Init, RParenLoc,
7858 Indices.data(), Indices.size());
7859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 }
7861
7862 if (IsWritten)
7863 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7864 CtorInitializers[i] = BOMInit;
7865 }
7866 }
7867
7868 return std::make_pair(CtorInitializers, NumInitializers);
7869}
7870
7871NestedNameSpecifier *
7872ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7873 const RecordData &Record, unsigned &Idx) {
7874 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007875 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 for (unsigned I = 0; I != N; ++I) {
7877 NestedNameSpecifier::SpecifierKind Kind
7878 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7879 switch (Kind) {
7880 case NestedNameSpecifier::Identifier: {
7881 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7882 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7883 break;
7884 }
7885
7886 case NestedNameSpecifier::Namespace: {
7887 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7888 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7889 break;
7890 }
7891
7892 case NestedNameSpecifier::NamespaceAlias: {
7893 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7894 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7895 break;
7896 }
7897
7898 case NestedNameSpecifier::TypeSpec:
7899 case NestedNameSpecifier::TypeSpecWithTemplate: {
7900 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7901 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007902 return nullptr;
7903
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 bool Template = Record[Idx++];
7905 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7906 break;
7907 }
7908
7909 case NestedNameSpecifier::Global: {
7910 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7911 // No associated value, and there can't be a prefix.
7912 break;
7913 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007914
7915 case NestedNameSpecifier::Super: {
7916 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7917 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7918 break;
7919 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007920 }
7921 Prev = NNS;
7922 }
7923 return NNS;
7924}
7925
7926NestedNameSpecifierLoc
7927ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7928 unsigned &Idx) {
7929 unsigned N = Record[Idx++];
7930 NestedNameSpecifierLocBuilder Builder;
7931 for (unsigned I = 0; I != N; ++I) {
7932 NestedNameSpecifier::SpecifierKind Kind
7933 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7934 switch (Kind) {
7935 case NestedNameSpecifier::Identifier: {
7936 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7937 SourceRange Range = ReadSourceRange(F, Record, Idx);
7938 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7939 break;
7940 }
7941
7942 case NestedNameSpecifier::Namespace: {
7943 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7944 SourceRange Range = ReadSourceRange(F, Record, Idx);
7945 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7946 break;
7947 }
7948
7949 case NestedNameSpecifier::NamespaceAlias: {
7950 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7951 SourceRange Range = ReadSourceRange(F, Record, Idx);
7952 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7953 break;
7954 }
7955
7956 case NestedNameSpecifier::TypeSpec:
7957 case NestedNameSpecifier::TypeSpecWithTemplate: {
7958 bool Template = Record[Idx++];
7959 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7960 if (!T)
7961 return NestedNameSpecifierLoc();
7962 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7963
7964 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7965 Builder.Extend(Context,
7966 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7967 T->getTypeLoc(), ColonColonLoc);
7968 break;
7969 }
7970
7971 case NestedNameSpecifier::Global: {
7972 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7973 Builder.MakeGlobal(Context, ColonColonLoc);
7974 break;
7975 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007976
7977 case NestedNameSpecifier::Super: {
7978 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7979 SourceRange Range = ReadSourceRange(F, Record, Idx);
7980 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7981 break;
7982 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 }
7984 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007985
Guy Benyei11169dd2012-12-18 14:30:41 +00007986 return Builder.getWithLocInContext(Context);
7987}
7988
7989SourceRange
7990ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7991 unsigned &Idx) {
7992 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7993 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7994 return SourceRange(beg, end);
7995}
7996
7997/// \brief Read an integral value
7998llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7999 unsigned BitWidth = Record[Idx++];
8000 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8001 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8002 Idx += NumWords;
8003 return Result;
8004}
8005
8006/// \brief Read a signed integral value
8007llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8008 bool isUnsigned = Record[Idx++];
8009 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8010}
8011
8012/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008013llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8014 const llvm::fltSemantics &Sem,
8015 unsigned &Idx) {
8016 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008017}
8018
8019// \brief Read a string
8020std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8021 unsigned Len = Record[Idx++];
8022 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8023 Idx += Len;
8024 return Result;
8025}
8026
8027VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8028 unsigned &Idx) {
8029 unsigned Major = Record[Idx++];
8030 unsigned Minor = Record[Idx++];
8031 unsigned Subminor = Record[Idx++];
8032 if (Minor == 0)
8033 return VersionTuple(Major);
8034 if (Subminor == 0)
8035 return VersionTuple(Major, Minor - 1);
8036 return VersionTuple(Major, Minor - 1, Subminor - 1);
8037}
8038
8039CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8040 const RecordData &Record,
8041 unsigned &Idx) {
8042 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8043 return CXXTemporary::Create(Context, Decl);
8044}
8045
8046DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008047 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008048}
8049
8050DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8051 return Diags.Report(Loc, DiagID);
8052}
8053
8054/// \brief Retrieve the identifier table associated with the
8055/// preprocessor.
8056IdentifierTable &ASTReader::getIdentifierTable() {
8057 return PP.getIdentifierTable();
8058}
8059
8060/// \brief Record that the given ID maps to the given switch-case
8061/// statement.
8062void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008063 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 "Already have a SwitchCase with this ID");
8065 (*CurrSwitchCaseStmts)[ID] = SC;
8066}
8067
8068/// \brief Retrieve the switch-case statement with the given ID.
8069SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008070 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 return (*CurrSwitchCaseStmts)[ID];
8072}
8073
8074void ASTReader::ClearSwitchCaseIDs() {
8075 CurrSwitchCaseStmts->clear();
8076}
8077
8078void ASTReader::ReadComments() {
8079 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008080 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008081 serialization::ModuleFile *> >::iterator
8082 I = CommentsCursors.begin(),
8083 E = CommentsCursors.end();
8084 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008085 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008086 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008087 serialization::ModuleFile &F = *I->second;
8088 SavedStreamPosition SavedPosition(Cursor);
8089
8090 RecordData Record;
8091 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008092 llvm::BitstreamEntry Entry =
8093 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008094
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008095 switch (Entry.Kind) {
8096 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8097 case llvm::BitstreamEntry::Error:
8098 Error("malformed block record in AST file");
8099 return;
8100 case llvm::BitstreamEntry::EndBlock:
8101 goto NextCursor;
8102 case llvm::BitstreamEntry::Record:
8103 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 }
8106
8107 // Read a record.
8108 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008109 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008110 case COMMENTS_RAW_COMMENT: {
8111 unsigned Idx = 0;
8112 SourceRange SR = ReadSourceRange(F, Record, Idx);
8113 RawComment::CommentKind Kind =
8114 (RawComment::CommentKind) Record[Idx++];
8115 bool IsTrailingComment = Record[Idx++];
8116 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008117 Comments.push_back(new (Context) RawComment(
8118 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8119 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 break;
8121 }
8122 }
8123 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008124 NextCursor:
8125 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008127}
8128
Richard Smithcd45dbc2014-04-19 03:48:30 +00008129std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8130 // If we know the owning module, use it.
8131 if (Module *M = D->getOwningModule())
8132 return M->getFullModuleName();
8133
8134 // Otherwise, use the name of the top-level module the decl is within.
8135 if (ModuleFile *M = getOwningModuleFile(D))
8136 return M->ModuleName;
8137
8138 // Not from a module.
8139 return "";
8140}
8141
Guy Benyei11169dd2012-12-18 14:30:41 +00008142void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008143 while (!PendingIdentifierInfos.empty() ||
8144 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008145 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008146 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 // If any identifiers with corresponding top-level declarations have
8148 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008149 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8150 TopLevelDeclsMap;
8151 TopLevelDeclsMap TopLevelDecls;
8152
Guy Benyei11169dd2012-12-18 14:30:41 +00008153 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008154 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008155 SmallVector<uint32_t, 4> DeclIDs =
8156 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008157 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008158
8159 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008160 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008161
Richard Smith851072e2014-05-19 20:59:20 +00008162 // For each decl chain that we wanted to complete while deserializing, mark
8163 // it as "still needs to be completed".
8164 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8165 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8166 }
8167 PendingIncompleteDeclChains.clear();
8168
Guy Benyei11169dd2012-12-18 14:30:41 +00008169 // Load pending declaration chains.
8170 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8171 loadPendingDeclChain(PendingDeclChains[I]);
8172 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8173 }
8174 PendingDeclChains.clear();
8175
Douglas Gregor6168bd22013-02-18 15:53:43 +00008176 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008177 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8178 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008179 IdentifierInfo *II = TLD->first;
8180 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008181 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008182 }
8183 }
8184
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 // Load any pending macro definitions.
8186 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008187 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8188 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8189 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8190 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008191 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008192 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008193 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8194 if (Info.M->Kind != MK_Module)
8195 resolvePendingMacro(II, Info);
8196 }
8197 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008198 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008199 ++IDIdx) {
8200 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8201 if (Info.M->Kind == MK_Module)
8202 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 }
8204 }
8205 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008206
8207 // Wire up the DeclContexts for Decls that we delayed setting until
8208 // recursive loading is completed.
8209 while (!PendingDeclContextInfos.empty()) {
8210 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8211 PendingDeclContextInfos.pop_front();
8212 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8213 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8214 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8215 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008216
Richard Smithd1c46742014-04-30 02:24:17 +00008217 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008218 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008219 auto Update = PendingUpdateRecords.pop_back_val();
8220 ReadingKindTracker ReadingKind(Read_Decl, *this);
8221 loadDeclUpdateRecords(Update.first, Update.second);
8222 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 }
8224
8225 // If we deserialized any C++ or Objective-C class definitions, any
8226 // Objective-C protocol definitions, or any redeclarable templates, make sure
8227 // that all redeclarations point to the definitions. Note that this can only
8228 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008229 for (Decl *D : PendingDefinitions) {
8230 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008231 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 // Make sure that the TagType points at the definition.
8233 const_cast<TagType*>(TagT)->decl = TD;
8234 }
8235
Craig Topperc6914d02014-08-25 04:15:02 +00008236 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008237 for (auto R : RD->redecls()) {
8238 assert((R == D) == R->isThisDeclarationADefinition() &&
8239 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008240 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 }
8243
8244 continue;
8245 }
8246
Craig Topperc6914d02014-08-25 04:15:02 +00008247 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 // Make sure that the ObjCInterfaceType points at the definition.
8249 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8250 ->Decl = ID;
8251
Aaron Ballman86c93902014-03-06 23:45:36 +00008252 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008253 R->Data = ID->Data;
8254
8255 continue;
8256 }
8257
Craig Topperc6914d02014-08-25 04:15:02 +00008258 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008259 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008260 R->Data = PD->Data;
8261
8262 continue;
8263 }
8264
Craig Topperc6914d02014-08-25 04:15:02 +00008265 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008266 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008267 R->Common = RTD->Common;
8268 }
8269 PendingDefinitions.clear();
8270
8271 // Load the bodies of any functions or methods we've encountered. We do
8272 // this now (delayed) so that we can be sure that the declaration chains
8273 // have been fully wired up.
8274 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8275 PBEnd = PendingBodies.end();
8276 PB != PBEnd; ++PB) {
8277 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8278 // FIXME: Check for =delete/=default?
8279 // FIXME: Complain about ODR violations here?
8280 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8281 FD->setLazyBody(PB->second);
8282 continue;
8283 }
8284
8285 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8286 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8287 MD->setLazyBody(PB->second);
8288 }
8289 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008290}
8291
8292void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008293 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8294 return;
8295
Richard Smitha0ce9c42014-07-29 23:23:27 +00008296 // Trigger the import of the full definition of each class that had any
8297 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008298 // These updates may in turn find and diagnose some ODR failures, so take
8299 // ownership of the set first.
8300 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8301 PendingOdrMergeFailures.clear();
8302 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008303 Merge.first->buildLookup();
8304 Merge.first->decls_begin();
8305 Merge.first->bases_begin();
8306 Merge.first->vbases_begin();
8307 for (auto *RD : Merge.second) {
8308 RD->decls_begin();
8309 RD->bases_begin();
8310 RD->vbases_begin();
8311 }
8312 }
8313
8314 // For each declaration from a merged context, check that the canonical
8315 // definition of that context also contains a declaration of the same
8316 // entity.
8317 //
8318 // Caution: this loop does things that might invalidate iterators into
8319 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8320 while (!PendingOdrMergeChecks.empty()) {
8321 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8322
8323 // FIXME: Skip over implicit declarations for now. This matters for things
8324 // like implicitly-declared special member functions. This isn't entirely
8325 // correct; we can end up with multiple unmerged declarations of the same
8326 // implicit entity.
8327 if (D->isImplicit())
8328 continue;
8329
8330 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008331
8332 bool Found = false;
8333 const Decl *DCanon = D->getCanonicalDecl();
8334
Richard Smith01bdb7a2014-08-28 05:44:07 +00008335 for (auto RI : D->redecls()) {
8336 if (RI->getLexicalDeclContext() == CanonDef) {
8337 Found = true;
8338 break;
8339 }
8340 }
8341 if (Found)
8342 continue;
8343
Richard Smitha0ce9c42014-07-29 23:23:27 +00008344 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008345 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008346 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8347 !Found && I != E; ++I) {
8348 for (auto RI : (*I)->redecls()) {
8349 if (RI->getLexicalDeclContext() == CanonDef) {
8350 // This declaration is present in the canonical definition. If it's
8351 // in the same redecl chain, it's the one we're looking for.
8352 if (RI->getCanonicalDecl() == DCanon)
8353 Found = true;
8354 else
8355 Candidates.push_back(cast<NamedDecl>(RI));
8356 break;
8357 }
8358 }
8359 }
8360
8361 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008362 // The AST doesn't like TagDecls becoming invalid after they've been
8363 // completed. We only really need to mark FieldDecls as invalid here.
8364 if (!isa<TagDecl>(D))
8365 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008366
8367 std::string CanonDefModule =
8368 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8369 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8370 << D << getOwningModuleNameForDiagnostic(D)
8371 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8372
8373 if (Candidates.empty())
8374 Diag(cast<Decl>(CanonDef)->getLocation(),
8375 diag::note_module_odr_violation_no_possible_decls) << D;
8376 else {
8377 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8378 Diag(Candidates[I]->getLocation(),
8379 diag::note_module_odr_violation_possible_decl)
8380 << Candidates[I];
8381 }
8382
8383 DiagnosedOdrMergeFailures.insert(CanonDef);
8384 }
8385 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008386
8387 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008388 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008389 // If we've already pointed out a specific problem with this class, don't
8390 // bother issuing a general "something's different" diagnostic.
Richard Smithcd45dbc2014-04-19 03:48:30 +00008391 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8392 continue;
8393
8394 bool Diagnosed = false;
8395 for (auto *RD : Merge.second) {
8396 // Multiple different declarations got merged together; tell the user
8397 // where they came from.
8398 if (Merge.first != RD) {
8399 // FIXME: Walk the definition, figure out what's different,
8400 // and diagnose that.
8401 if (!Diagnosed) {
8402 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8403 Diag(Merge.first->getLocation(),
8404 diag::err_module_odr_violation_different_definitions)
8405 << Merge.first << Module.empty() << Module;
8406 Diagnosed = true;
8407 }
8408
8409 Diag(RD->getLocation(),
8410 diag::note_module_odr_violation_different_definitions)
8411 << getOwningModuleNameForDiagnostic(RD);
8412 }
8413 }
8414
8415 if (!Diagnosed) {
8416 // All definitions are updates to the same declaration. This happens if a
8417 // module instantiates the declaration of a class template specialization
8418 // and two or more other modules instantiate its definition.
8419 //
8420 // FIXME: Indicate which modules had instantiations of this definition.
8421 // FIXME: How can this even happen?
8422 Diag(Merge.first->getLocation(),
8423 diag::err_module_odr_violation_different_instantiations)
8424 << Merge.first;
8425 }
8426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008427}
8428
8429void ASTReader::FinishedDeserializing() {
8430 assert(NumCurrentElementsDeserializing &&
8431 "FinishedDeserializing not paired with StartedDeserializing");
8432 if (NumCurrentElementsDeserializing == 1) {
8433 // We decrease NumCurrentElementsDeserializing only after pending actions
8434 // are finished, to avoid recursively re-calling finishPendingActions().
8435 finishPendingActions();
8436 }
8437 --NumCurrentElementsDeserializing;
8438
Richard Smitha0ce9c42014-07-29 23:23:27 +00008439 if (NumCurrentElementsDeserializing == 0) {
8440 diagnoseOdrViolations();
8441
Richard Smith04d05b52014-03-23 00:27:18 +00008442 // We are not in recursive loading, so it's safe to pass the "interesting"
8443 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008444 if (Consumer)
8445 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 }
8447}
8448
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008449void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008450 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008451
8452 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8453 SemaObj->TUScope->AddDecl(D);
8454 } else if (SemaObj->TUScope) {
8455 // Adding the decl to IdResolver may have failed because it was already in
8456 // (even though it was not added in scope). If it is already in, make sure
8457 // it gets in the scope as well.
8458 if (std::find(SemaObj->IdResolver.begin(Name),
8459 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8460 SemaObj->TUScope->AddDecl(D);
8461 }
8462}
8463
Nico Weber824285e2014-05-08 04:26:47 +00008464ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8465 bool DisableValidation, bool AllowASTWithCompilerErrors,
8466 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008467 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008468 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008469 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008470 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8471 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8472 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8473 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008474 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8475 AllowConfigurationMismatch(AllowConfigurationMismatch),
8476 ValidateSystemInputs(ValidateSystemInputs),
8477 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008478 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008479 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8480 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8481 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8482 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8483 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8484 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8485 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8486 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8487 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8488 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8489 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 SourceMgr.setExternalSLocEntrySource(this);
8491}
8492
8493ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008494 if (OwnsDeserializationListener)
8495 delete DeserializationListener;
8496
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 for (DeclContextVisibleUpdatesPending::iterator
8498 I = PendingVisibleUpdates.begin(),
8499 E = PendingVisibleUpdates.end();
8500 I != E; ++I) {
8501 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8502 F = I->second.end();
8503 J != F; ++J)
8504 delete J->first;
8505 }
8506}